Next.js Tutorial
- Next.js Introduction
- Next.js Installation
- Project Structure
- Pages & Routing
- Dynamic Routing
- Linking & Navigating
- Data Fetching (SSR)
- Data Fetching (SSG)
- Client-Side Rendering
- API Routes
- Layouts & Components
- Styling
- Image Optimization
- Font Optimization
- Script Optimization
- Middleware
- Environment Variables
- Error Handling
- Authentication
- React Server Components
- Server Actions
- Suspense & Streaming
- Caching & Revalidation
- TypeScript Integration
- Deployment
Font Optimization (`next/font`)
Custom fonts are crucial for design, but they often result in layout shifts, slow rendering times, and privacy concerns when fetching from third-party networks (like Google Fonts).
Next.js handles all these issues natively via the next/font/target module.
How `next/font` works
When you use next/font/google, Next.js downloads the font files at build timeand self-hosts them alongside your other static assets. This provides immense benefits:
- No Network Requests: Since the font is hosted locally, the browser doesn't have to resolve and fetch scripts from `fonts.googleapis.com`.
- Privacy: No user data or IP addresses are sent to Google because your own server delivers the font.
- Zero Layout Shift: Next.js automatically calculates the exact `size-adjust` property to prevent the dreaded Cumulative Layout Shift (CLS) when the font swaps.
Using Google Fonts
In the App Router, you can easily define a Google Font in your root layout.js.
// app/layout.js
import { Inter, Roboto_Mono } from 'next/font/google';
// Configure the font
const inter = Inter({
subsets: ['latin'],
display: 'swap', // ensures text is visible while waiting for the custom font
});
const roboto_mono = Roboto_Mono({
subsets: ['latin'],
display: 'swap',
variable: '--font-roboto-mono', // Creates a CSS variable!
});
export default function RootLayout({ children }) {
return (
// Apply the font class to the HTML body
<html lang="en" className={inter.className}>
<body>{children}</body>
</html>
);
}Using Local Custom Fonts
If you purchased a licensed font (like a `.woff2` file), you can use next/font/local instead.
// app/layout.js
import localFont from 'next/font/local';
// Load locally
const myFont = localFont({
src: './MyFont.woff2',
display: 'swap',
});
export default function RootLayout({ children }) {
return (
<html lang="en" className={myFont.className}>
<body>{children}</body>
</html>
);
}Conclusion
Always use `next/font` instead of manual <link rel="stylesheet"> tags for fonts. It takes only seconds to configure, and the performance benefits are massive. Next, we will learn about Script Optimization.