typescriptbeginner

Font Optimization with next/font

Use next/font for automatic self-hosted font optimization with zero layout shift.

typescript
// app/layout.tsx
import { Inter, JetBrains_Mono } from 'next/font/google';
import localFont from 'next/font/local';

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

const jetbrainsMono = JetBrains_Mono({
  subsets: ['latin'],
  display: 'swap',
  variable: '--font-mono',
});

const calSans = localFont({
  src: '../fonts/CalSans-SemiBold.woff2',
  variable: '--font-cal',
  display: 'swap',
});

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html
      lang="en"
      className={`${inter.variable} ${jetbrainsMono.variable} ${calSans.variable}`}
    >
      <body className="font-sans">{children}</body>
    </html>
  );
}

// tailwind.config.ts — reference CSS variables
// fontFamily: {
//   sans: ['var(--font-inter)'],
//   mono: ['var(--font-mono)'],
//   cal: ['var(--font-cal)'],
// }

Use Cases

  • custom typography
  • performance optimization
  • preventing CLS

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.