0
0
NextJSframework~5 mins

Font optimization and self-hosting in NextJS

Choose your learning style9 modes available
Introduction

Fonts make your website look nice and readable. Optimizing and self-hosting fonts helps your site load faster and work well even without internet.

You want your website to load quickly on slow internet.
You want to use custom fonts without relying on external services.
You want to improve your website's privacy by not loading fonts from third parties.
You want consistent font display even if external font services are down.
You want to reduce layout shifts caused by late font loading.
Syntax
NextJS
import localFont from 'next/font/local';

const myFont = localFont({
  src: [
    {
      path: './fonts/MyFont-Regular.woff2',
      weight: '400',
      style: 'normal'
    },
    {
      path: './fonts/MyFont-Bold.woff2',
      weight: '700',
      style: 'normal'
    }
  ],
  variable: '--my-font'
});

Use next/font/local to load fonts stored in your project folder.

Define font weights and styles to match your font files for better control.

Examples
Loads a single font file for normal weight and style.
NextJS
import localFont from 'next/font/local';

const roboto = localFont({
  src: './fonts/Roboto-Regular.woff2',
  weight: '400',
  style: 'normal'
});
Loads multiple font styles and assigns a CSS variable for easy use.
NextJS
import localFont from 'next/font/local';

const openSans = localFont({
  src: [
    { path: './fonts/OpenSans-Regular.woff2', weight: '400', style: 'normal' },
    { path: './fonts/OpenSans-Italic.woff2', weight: '400', style: 'italic' }
  ],
  variable: '--open-sans'
});
Sample Program

This Next.js component uses a self-hosted font loaded with next/font/local. The font is applied using a CSS variable for consistent styling.

NextJS
import localFont from 'next/font/local';

const myFont = localFont({
  src: [
    { path: './fonts/MyFont-Regular.woff2', weight: '400', style: 'normal' },
    { path: './fonts/MyFont-Bold.woff2', weight: '700', style: 'normal' }
  ],
  variable: '--my-font'
});

export default function Home() {
  return (
    <main className={myFont.className} style={{ fontFamily: 'var(--my-font)' }}>
      <h1>Hello, this text uses a self-hosted font!</h1>
      <p>Font optimization helps this page load faster and look consistent.</p>
    </main>
  );
}
OutputSuccess
Important Notes

Always include multiple font weights and styles if your design needs them.

Place font files in the public/fonts or a similar folder accessible by your app.

Using next/font automatically optimizes fonts for best performance.

Summary

Self-hosting fonts improves speed and privacy.

Next.js provides next/font/local to easily load local fonts.

Use CSS variables to apply fonts consistently across your app.