Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Fonts with next/font

The next/font module loads fonts so that the page does not flicker while loading and does not contact third-party servers. Next.js downloads Google Fonts at build time and serves them from your own address — the visitor makes no requests to Google.

A Google Fonts font

The starter project already uses the Geist font. Let us replace it with Inter:

// app/layout.tsx
import { Inter } from 'next/font/google';
import './globals.css';
 
const inter = Inter({
  subsets: ['latin'],
});
 
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" className={inter.className}>
      <body>{children}</body>
    </html>
  );
}

Each font is imported as a function with the same name, spaces replaced by underscores: Roboto_Mono, Open_Sans. The className property holds a class with the right font-family. Reload the page — all site text is now set in Inter.

Character sets and weights

OptionExampleWhy
subsets['latin', 'cyrillic']Which alphabets to load
weight['400', '700']Weights for fonts without a variable weight
style['normal', 'italic']Italics
display'swap'How to show text before the font loads

Inter is a variable font, so you can leave out weight: every weight is available.

A second font through a CSS variable

Headings often use a separate font. It is convenient to pass it to CSS as a variable:

// app/layout.tsx (fragment)
import { Inter, Lora } from 'next/font/google';
 
const inter = Inter({ subsets: ['latin'] });
const lora = Lora({ subsets: ['latin'], variable: '--font-heading' });
 
// <html lang="en" className={`${inter.className} ${lora.variable}`}>
/* app/globals.css */
h1,
h2 {
  font-family: var(--font-heading);
}

The variable option creates a CSS variable with the font family. Headings on every page get Lora, the rest of the text gets Inter.

Your own font file

A font file from the project is loaded with next/font/local:

// app/layout.tsx (fragment)
import localFont from 'next/font/local';
 
const brand = localFont({ src: './fonts/Brand.woff2' });

The path is relative to the file where the function is called. It is used the same way: brand.className.

Common mistake

Calling Inter(...) inside a component or in several files. Font functions must be called at the top level of a module, and each call creates a separate copy of the font. Load the font once in the root layout and use the class or CSS variable everywhere else.

Thanks for reading!

Donate to the site — we work hard for you.