WhoBuilt

Using Fonts in Next.js

Nov 16, 2022· 6 min· 231K views·Watch on YouTube

Lee Robinson, a developer at Vercel, explains how to use Google Fonts and local fonts with Next.js 13, including Tailwind CSS.

Why external font links can cause problems

Lee starts with a standard Next.js 13 app, which uses the system font stack. Adding Roboto through a Google Fonts link works, but the fallback font loads first and the app makes external requests for the font. On slow connections, this can mean a noticeable delay and layout shift.

Load Google Fonts with Next.js

Lee installs the separate `@next/font` package and imports Roboto in the Pages Router app. He sets the Latin subset and chooses weights, then applies the generated class to the page. Next.js self-hosts the font and adds a fallback font designed to reduce layout shift.

Choose fonts and weights

The same approach works with other Google Fonts, including Inter and IBM Plex. For variable fonts such as Inter, Lee recommends leaving out explicit weights where possible, which can improve performance.

Use local fonts and Tailwind CSS

Local font files work too, using a source path when defining the font. For Tailwind CSS, Lee applies a named CSS variable from the font and maps that variable to Tailwind’s sans family in the config. In the beta App Directory, he applies the font to the root layout.

Takeaways

  • Use `@next/font` to self-host Google Fonts and avoid runtime requests to Google Fonts.
  • Limit font subsets and weights to what the app needs.
  • Consider variable fonts to reduce font file overhead.
  • For Tailwind, expose the font through a CSS variable and map it in the Tailwind config.
  • In the App Directory, apply the font in the root layout.

Mentioned in this talk

Search inside this talk

What was claimed 6

Related talks

Using Fonts in Next.js · WhoBuilt