Overview
The next/font module automatically optimizes fonts and removes external network requests, improving privacy and performance. It has built-in self-hosting for any font file, so web fonts load optimally with no layout shift.
Basic Usage
- Import the font loader from
next/font/googleornext/font/local. - Call it as a function with the appropriate options.
- Set the
classNameof the element you want to style.
// app/layout.tsx
import { Geist } from 'next/font/google'
const geist = Geist({
subsets: ['latin'],
})
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" className={geist.className}>
<body>{children}</body>
</html>
)
}
Scope: Fonts are scoped to the component where they are used. To apply a font to the whole application, add it to the Root Layout.
Google Fonts
- Any Google Font can be self-hosted automatically.
- Font files are included as static assets and served from your own domain, so the browser sends no requests to Google.
- Import the chosen font from
next/font/google. - Variable fonts are recommended for the best performance and flexibility.
- If the font is not variable, you must specify a
weight:
import { Roboto } from 'next/font/google'
const roboto = Roboto({
weight: '400',
subsets: ['latin'],
})
Local Fonts
- Import
localFontfromnext/font/localand setsrcto the font file. - The path is resolved relative to the file where
localFontis called. - Fonts can live anywhere in the project, including
publicor co-located in theappfolder.
import localFont from 'next/font/local'
const myFont = localFont({
src: './my-font.woff2',
})
Multiple files for one family
src can be an array of objects with path, weight, and style:
const roboto = localFont({
src: [
{ path: './Roboto-Regular.woff2', weight: '400', style: 'normal' },
{ path: './Roboto-Italic.woff2', weight: '400', style: 'italic' },
{ path: './Roboto-Bold.woff2', weight: '700', style: 'normal' },
{ path: './Roboto-BoldItalic.woff2', weight: '700', style: 'italic' },
],
})
Key Takeaways
-
next/fontself-hosts fonts, with no external network requests and no layout shift. - Use
next/font/googlefor Google Fonts andnext/font/localfor your own font files. - Prefer variable fonts; otherwise specify
weight. - Apply the font via
className. Put it in the Root Layout for app-wide use.
Top comments (0)