Next.js Font Optimization
Overview
Next.js provides built-in font optimization through the next/font module, automatically optimizing font loading, eliminating external network requests, and improving performance and user experience.
Why Font Optimization?
Problems with Traditional Font Loading
- Layout Shift (CLS): Fonts loading can cause the page layout to jump
- Performance Impact: External font requests increase load time
- Privacy Concerns: Using external services like Google Fonts may leak user information
- Network Dependency: Reliance on third-party CDN availability
Advantages of Next.js Font Optimization
- Automatically self-host font files
- Zero layout shift
- Automatic font subsetting
- Preload critical fonts
- Support for Google Fonts and local fonts
Using Google Fonts
Basic Usage
Multiple Font Weights
Variable Fonts
Use in CSS:
Using Local Fonts
Loading Local Font Files
Multiple File Configuration
Combining Multiple Fonts
Using Multiple Fonts Together
Using with Tailwind CSS
Usage:
Font Configuration Options
Full Configuration Example
display Options
auto: Browser default behaviorblock: Briefly hide text, then show the fontswap: Show fallback font immediately, switch when loaded (recommended)fallback: Hide text briefly, then show fallback fontoptional: Hide text briefly, may not switch fonts
Using Fonts on Specific Pages
On a Single Page
In Components
Performance Optimization Tips
1. Use Font Subsets
2. Limit Font Weights
3. Use Variable Fonts
4. Preload Critical Fonts
Chinese Font Optimization
Using Local Chinese Fonts
Font Subsetting
Since Chinese font files are large, it is recommended to use tools for subsetting:
Debugging and Testing
Checking Font Loading
In browser developer tools:
- Network tab: Check font file loading
- Performance tab: Check CLS metrics
- Lighthouse: Run performance audits
Verifying Font Application
Best Practices
1. Global Font Configuration
2. CSS Configuration
3. Conditional Loading
Practical Example
Complete Font Configuration
Related Resources
Previous Chapter: Image Optimization | Next Chapter: Metadata