Next.js Performance

Font Optimization

next/font, Google Fonts, local fonts, and font loading strategies.

Advertisement

Font Optimization

next/font, Google Fonts, local fonts, and font loading strategies.

Overview

Next.js optimizes font loading to prevent layout shifts.

Key Concepts

  • next/font — Built-in font optimization
  • Google Fonts — Load fonts from Google Fonts
  • Local Fonts — Use font files in your project
  • Font Display — Control font loading behavior
  • Font Subsetting — Load only needed characters

Code Examples

// app/layout.js
import { Inter, Roboto } from 'next/font/google';
import localFont from 'next/font/local';

const inter = Inter({ subsets: ['latin'] });
const roboto = Roboto({ weight: '400', subsets: ['latin'] });
const myFont = localFont({
  src: './fonts/MyFont.woff2',
  display: 'swap'
});

export default function RootLayout({ children }) {
  return (
    <html lang="en" className={inter.className}>
      <body>{children}</body>
    </html>
  );
}

// Component with font
function Heading() {
  return <h1 className={roboto.className}>Hello World</h1>;
}

// CSS variables
const poppins = Poppins({
  subsets: ['latin'],
  variable: '--font-poppins'
});

export default function Layout({ children }) {
  return (
    <html lang="en" className={poppins.variable}>
      <body className="font-sans">{children}</body>
    </html>
  );
}
/* tailwind.config.js */
module.exports = {
  theme: {
    extend: {
      fontFamily: {
        sans: ['var(--font-poppins)']
      }
    }
  }
};

Practice

Implement a custom font with proper loading and fallback fonts.