Next.jsMedium

What is automatic font optimization in Next.js?

Automatic font optimization originally meant that Next.js inlined Google Fonts CSS at build time when you used a <link> tag, saving a round-trip. That approach is legacy: since Next.js 13 the next/font module does much more, self-hosting the font files, preloading them and generating fallback metrics to eliminate layout shift.

The old behavior (Next.js 10.2 to 12)

  • With <link href="https://fonts.googleapis.com/css2?family=Inter" rel="stylesheet"> in _document, Next.js downloaded the CSS at build time and inlined it.
  • The font files themselves still came from Google, so there were still third-party connections and possible layout shift.
  • Controlled by optimizeFonts in next.config.js, which has since been removed.

The modern behavior (next/font)

  1. Fonts are downloaded at build time and served from /_next/static/media/ with long-lived cache headers.
  2. Only the subsets and weights you request are included.
  3. Files are preloaded for the routes that use them.
  4. A fallback font is tuned with size-adjust and metric overrides so the text occupies the same space before and after the web font loads, keeping CLS near zero.
  5. font-display: swap by default so text is visible immediately.

Why it matters

Fonts affect LCP (text is often the LCP element) and CLS. Third-party font hosting also raises privacy concerns, for example under GDPR in some EU rulings.

What to say in an interview

"Use next/font; the old inlining is obsolete. It self-hosts, subsets, preloads and generates metric-matched fallbacks."

Code example

tsx
1// Legacy (do not use): font loaded from Google at runtime
2// <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet" />
3
4// Modern: app/layout.tsx
5import { Inter } from "next/font/google";
6
7const inter = Inter({
8 subsets: ["latin"],
9 display: "swap", // text visible immediately
10 adjustFontFallback: true, // metric-matched fallback (default)
11 variable: "--font-inter",
12});
13
14export default function RootLayout({ children }: { children: React.ReactNode }) {
15 return (
16 <html lang="en" className={inter.variable}>
17 <body style={{ fontFamily: "var(--font-inter)" }}>{children}</body>
18 </html>
19 );
20}
21// Output: files under /_next/static/media/*.woff2, preloaded, no requests to fonts.googleapis.com

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app