🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Styling••By Komal Nakrani

Astro Fonts API Explained: Providers, Preloads, Fallbacks

The Astro Fonts API explained: configure fonts in astro.config.mjs, use Google, Fontsource or local files, add the Font component, preload and tune fallbacks.

#Astro#Fonts API#Fonts#Performance#CSS

The Astro Fonts API lets you declare web fonts once in astro.config.mjs and have Astro download, self-host, subset and serve them with optimised fallbacks. You add each family to the top-level fonts array with a provider (Google, Fontsource, Bunny, Fontshare, Adobe, npm or local files) and a cssVariable, then place <Font cssVariable="..." /> from astro:assets in your page head. Astro generates the @font-face rules, optional preload links and a CSS variable you use in styles.

The Fonts API became stable in Astro 6.0, after a period as an experimental flag. It replaces the common pattern of pasting a Google Fonts <link> into a layout, which adds a third-party connection, leaks visitor IPs to another host, and gives you little control over what loads.

Key Takeaways

  • Configure fonts in the top-level fonts array of astro.config.mjs using fontProviders from astro/config.
  • Astro downloads remote fonts at build time and serves them from your own site, so there is no third-party request.
  • The <Font /> component outputs @font-face CSS and, with preload, preload links for the files you choose.
  • Only weight 400 is included by default. List every weight and style you use.
  • Fallbacks ending in a generic family (like sans-serif) get metric-adjusted fallback fonts that reduce layout shift.

Configure a font

Add a fonts array to your config. Each entry needs a provider, a name and a cssVariable:

// astro.config.mjs
import { defineConfig, fontProviders } from 'astro/config';

export default defineConfig({
  fonts: [
    {
      provider: fontProviders.google(),
      name: 'Inter',
      cssVariable: '--font-inter',
      weights: ['100 900'],
      styles: ['normal'],
      subsets: ['latin'],
      fallbacks: ['system-ui', 'sans-serif'],
    },
    {
      provider: fontProviders.fontsource(),
      name: 'JetBrains Mono',
      cssVariable: '--font-mono',
      weights: [400, 700],
      fallbacks: ['monospace'],
    },
  ],
});

Inter is a variable font, so '100 900' requests the whole weight axis as one file. For static fonts, list individual weights.

Defaults to remember:

Option Default Note
weights [400] Add every weight you use, or bold text will be synthesised
styles ['normal', 'italic'] Drop italic if you never use it
subsets ['latin'] Add latin-ext, cyrillic and others as needed
formats ['woff2'] WOFF2 is supported by all current browsers
fallbacks ['sans-serif'] Set [] to disable
optimizedFallbacks true Generates metric-matched fallbacks

Add the Font component

In your base layout, import Font from astro:assets and render one per family:

---
// src/layouts/Base.astro
import { Font } from 'astro:assets';
const { title } = Astro.props;
---
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>{title}</title>
    <Font cssVariable="--font-inter" preload />
    <Font cssVariable="--font-mono" />
  </head>
  <body>
    <slot />
  </body>
</html>

<style is:global>
  body { font-family: var(--font-inter); }
  code, pre { font-family: var(--font-mono); }
</style>

The cssVariable value must match one in your config. A typo throws the error “Font family not found.” with the message No data was found for the `"--font-x"` family passed to the `<Font>` component. The fix for the font family error covers it.

The CSS variable already contains the fallback stack, so font-family: var(--font-inter) is all you need.

Use it with Tailwind CSS

Point Tailwind’s font families at the variables. With Tailwind CSS 4’s CSS-first config:

/* src/styles/global.css */
@import 'tailwindcss';

@theme {
  --font-sans: var(--font-inter);
  --font-mono: var(--font-mono);
}

With Tailwind CSS 3, set theme.extend.fontFamily.sans to ['var(--font-inter)'] in tailwind.config.mjs. Either way, the font files and @font-face rules still come from the <Font /> component. The Astro styling guide covers Tailwind setup.

Providers

Astro ships these providers on fontProviders:

Provider Source Good for
google() Google Fonts The largest free catalogue
fontsource() Fontsource (npm-hosted open-source fonts) Open-source fonts with consistent metadata
bunny() Bunny Fonts A Google Fonts mirror with a privacy focus
fontshare() Fontshare Free fonts from Indian Type Foundry
adobe({ id }) Adobe Fonts kit Fonts licensed through Adobe
googleicons() Google Material Symbols Icon fonts
npm() Font packages in node_modules Fonts installed as packages
local() Files in your repository Commercial or custom fonts

Remote providers are resolved at build time and the files are copied into your build output, so the published site makes no requests to the provider. Check each font’s licence permits self-hosting; for Adobe Fonts, follow Adobe’s terms for your kit.

