Introduction & The Magic of Optimized Typography

Hello, developers! Ever felt like your font setups are more of a chore than a charm? Let’s flip that script. In Next.js, the new next/font module transforms your typography game from meh to magnificent with minimal effort. Whether you’re a beginner or a seasoned developer, this feature gives you a performance-first, no-fuss approach to loading fonts.

What’s All the Buzz About?

Imagine a world where:

A Quick Peek at Google Fonts Integration

For starters, here’s how you can import a Google Font effortlessly:

// In your root component (e.g., app/layout.js)
import { Inter } from 'next/font/google';

const inter = Inter({
  subsets: ['latin'],
  // The "variable" assigns a CSS variable so you can reference it in your custom styles
  variable: '--font-inter',
});

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

Two important points here:

With this setup, you’re on your way to cleaner code, faster load times, and a consistent design system.


Importing and Utilizing Local Fonts in Next.js

Now that you’ve seen how effortlessly Google Fonts can be integrated, it’s time to get personal with your very own local fonts. Nothing beats the charm of a custom typeface that truly represents your unique style!

Importing a Local Font

Using next/font, importing a local font is quite straightforward. Instead of writing bulky @font-face declarations, simply use the localFont function:

// In a dedicated file, e.g., fonts.js
import localFont from 'next/font/local';

const myLocalFont = localFont({
  src: [
    {
      path: '../public/fonts/MyLocalFont-Regular.woff2',
      weight: '400',
      style: 'normal',
    },
    {
      path: '../public/fonts/MyLocalFont-Bold.woff2',
      weight: '700',
      style: 'normal',
    },
  ],
  // This creates a CSS variable (--font-myLocal) for versatile styling
  variable: '--font-myLocal',
  display: 'swap',
});

export default myLocalFont;