0
0
NextJSframework~5 mins

Font optimization with next/font in NextJS

Choose your learning style9 modes available
Introduction

Using next/font helps your website load fonts faster and look better on all devices. It automatically optimizes fonts for speed and quality.

You want your website to load quickly with custom fonts.
You want to avoid slow font loading that causes text to jump or flash.
You want to use Google Fonts or local fonts easily in your Next.js app.
You want to improve your website's performance scores.
You want consistent font rendering across browsers and devices.
Syntax
NextJS
import { fontName } from 'next/font/google';

const myFont = fontName({
  subsets: ['latin'],
  weight: ['400', '700'],
  style: ['normal', 'italic'],
  variable: '--my-font-variable',
});

Replace fontName with the actual font you want, like Roboto or Inter.

You can specify subsets, weights, and styles to load only what you need.

Examples
This loads the Roboto font with normal weight 400 for Latin characters.
NextJS
import { Roboto } from 'next/font/google';

const roboto = Roboto({
  subsets: ['latin'],
  weight: ['400'],
});
This loads Inter font with normal and bold weights, including italic styles.
NextJS
import { Inter } from 'next/font/google';

const inter = Inter({
  subsets: ['latin'],
  weight: ['400', '700'],
  style: ['normal', 'italic'],
});
This loads a local font file and assigns a CSS variable for easy use.
NextJS
import localFont from 'next/font/local';

const myLocalFont = localFont({
  src: './fonts/MyFont.woff2',
  variable: '--my-local-font',
});
Sample Program

This Next.js component loads the Inter font with normal and bold weights. It applies the font style to the main content using the className provided by next/font. The font is optimized and loaded efficiently.

NextJS
import { Inter } from 'next/font/google';

const inter = Inter({
  subsets: ['latin'],
  weight: ['400', '700'],
});

export default function Home() {
  return (
    <main className={inter.className} style={{ padding: '2rem' }}>
      <h1>Hello, Next.js with optimized fonts!</h1>
      <p>This text uses the Inter font loaded and optimized by next/font.</p>
    </main>
  );
}
OutputSuccess
Important Notes

Using next/font automatically preloads fonts for faster loading.

Only include the font weights and styles you need to keep your site fast.

Fonts loaded with next/font avoid layout shifts caused by late font loading.

Summary

next/font helps load fonts faster and better in Next.js apps.

You can load Google Fonts or local fonts with simple code.

Optimizing fonts improves user experience and website speed.