DEV Community

Gabriel Linassi
Gabriel Linassi

Posted on

How to load local fonts in NextJS (Optimal way)

This is my solution to load custom local fonts in NextJS.

Add the font on the /public folder. woff2 extension is good enough as you can see on caniuse

PS. If you have a problem regarding vertical alignment, make sure to use this awesome tool to fix it. Just load the font and select "fix vertical metrics". Then use this new font instead.

Import the font with CSS @font-face like below:

@font-face {
  font-family: 'Bebas Neue';
  src: url('/fonts/BebasNeue/BebasNeue-Regular.woff2') format('woff2');
  font-weight: 400;
  font-display: swap;
}
Enter fullscreen mode Exit fullscreen mode

Optimize the font by preloading it. Add the snippet below on _Document file:

<link
  rel="preload"
  href="/fonts/BebasNeue/BebasNeue-Regular.woff2"
  as="font"
  crossOrigin=""
/>
Enter fullscreen mode Exit fullscreen mode

PS. It's not needed to add any caching mecanism. Nextjs takes care of it for static assets. More details here

Make sure to test it on different browsers (safari, chrome, firefox and edge) with lambdatest for example.

References:
https://leerob.io/blog/fonts
https://github.com/vercel/next.js/discussions/25389

Top comments (0)