Script Valley
Next.js: Full-Stack React Applications
Performance, Optimization, and DeploymentLesson 6.2

How to optimize fonts in Next.js with next/font

next/font/google, next/font/local, font variables, zero layout shift, self-hosting, font-display swap, applying to Tailwind

Self-Hosted Fonts with next/font

next/font downloads fonts at build time and serves them from your own domain. No external network request at runtime. No layout shift. Zero tracking by Google.

// app/layout.tsx
import { Inter, Roboto_Mono } from 'next/font/google'

const inter = Inter({
  subsets: ['latin'],
  variable: '--font-inter',  // CSS variable name
  display: 'swap',
})

const robotoMono = Roboto_Mono({
  subsets: ['latin'],
  variable: '--font-roboto-mono',
  display: 'swap',
})

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" className={`${inter.variable} ${robotoMono.variable}`}>
      <body className="font-sans">{children}</body>
    </html>
  )
}

Using with Tailwind CSS

// tailwind.config.ts
theme: {
  extend: {
    fontFamily: {
      sans: ['var(--font-inter)'],
      mono: ['var(--font-roboto-mono)'],
    },
  },
}

Local Fonts

import localFont from 'next/font/local'

const myFont = localFont({
  src: './fonts/MyFont.woff2',
  variable: '--font-my-font',
})

Apply font variables to the <html> element, not the body. This makes them available as CSS custom properties throughout the entire document, including portals and modals rendered outside the body.

Up next

How to add metadata and Open Graph tags in Next.js

Sign in to track progress