SyntaxStudy
Sign Up
Next.js next/font for Optimised Web Fonts
Next.js Beginner 1 min read

next/font for Optimised Web Fonts

next/font is the companion to next/image for typography. It automatically optimises font loading by downloading fonts at build time, self-hosting them on your domain, and generating CSS with size-adjust and unicode-range to eliminate layout shift. Unlike loading fonts from Google Fonts with a link tag, next/font makes no external requests from the browser, improving both performance and privacy. Google Fonts are available via next/font/google. You import the font constructor, call it with your desired weights and subsets, and it returns an object containing a className and a style property. Passing the className to the html element in your root layout applies the font globally. Alternatively you can use CSS variables to integrate the font with Tailwind CSS or other CSS frameworks. Local fonts are loaded with the LocalFont constructor from next/font/local. You provide the path to the font file (relative to the module) and any additional metadata. This is useful for custom brand fonts or fonts not available on Google Fonts. next/font supports variable fonts, which are single font files that contain multiple weights and styles, resulting in better compression and more typographic flexibility.
Example
// app/layout.tsx — Google Fonts via next/font/google

import { Inter, Merriweather } from 'next/font/google';

// Variable font — single file covers all weights
const inter = Inter({
  subsets: ['latin'],
  variable: '--font-inter', // CSS variable for Tailwind
  display: 'swap',
});

// Non-variable font — specify weights explicitly
const merriweather = Merriweather({
  subsets: ['latin'],
  weight: ['400', '700'],
  style: ['normal', 'italic'],
  variable: '--font-merriweather',
  display: 'swap',
});

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    // Apply both fonts as CSS variables on the html element
    <html lang="en" className={`${inter.variable} ${merriweather.variable}`}>
      <body className="font-sans">{children}</body>
    </html>
  );
}

// tailwind.config.ts — reference the CSS variables
import type { Config } from 'tailwindcss';

const config: Config = {
  theme: {
    extend: {
      fontFamily: {
        sans: ['var(--font-inter)', 'system-ui', 'sans-serif'],
        serif: ['var(--font-merriweather)', 'Georgia', 'serif'],
      },
    },
  },
};
export default config;

// Local font example
import localFont from 'next/font/local';

const brandFont = localFont({
  src: [
    { path: '../public/fonts/BrandFont-Regular.woff2', weight: '400' },
    { path: '../public/fonts/BrandFont-Bold.woff2', weight: '700' },
  ],
  variable: '--font-brand',
});