Advanced

Find out how Nuxt Fonts works behind the scenes to optimize fonts in your project.

How it works

Nuxt Fonts processes all your CSS and does the following things automatically when it encounters a font-family declaration.

  1. Resolves fonts used in CSS. It starts by looking in your public/ directory for font files that match the name, like Roboto.woff2, RobotoBold.ttf, etc. Then it moves on to web font providers like google, bunny and fontshare. Once a provider is found (in this case, probably Google Fonts), we move on to the next step.
  2. Generates and injects @font-face rules for you. We'll generate rules to point your browser to the right source files. They'll be injected into the same CSS where you use the font-family.
    /* If you write something like this: */
    :root {
      font-family: Poppins;
    }
    
    /* Then Nuxt fonts will add declarations that look like this at the beginning of the CSS file: */
    @font-face {
      font-family: 'Poppins';
      src: local("Poppins"), url("/_fonts/<hash>.woff2") format(woff2);
      font-display: swap;
      unicode-range: U+0000-00FF,U+0131, /* ... */;
      font-weight: 400;
      font-style: normal;
    }
    /* ... plus more font-face declarations for other unicode ranges/weights */
    
  3. Proxies and caches font requests. Rather than using the original source URLs (to remote servers), we generate rewrites under the /_fonts subpath. When accessed by your browser, we download the font from the remote server and cache it locally.
  4. Creates font fallback metrics. If we have access to the font metrics (ascent, descent, line gap, character width, etc.) then we can generate a fallback @font-face declaration as well. The idea is that we 'morph' a local system font (like Arial or Times New Roman) to be as close as possible to the size of the web font, to decrease layout shift (read more about CLS).
    :root {
      /* This will generate fallbacks for local versions of Helvetica and Arial, adjusted to match Roboto's metrics. */
      font-family: Roboto, Helvetica, Arial;
      /* If you provide a generic family (like serif or sans-serif), we will use a system font from that family. */
      font-family: Merriweather, serif;
    }
    
  5. Include fonts in build. When you build your project, we'll copy across all the fonts used in your project so you don't need to make any external requests when loading your site. (Any that haven't already been cached in development are downloaded at build time.) Font file names are hashed and Nuxt will serve them with long-lived cache headers.