next/font and Zero-Layout-Shift Typography
Web fonts are a classic performance trap. The naive path â a stylesheet link to Google Fonts, followed by a cascade of fallback rendering, swap, and repaint â costs extra round-trips, risks a flash of invisible text, and shifts layout as metrics change between the fallback and the real face. Next.js's next/font module eliminates that sequence. It downloads font files at build time, self-hosts them under your own domain, generates size-adjust fallback metrics so the placeholder text occupies the same box as the final text, and exposes the family as a CSS variable or a class your components consume.
The result is typography that feels native: no third-party request on the critical path, no layout shift when the font loads, and subsetting that ships only the characters your locale actually needs. This lesson covers Google and local font workflows, the options that matter, variable fonts, Tailwind integration, and how to avoid the subsetting bugs that silently drop glyphs.
Prerequisites
- !Next.js App Router project with a root layout
- !CSS familiarity with font-family and fallback stacks
- !Basic understanding of rendering metrics and layout shift
What You'll Learn
- 1Load Google and self-hosted fonts through next/font
- 2Choose weights, subsets, and display strategies deliberately
- 3Expose fonts as CSS variables and connect them to Tailwind
- 4Diagnose missing glyphs and unexpected font swaps
Google fonts without the Google request
The next/font/google entry point takes the family you want, fetches the files during the build, and rewrites the references so production serves them from your domain. Nothing in the browser talks to fonts.googleapis.com â a privacy and performance win, especially for European audiences where third-party font requests attract scrutiny.
// app/layout.js
import { Inter, Source_Serif_4 } from 'next/font/google';
const inter = Inter({
subsets: ['latin'],
display: 'swap',
variable: '--font-inter',
});
const serif = Source_Serif_4({
subsets: ['latin'],
weight: ['400', '600', '700'],
style: ['normal', 'italic'],
variable: '--font-serif',
});
export default function RootLayout({ children }) {
return (
<html lang="en" className={`${inter.variable} ${serif.variable}`}>
<body className="font-sans">{children}</body>
</html>
);
}
The variable option registers a CSS custom property on the html element, which keeps the font choice composable: any stylesheet or utility class can reference var(--font-inter) without importing the JavaScript module that defined it.
Self-hosted local fonts
When the brand ships its own files â licensed WOFF2 files in the repository, a variable font from a design system â next/font/local points at them with the same API shape. The files still get hashed, subset if configured, and served under /_next/static with immutable cache headers.
// app/layout.js
import localFont from 'next/font/local';
const brandSans = localFont({
src: [
{
path: './fonts/BrandSans-Regular.woff2',
weight: '400',
style: 'normal',
},
{
path: './fonts/BrandSans-Bold.woff2',
weight: '700',
style: 'normal',
},
],
display: 'swap',
variable: '--font-brand',
fallback: ['system-ui', 'arial'],
});
export default function RootLayout({ children }) {
return (
<html lang="en" className={brandSans.variable}>
<body>{children}</body>
</html>
);
}
Listing each weight and style explicitly is not ceremony: it lets the build emit the correct @font-face descriptors and prevents the browser from synthesizing a fake bold from a regular file.
Variable fonts: one file, every weight
A variable font packs the whole weight axis into a single file, which usually beats downloading four static weights. Request the axis range instead of a list, and the build emits one face with a font-weight descriptor spanning your range.
// app/layout.js
import { Roboto_Flex } from 'next/font/google';
const roboto = Roboto_Flex({
subsets: ['latin'],
axes: ['wght', 'GRAD', 'wdth'],
display: 'swap',
variable: '--font-roboto-flex',
});
Variable fonts shine when the design uses many intermediate weights. When only regular and bold are ever rendered, two static files can be smaller than one variable file carrying axes you never touch â measure rather than assume.
Options that change real behavior
| Option | Purpose | Guidance |
|---|---|---|
subsets | Character sets to ship | Always include the locales you render |
display | Font loading behavior | swap for most UI; optional for ultra-strict CLS |
weight | Static weights to include | Required for non-variable Google fonts |
axes | Variable font axes | Include only axes you style against |
fallback | System stack for metrics | Keep close in width to avoid shift |
preload | Preload the face | Disable for fonts used only on rare routes |
adjustFontFallback | Auto metric fallback | Leave on unless you supply your own |
display: swap shows the fallback immediately and swaps when the face arrives; display: optional skips the swap entirely and uses the fallback for users on slow connections, which can eliminate shift but may surprise users who expected the brand font.
Connecting to Tailwind and component CSS
The variable wiring makes the font a design token like any other. Tailwind maps the CSS variable into the theme, so utility classes such as font-sans and font-serif follow the JavaScript configuration with no duplicated family names.
// tailwind.config.js
module.exports = {
theme: {
extend: {
fontFamily: {
sans: ['var(--font-inter)', 'system-ui', 'sans-serif'],
serif: ['var(--font-serif)', 'Georgia', 'serif'],
brand: ['var(--font-brand)', 'system-ui', 'sans-serif'],
},
},
},
};
Component-level CSS can consume the same variable without touching Tailwind: font-family: var(--font-serif); inside a CSS Module works because the variable is defined on the html element and inherited everywhere.
Subsetting bugs and how they show up
The most common font bug is missing characters. A page renders fine in English and displays fallback glyphs â or empty boxes â for accented characters, punctuation such as the em dash, or a second language you added later. The cause is almost always a subset that does not include those glyphs, or a local file that was itself subsetted at design time. The fix is to include the needed subsets and, for local fonts, ship the complete file or regenerate it with the right character coverage. Test with a page that renders the full alphabet of every supported locale, including curly quotes and dashes, right in your visual regression suite.
Production pitfalls
Teams hit a predictable set of issues: fonts loaded with next/font on the root layout but a second stylesheet link sneaking back in during a redesign, doubling requests and reintroducing the original problem. Preload enabled for a decorative font used on one marketing page, competing with the hero image for bandwidth. A weight list that omits italic, so the browser synthesizes slanted glyphs that look wrong next to true italics. And family names referenced directly in CSS instead of through the variable, which works in development and breaks the moment the font is renamed.
Measuring whether your font choices help
Font work rewards measurement over taste debates. Before changing anything, capture the current numbers: total blocking time attributed to font loading, the shift score on a cold-cache visit, and the transferred bytes of font files alone. After switching to next/font, the same pages should show zero third-party font requests, a smaller or equal byte count, and a layout shift score that stays flat when the face swaps in. The performance panel's network rows tell the story quickly â look for font files served from your own origin with long-lived cache headers, and confirm the preloaded face matches the one actually used above the fold. Field data from real users matters more than lab numbers, so if analytics reports a core web vitals regression after a brand refresh, check the font pipeline before suspecting the JavaScript. A quarterly audit of which declared weights ever appear in the rendered page often reveals faces that can be dropped entirely, which is free performance reclaimed with a two-line diff.
Common Mistakes
Referencing Google Fonts with a stylesheet link alongside next/font
Fix: Delete the link tag; next/font already self-hosts and preloads the face at build time.
Shipping only the latin subset on a multilingual site
Fix: Include every subset your locales need and add a glyph-coverage check to visual tests.
Disabling adjustFontFallback without providing your own metric-matched fallback
Fix: Either keep the automatic adjustment or supply a fallback font whose metrics closely match, or layout shift returns.
Preloading fonts that are not used above the fold
Fix: Set preload: false for decorative or route-specific faces so the critical path stays focused.
Best Practices
- Expose every font as a CSS variable and map it into your Tailwind theme once
- Prefer variable fonts when the design uses many weights; measure file size either way
- Keep the fallback stack metrically close so the swap does not reflow text
- Render the full character set of each supported locale in a visual test to catch subset gaps
Interview Questions
Q1: How does next/font prevent layout shift on swap?
It computes size-adjust and ascent/descent overrides for a local fallback face, so the fallback occupies the same box as the web font and the swap does not reflow content.
Q2: Why does next/font matter for privacy as well as speed?
Font files are downloaded at build time and served from your own domain, so end users never make requests to third-party font CDNs that log their IPs.
Q3: When would you set preload to false?
When the font is not used on above-the-fold content of the route being served â decorative faces or fonts exclusive to rare pages would otherwise compete for bandwidth with critical resources.
Key Takeaways
- next/font downloads and self-hosts fonts at build time, removing third-party requests from the critical path.
- Metric-adjusted fallbacks make the swap invisible, which is what keeps CLS at zero.
- Use the variable option to expose fonts as design tokens and wire them into Tailwind once.
- Variable fonts collapse weight lists into one file when the design actually uses many weights.
- Subset gaps are silent; test every supported locale's glyphs in visual regression.