Topic 38 of 47
Font Optimization Customization
Overview
Next.js automatically optimizes web fonts. `next/font` downloads font files at build time and hosts them with your static assets, eliminating layout shift (FOUT) and removing network requests to external providers like Google Fonts.
Syntax
tsx
// app/layout.tsx
import { Inter, Roboto_Mono } from 'next/font/google';
// 1. Initialize fonts
const inter = Inter({
subsets: ['latin'],
display: 'swap', // Fallback display behavior
variable: '--font-inter', // Create a CSS variable
});
const robotoMono = Roboto_Mono({
subsets: ['latin'],
display: 'swap',
variable: '--font-roboto-mono',
});
// 2. Apply to HTML body
export default function RootLayout({ children }) {
return (
<html lang="en" className={`${inter.variable} ${robotoMono.variable}`}>
<body className="font-sans">
{children}
</body>
</html>
);
}Common Pitfalls
- Always use the `subsets` property when importing Google fonts (e.g., `['latin']`) to reduce the font file size by excluding unused glyphs.
- Font optimizations require no client-side JavaScript. Do not try to inject `<link href="https://fonts.googleapis.com...">` manually in the Document head.
Real-World Example
Using local fonts downloaded in your project:
example
tsx
// app/layout.tsx
import localFont from 'next/font/local';
// You can load multiple weights from a single variable font
const myFont = localFont({
src: './fonts/GeistVF.woff',
display: 'swap',
variable: '--font-geist',
});
export default function RootLayout({ children }) {
return (
<html lang="en" className={myFont.variable}>
<body>{children}</body>
</html>
);
}