Topic 35 of 39
Font Optimization
Overview
The next/font module automatically optimizes fonts (including Google Fonts) by downloading them at build time and hosting them alongside your static assets. This eliminates external network requests and prevents layout shift (FOUT/FOIT).
Syntax
tsx
// app/layout.tsx
import { Roboto } from 'next/font/google';
// Configures the font at build time
const roboto = Roboto({
weight: ['400', '700'],
subsets: ['latin'],
display: 'swap',
});
export default function RootLayout({ children }) {
// Applies the font class to the body
return (
<html lang="en">
<body className={roboto.className}>
{children}
</body>
</html>
);
}Common Pitfalls
- Importing Google Fonts via
<link>tags in the document head instead of usingnext/font, which slows down the site. - Loading too many font weights, which increases the bundle size.
Interview Questions
Q:
What is the primary benefit of using
next/font/google over standard CDN links?A:
Next.js downloads the Google Font at build time and serves it locally from your domain. This ensures zero external network requests and guarantees privacy.
Real-World Example
Setting up a custom local font.
example
tsx
import localFont from 'next/font/local';
// Loads a font file from the public directory
const myFont = localFont({ src: '../public/fonts/CustomFont.woff2' });
export default function Page() {
return <h1 className={myFont.className}>Custom Font Look</h1>;
}Check Your Knowledge
Test your understanding of Font Optimization with these quick questions.