You can also write a custom provider. The font provider reference documents the interface.

Local fonts

For fonts you have licensed as files, use the local provider with one variant per file:

// astro.config.mjs
import { defineConfig, fontProviders } from 'astro/config';

export default defineConfig({
  fonts: [
    {
      provider: fontProviders.local(),
      name: 'Brand Sans',
      cssVariable: '--font-brand',
      fallbacks: ['Arial', 'sans-serif'],
      options: {
        variants: [
          { src: ['./src/assets/fonts/BrandSans-Regular.woff2'], weight: 400, style: 'normal' },
          { src: ['./src/assets/fonts/BrandSans-Bold.woff2'], weight: 700, style: 'normal' },
          { src: ['./src/assets/fonts/BrandSans-Italic.woff2'], weight: 400, style: 'italic' },
        ],
      },
    },
  ],
});

Keep the source files in src/, not public/. Astro copies processed fonts into the build output, so files in public/ would be shipped twice. If weight or style is omitted, Astro tries to infer it from the file.

Preloading the right files

Preloading tells the browser to fetch a font before it discovers it in CSS, which helps text render in the final font sooner. Preload too much and you compete with the hero image for bandwidth.

preload accepts true (all files for that family) or a filter:

---
// src/layouts/Base.astro (head excerpt)
import { Font } from 'astro:assets';
---
<Font cssVariable="--font-inter" preload={[{ weight: 400, style: 'normal', subset: 'latin' }]} />

A sensible default is to preload only the body text face in the main subset, and let headings and italics load normally. With a variable font, that is usually one file. The Astro performance guide covers how fonts affect LCP and CLS.

Optimised fallbacks and layout shift

While a web font loads, the browser shows a fallback. If the fallback has different metrics, text reflows when the web font arrives, causing layout shift.

When the last item in fallbacks is a generic family such as sans-serif or serif, Astro reads the web font’s metrics and generates an extra @font-face that wraps a local system font with size-adjust, ascent-override, descent-override and line-gap-override. The fallback then occupies nearly the same space as the real font, so the swap barely moves the page.

To control fallbacks yourself, set optimizedFallbacks: false and provide your own stack.

Accessing font data in code

astro:assets also exports fontData, keyed by CSS variable, with the resolved files for each family. It is useful when you need font files outside CSS, for example to generate Open Graph images at build time with a library that needs font binaries:

// src/pages/og/[slug].png.ts (excerpt)
import { fontData } from 'astro:assets';

const interFiles = fontData['--font-inter'];
// Each entry describes a resolved font face, including its source URLs.

Check the Astro fonts guide for the current shape of this data and the related helpers.

If your layout has this:

<link rel="preconnect" href="https://fonts.googleapis.com" />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet" />

Replace it in four steps:

  1. Remove both <link> tags.
  2. Add Inter to fonts in astro.config.mjs with provider: fontProviders.google(), the weights you used, and a cssVariable.
  3. Add <Font cssVariable="--font-inter" preload /> to the head.
  4. Replace font-family: 'Inter', sans-serif in your CSS with var(--font-inter).

Run astro build and check the network tab: font files now come from your own domain. If you use Fontsource packages (@fontsource/inter) imported in a layout, the same steps apply with fontProviders.fontsource().

Common mistakes

  • Bold looks fake. You used font-weight: 700 without adding 700 to weights, so the browser synthesises bold.
  • Font missing in some languages. The text needs a subset you did not list.
  • No font in production. The <Font /> component is missing from the layout used by that page.
  • Duplicated files. Local fonts placed in public/ and referenced from the config.
  • Too many preloads. preload on every family and weight delays more important resources.

Every Komal Astro theme is a full Astro 7 project, so switching its typography means editing the fonts entries and the CSS variables, not hunting through templates.

FAQ

Is the Astro Fonts API still experimental?

No. It was stable as of Astro 6.0, configured with the top-level fonts option. Earlier versions used an experimental flag with a slightly different setup.

Does the Astro Fonts API self-host Google Fonts?

Yes. With fontProviders.google(), Astro downloads the font files at build time and serves them from your site, so visitors make no requests to Google.

How do I use a local font file in Astro?

Use fontProviders.local() and list each file under options.variants with its src, weight and style. Keep the files in src/, then add <Font cssVariable="..." /> to your layout.

Why is only the regular weight of my font loading?

weights defaults to [400]. Add every weight you use, or a range like '100 900' for a variable font.

Should I preload fonts in Astro?

Preload the main body font face only. Preloading every weight and style competes with images and scripts for bandwidth and can make the page slower.