Next.jsEasy
What is next/font and how does it optimize fonts?
next/font loads Google Fonts or local font files at build time and self-hosts them with your app. It removes requests to external font servers, preloads the font, adds font-display and automatic fallback metrics so text does not shift, and exposes a class name or CSS variable to apply it.
Two modules
next/font/google:import { Inter, Geist } from "next/font/google". Font files are downloaded at build time and served from your domain, so the browser never contacts Google (better privacy and performance).next/font/local:localFont({ src: "./fonts/Brand.woff2" })or multiple weights and styles.
Optimizations
- Self-hosting removes DNS lookups and connections to third-party origins.
- Preloading of the font files used on the route.
- Zero layout shift: a fallback font with adjusted
size-adjust,ascent-overrideand similar metrics, so swapping to the web font barely moves text. - Subsetting:
subsets: ["latin"]keeps files small. - Variable fonts are recommended; one file covers all weights.
Options
weight, style, subsets, display (default swap), variable (CSS variable name), preload, fallback, adjustFontFallback.
Applying it
className={inter.className}on<html>or<body>.- Or
variable: "--font-sans"and reference it in CSS or Tailwind's@theme.
Rules
Call the font loader at module scope, not inside a component, and assign it to a constant. create-next-app uses Geist and Geist Mono by default.
Code example
tsx
1// app/fonts.ts2import { Geist, Geist_Mono } from "next/font/google";3import localFont from "next/font/local";45export const sans = Geist({ subsets: ["latin"], variable: "--font-sans" });6export const mono = Geist_Mono({ subsets: ["latin"], variable: "--font-mono" });7export const brand = localFont({8 src: [9 { path: "./fonts/Brand-Regular.woff2", weight: "400" },10 { path: "./fonts/Brand-Bold.woff2", weight: "700" },11 ],12 variable: "--font-brand",13});1415// app/layout.tsx16// import { sans, mono, brand } from "./fonts";17// <html lang="en" className={`${sans.variable} ${mono.variable} ${brand.variable}`}>18// <body className="font-sans">{children}</body>19// </html>2021/* app/globals.css (Tailwind v4) */22// @theme { --font-sans: var(--font-sans); --font-mono: var(--font-mono); }
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.