the Blog's Logo
the Blog's Logo
Creating Custom Fonts in Next.jsimage
Photo by Ahmad Dirinion Unsplash

Next.js provides first-class support for self-hosted and Google Fonts. You can import them using next/font and use custom CSS variables for fine control over your typography. This improves loading speed and avoids layout shifts due to font swapping.

Font Optimization

The next/font module automatically optimizes fonts and supports built-in self-hosting. You can use it to load web fonts without layout shifts, either globally or at the component level.

To use a font, import it from next/font/local or next/font/google, call it with your options, and set the className on the element you want it applied to.

Google Fonts

Next.js allows you to self-host Google Fonts, serving them from your domain without additional network requests.

Example applying a font globally in pages/_app:

import { Geist } from 'next/font/google'
import type { AppProps } from 'next/app'
const geist = Geist({
  subsets: ['latin'],
})
export default function MyApp({ Component, pageProps }: AppProps) {
  return (
    <main className={geist.className}>
      <Component {...pageProps} />
    </main>
  )
}
import { Geist } from 'next/font/google'
const geist = Geist({
  subsets: ['latin'],
})

Then apply it to your main layout using className:

export default function MyApp({ Component, pageProps }) {
  return (
    <main className={geist.className}>
      <Component {...pageProps} />
    </main>
  )
}

Local Fonts

To use a local font, import it from next/font/local and provide the path to your font file. Fonts can reside in the public folder or alongside your code.

import localFont from 'next/font/local'
import type { AppProps } from 'next/app'
const myFont = localFont({
  src: './my-font.woff2',
})
export default function MyApp({ Component, pageProps }: AppProps) {
  return (
    <main className={myFont.className}>
      <Component {...pageProps} />
    </main>
  )
}

If a font has multiple weights or styles, pass an array of objects to src:

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' },
  ],
})

Summary

Using next/font simplifies font management in Next.js:

  • Optimizes loading and reduces layout shifts.

  • Supports both Google and local fonts with self-hosting.

  • Provides fine-grained control using CSS variables.

For the full API reference and advanced features, see the Next.js Font API Reference.