Search code examples
next.jsfonts

Fonts are not loading on first visit or on refresh in next js


I am using @next/font/google for optimizing the performance in my project. But i am facing some issue, fonts are not loading on the first visit or when i refresh the page.

My implementation

pages/_appjs

import { Alegreya_Sans, Montserrat, IBM_Plex_Sans } from "@next/font/google";
const alegreya = Alegreya_Sans({
  weight: ["100", "300", "400", "500", "700"],
  variable: "--alegreya-font",
});
const montserrat = Montserrat({
  weight: "700",
  variable: "--montserrat-font",
});
const ibmSans = IBM_Plex_Sans({
  weight: ["400", "600"],
  variable: "--ibmSans-font",
});

function MyApp({ Component, pageProps }) {
  return (
    <>
      <style jsx global>{`
        :root {
          --alegreya-font: ${alegreya.style.fontFamily};
          --ibmSans-font: ${ibmSans.style.fontFamily};
          --montserrat-font: ${montserrat.style.fontFamily};
        }
      `}</style>
      <Component
        {...pageProps}
        isDarkTheme={isDark}
        setAllCategories={(value) => {
          setAllCategories(value);
        }}
        isMobile={isMobile}
      />
    </>
  );
}

export default MyApp;

Can someone figure out what am i missing in the above code?


Solution

  • I found solution for above. I was missing display property in the font instance. The code will look like

    const alegreya = Alegreya_Sans({
      weight: ['100', '300', '400', '500', '700'],
      variable: '--alegreya-font',
      display: 'swap'
    });
    const montserrat = Montserrat({
      weight: '700',
      variable: '--montserrat-font',
      display: 'swap'
    });
    const ibmSans = IBM_Plex_Sans({
      weight: ['400', '600'],
      variable: '--ibmSans-font',
      display: 'swap'
    });
    

    The display property was the missing parameter and this is solving issue for me. Now fonts are loading when refreshed or on first visit.