Next.js
Beginner
1 min read
next/font for Optimised Web Fonts
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',
});