Using Astro’s Experimental Fonts API

Astro, Fonts, Typography, Frontend, Experimental

Astro Fonts API Example

Using Astro’s Experimental Fonts API

Astro introduced an Experimental Fonts API that makes it easier to load and manage fonts from providers like Google, Fontsource, Bunny, or even self-hosted files. This feature helps you configure fonts in a centralized way, automatically handle CSS variables, and improve performance with options like preloading. 🚀


Why use the Fonts API?


Enabling the Fonts API

To start, enable the fonts experimental flag inside your astro.config.mjs:

// astro.config.mjs

import { defineConfig, fontProviders } from "astro/config";

export default defineConfig({
  experimental: {
    fonts: [
      {
        provider: fontProviders.google(),
        name: "Roboto",
        cssVariable: "--font-roboto",
        preload: true,
      },
    ],
  },
});

Using fonts in components

Once configured, you can use the <Font /> component from astro:assets in your layout or head:

---
// src/components/Head.astro
import { Font } from 'astro:assets';
---

<head>
  <Font cssVariable="--font-roboto" preload />
  <style>
    body {
      font-family: var(--font-roboto), sans-serif;
    }
  </style>
</head>

Now your entire site can use the Roboto font through the CSS variable. 🎉


Configuration options

Here are some useful options when setting up fonts:

OptionDescription
providerFont source: Google, Fontsource, Bunny, or local
nameFont family name
cssVariableCSS variable to reference in styles (e.g. --font-roboto)
preloadPreloads the font for faster initial render
weightsArray of font weights (e.g. [400, 700])
styleFont style (e.g. normal, italic)
subsetsCharacter subsets (e.g. latin, latin-ext)
fallbacksAlternative fonts if the primary one fails

Full example

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

export default defineConfig({
  experimental: {
    fonts: [
      {
        provider: fontProviders.google(),
        name: "Roboto",
        cssVariable: "--font-roboto",
        preload: true,
        weights: [400, 700],
        style: "normal",
        subsets: ["latin", "latin-ext"],
        fallbacks: ["sans-serif"],
      },
    ],
  },
});
---
// src/components/Head.astro
import { Font } from 'astro:assets';
---

<head>
  <Font cssVariable="--font-roboto" preload />
  <style>
    body {
      font-family: var(--font-roboto), sans-serif;
    }
    h1 {
      font-family: var(--font-roboto), sans-serif;
      font-weight: 700;
    }
  </style>
</head>

Caveats

Final thoughts

The Experimental Fonts API makes font management in Astro projects much easier and cleaner. With automatic CSS variables, preload support, and multi-provider flexibility, it’s a great tool to improve typography and performance.

If you’re starting a new Astro project, give it a try — just remember it’s still experimental, so keep an eye on updates in the Astro docs .