Using Fontsource in Svelte
Notes on adding custom fonts in Svelte.
Fontsource is a collection of open-source fonts that are packaged into individual NPM packages for self-hosting in your web apps.
Fontsource packages are handled by SvelteKit’s Vite build, keeping the font files self-hosted and versioned with the rest of your application.
The next question is whether to use static or variable fonts.
Variable fonts are generally preferred because they offer greater design flexibility and better performance while reducing the need for multiple font files.
1. Install the Font
To use a variable font with Fontsource, install the corresponding variable font package.
pnpm add -D @fontsource-variable/inter 2. Import it from the root layout
Import the font in src/routes/+layout.svelte:
import "@fontsource-variable/inter"; All weights from 100 to 900 are available. Unicode ranges also allow the browser to fetch only the characters it needs.
<script>
+ import "@fontsource-variable/inter";
let { children } = $props();
</script>
{@render children()}
+<style>
+ :global(body) {
+ margin: 0;
+ font-family: "Inter Variable", sans-serif;
+ }
+</style> This makes the font available across every page. To limit a font to one section
of the application, import it from that route’s +layout.svelte instead.
3. Preload Fonts
SvelteKit provides a built-in preload filter through the handle hook, allowing
us to control which assets are preloaded. By default, SvelteKit preloads JavaScript & CSS files, but we can extend this behavior to include fonts.
Create a hooks.server.js file inside src to configure font preloading.
/src/hooks.server.js
/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
return resolve(event, {
preload: ({ type }) => {
return type === "font" || type === "js" || type === "css";
},
});
} Using a blanket font preload filter (type === "font") can be counterproductive.
Rather than improving page load performance, it may cause the browser to preload
every available font subset, adding unnecessary network overhead for fonts your
app might never use.
Instead, preload only the font subsets your app actually needs.
/src/hooks.server.js
/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
return resolve(event, {
preload: ({ type, filename }) => {
if (type === "font") {
return filename?.includes("latin-wght") ?? false;
}
return type === "js" || type === "css";
},
});
} Now, SvelteKit will preload only font files matching latin-wght, while
continuing to preload JavaScript and CSS as usual.
The browser will still fetch other subsets on demand when the corresponding characters appear on the page.
For better performance and faster page loads, you can subset fonts to include only the characters you need.
> cd ..