Search code examples
cssreactjsnext.jsfontslocal

Local font not loading in NextJs


I am trying to load the local font 'Stigfier' through my 'styles/styles.css' global css and it is not loading. My google fonts loaded in the '_document.jsx' work fine.

  @font-face {
    font-family: Stigfier;
    src:
         url('/../public/fonts/stigfier/Stigfier.woff') format('woff'),
         url('/../public/fonts/stigfier/Stigfier.woff2') format('woff2'),
         url('/../public/fonts/stigfier/Stigfier.ttf') format('truetype'),
         url('/../public/fonts/stigfier/Stigfier.otf') format('opentype');
    font-weight: 400;
    font-style: normal;
    font-display: swap;
}

body {
    font-family: Stigfier;
}

But it is not loading, same with the recommended way in the Nextjs website docs:

import localFont from '@next/font/local'

const stigfier = localFont({src: '/../public/fonts/stigfier/Stigfier.woff2'})


export default function MyApp({ Component, pageProps }) {
  return (
    <div className={stigfier.className}>
     <Component {...pageProps} />
   </div>
  )
}

and even creating a link in the '_document.jsx' like so:

        <link
        rel="preload"
        href="/../public/fonts/stigfier/Stigfier.ttf"
        as="font"
        type="font/ttf"
        crossOrigin="anonymous"
        />

Solution

  • As your fonts are already in the public folder you do not need to specify it.

     @font-face {
        font-family: Stigfier;
        src:
             url('/fonts/stigfier/Stigfier.woff') format('woff'),
             url('/fonts/stigfier/Stigfier.woff2') format('woff2'),
             url('/fonts/stigfier/Stigfier.ttf') format('truetype'),
             url('/fonts/stigfier/Stigfier.otf') format('opentype');
        font-weight: 400;
        font-style: normal;
        font-display: swap;
    }
    
    body {
        font-family: Stigfier;
    }