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.
Imagine a world where:
@font-face rules.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:
.className: This auto-generated CSS class applies the font styling globally when added to your root element..variable: By assigning a CSS variable (in this case, -font-inter), you gain the flexibility to reference the font in plain CSS, SCSS, or Tailwind configurations.With this setup, you’re on your way to cleaner code, faster load times, and a consistent design system.
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!
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;