Performance: Font optimization with next/font
This affects page load speed by optimizing font delivery and rendering, reducing blocking time and layout shifts.
import { Inter } from 'next/font/google'; const inter = Inter({ subsets: ['latin'], variable: '--font-inter' }); export default function App({ Component, pageProps }) { return <main className={inter.variable}><Component {...pageProps} /></main>; }
import '../styles/globals.css'; // In globals.css @font-face { font-family: 'CustomFont'; src: url('/fonts/customfont.woff2') format('woff2'); font-display: swap; } // Use font-family: 'CustomFont' in CSS
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| CSS @font-face with font-display: swap | Minimal DOM impact | Triggers reflow on font swap | Paint cost on font swap | [!] OK |
| next/font with automatic preload and subset | Minimal DOM impact | Single reflow during initial layout | Reduced paint cost | [OK] Good |
next/font in a Next.js application?next/fontnext/font is designed to load fonts efficiently in Next.js apps, improving speed and user experience.next/font.Inter font from Google Fonts using next/font/google?import { Inter } from 'next/font/google';
const inter = Inter({ subsets: ['latin'] });
export default function Home() {
return <main className={inter.className}>Hello World</main>;
}inter.className in the <main> element?inter.className providesInter font function returns an object with a className property that applies the optimized font styles.className={inter.className} applies the Inter font styles to the <main> element.next/font/local:import localFont from 'next/font/local';
const myFont = localFont({
src: './fonts/MyFont.ttf',
weight: '400',
style: 'normal'
});
export default function Page() {
return <div className={myFont.className}>Sample Text</div>;
}src property format for localFontsrc to be an array of objects with path and weight, not a single string.src path must be an array, not a string -> Option Asrc path must be an array, not a string [OK]Roboto and Open Sans, both with latin subsets, and apply them to different parts of your Next.js page. Which approach correctly uses next/font/google to optimize both fonts and apply them separately?Pass the test and this pattern moves unknown