DEV Community

Ogasawara Kakeru
Ogasawara Kakeru

Posted on

Next.js ~Font Optimization~

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

  1. Import the font loader from next/font/google or next/font/local.
  2. Call it as a function with the appropriate options.
  3. Set the className of 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>
  )
}
Enter fullscreen mode Exit fullscreen mode

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'],
})
Enter fullscreen mode Exit fullscreen mode

Local Fonts

  • Import localFont from next/font/local and set src to the font file.
  • The path is resolved relative to the file where localFont is called.
  • Fonts can live anywhere in the project, including public or co-located in the app folder.
import localFont from 'next/font/local'

const myFont = localFont({
  src: './my-font.woff2',
})
Enter fullscreen mode Exit fullscreen mode

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' },
  ],
})
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • next/font self-hosts fonts, with no external network requests and no layout shift.
  • Use next/font/google for Google Fonts and next/font/local for 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)