DEV Community

Gabriel Linassi
Gabriel Linassi

Posted on

1 1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay