patterntypescriptnextjsTip
next/font: self-hosted fonts with zero layout shift
Viewed 0 times
Next.js 13.0+ for next/font
next/fontGoogle Fontsself-hosted fontsfont variablelayout shiftFOUT
Problem
Loading Google Fonts via a <link> tag causes network requests to Google's servers, impacts privacy, and causes layout shift (FOUT/FOIT) when the font loads after the page. Custom fonts need complex self-hosting setup.
Solution
Use next/font/google or next/font/local for automatic self-hosting and size-adjust:
// app/layout.tsx
import { Inter, Playfair_Display } from 'next/font/google';
const inter = Inter({
subsets: ['latin'],
display: 'swap',
variable: '--font-inter',
});
const playfair = Playfair_Display({
subsets: ['latin'],
weight: ['400', '700'],
variable: '--font-playfair',
});
export default function RootLayout({ children }) {
return (
<html lang='en' className={
<body className={inter.className}>{children}</body>
</html>
);
}
// tailwind.config.ts
export default {
theme: {
extend: {
fontFamily: {
sans: ['var(--font-inter)', 'system-ui'],
serif: ['var(--font-playfair)', 'serif'],
},
},
},
};
// Local font
import localFont from 'next/font/local';
const myFont = localFont({
src: './fonts/MyFont.woff2',
variable: '--font-my',
});
// app/layout.tsx
import { Inter, Playfair_Display } from 'next/font/google';
const inter = Inter({
subsets: ['latin'],
display: 'swap',
variable: '--font-inter',
});
const playfair = Playfair_Display({
subsets: ['latin'],
weight: ['400', '700'],
variable: '--font-playfair',
});
export default function RootLayout({ children }) {
return (
<html lang='en' className={
${inter.variable} ${playfair.variable}}><body className={inter.className}>{children}</body>
</html>
);
}
// tailwind.config.ts
export default {
theme: {
extend: {
fontFamily: {
sans: ['var(--font-inter)', 'system-ui'],
serif: ['var(--font-playfair)', 'serif'],
},
},
},
};
// Local font
import localFont from 'next/font/local';
const myFont = localFont({
src: './fonts/MyFont.woff2',
variable: '--font-my',
});
Why
next/font downloads and self-hosts Google Fonts at build time, eliminating runtime requests to Google and improving privacy compliance (GDPR). It automatically adds size-adjust CSS to minimize layout shift during font swap.
Gotchas
- Font files are downloaded at build time — CI/CD needs internet access during next build
- Each font call creates a separate optimized CSS chunk — don't call Inter() in multiple files
- The variable prop is needed for Tailwind or custom CSS variable usage; className applies the font directly
- Fonts with many weights/variants increase bundle size — only include what you use
Code Snippets
Google Font with CSS variable
import { Inter } from 'next/font/google';
const inter = Inter({ subsets: ['latin'], variable: '--font-inter' });
// In layout: <html className={inter.variable}>Context
When adding custom or Google Fonts to a Next.js application
Revisions (0)
No revisions yet.