Labs ICT
Pro Login

Font Optimization

Font Optimization

Next.js automatically optimizes fonts you use in your application. It downloads fonts at build time and serves them from your domain, eliminating external network requests and improving performance.

Think of font optimization as a font delivery service. Instead of making users download fonts from Google Fonts every time, Next.js hosts them locally for faster loading.

Using Google Fonts

Next.js makes it easy to use Google Fonts with the next/font module:

// app/layout.js
import { Inter } from 'next/font/google';

const inter = Inter({
  subsets: ['latin'],
  display: 'swap',
});

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

The font is automatically downloaded during build and served from your domain.

Using Local Fonts

You can also use local font files from your project:

// app/layout.js
import localFont from 'next/font/local';

const myFont = localFont({
  src: './fonts/MyFont.woff2',
  display: 'swap',
});

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

This is useful for custom fonts or when you need complete control over font files.

Font Configuration Options

The font module provides several configuration options:

const inter = Inter({
  subsets: ['latin'],        // Font subsets to load
  display: 'swap',          // How to display font while loading
  weight: ['400', '700'],   // Font weights to include
  variable: '--font-inter', // CSS variable name
});

The display: 'swap' option ensures text remains visible while the font loads.

Benefits of Font Optimization

Font optimization provides several advantages:

Faster loading: Fonts are served from your domain, reducing DNS lookups.

No layout shift: Next.js preloads fonts to prevent text flash.

Automatic subsetting: Only the characters you need are included.

Self-hosted: No reliance on external services like Google Fonts.

Font optimization is a simple way to improve your application's performance and user experience.