Adding custom fonts to your Next JS project is super easy and performant. Fonts get downloaded at build time, which means great performance and no nasty fall back font flash and shifting of content on the page when your page first loads.

There are multiple factors we need to take into consideration when building our websites and performance is one of the biggies. We need to do everything we can to make our sites load as quickly as possible, for good user experience and for search engines. The slower our pages load the worse they will rank in the search engines and the more annoyed your user will be, fortunately the good folks at Next are doing a fine job in doing everything they can to take care of all the heavy lifting for us.

In Next JS 13 and above, Next now automatically optimises our fonts for us. We just need to import the fonts we want and store them in a variable (font loader object), then pass it to the component we want to use it in. So in this case we add it to the body element, that way it will be used throughout the whole document.

import {Inter} from 'next/font/google';
const inter = Inter({subsets: ['latin']});

export default function RootLayout({children}){
 return (
   <html lang='en'>
     <body className={`${inter.className}`}>
       <div id='wrapper'>{children}</div>
     </body>
   </html>
 );
}

But what if we want to use that custom font in our stylesheets... highly likely! for this, we can take advantage of CSS variables. All we need to do here is set the variable option on our font loader object:

 import {Inter} from 'next/font/google';
 const inter = Inter({
    subsets: ['latin'],
    variable: '--font-inter'
  });

export default function RootLayout({children}){
  return (
    <html lang='en'className={`${inter.variable}`}>
      <body>
        <div id='wrapper'>{children}</div>
      </body>
    </html>
  );
}

Then use that font wherever needed in our css files.

 .text{
   font-family: var(--font-inter);
 }

The font loader object has a whole load of useful options including:

  • font weight
  • font style
  • variable
  • src (if you want to host your own fonts)

    and many many more.