How to load custom fonts in a next.js app when it's in production?

Viewed 2374

Ok, so the question might sound extremely easy to be answered and trust me I've gone through the next js docs already! I think what I am experiencing in my next js project might be bug or something that I'm missing out.

I have custom fonts in .ttf format and they are inside a folder called ''fonts'' inside of the public folder, when I run my project with npm run dev and check it on localhost my fonts are imported and applied properly to the pages but in production my next js app just seems not to be able to load/find the fonts!

When I open my project in production the standard font is applied and in the console tab I can see an error message saying: Failed to load resource: the server responded with a status of 404 () and that message is associated with the fonts that were not loaded/found!

So the main problem is that in development everything works and expected and the error/bug doesn't happen, only in production that the fonts dont get loaded or found.

1 Answers

What I did in my previous project was

  1. Put the fonts in public/static or somewhere
  2. In the same directory as the fonts put a CSS file where the fonts are declared

Example: /public/fonts/fonts_style.css

    @font-face {
      font-family: 'Raleway';
      font-style: normal;
      font-weight: 400;
      src: url('../fonts/raleway-v19-latin-regular.eot'); /* IE9 Compat Modes */
      src: local(''),
           url('../fonts/raleway-v19-latin-regular.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
           url('../fonts/raleway-v19-latin-regular.woff2') format('woff2'), /* Super Modern Browsers */
           url('../fonts/raleway-v19-latin-regular.woff') format('woff'), /* Modern Browsers */
           url('../fonts/raleway-v19-latin-regular.ttf') format('truetype'), /* Safari, Android, iOS */
           url('../fonts/raleway-v19-latin-regular.svg#Raleway') format('svg'); /* Legacy iOS */
    }

  1. And import that in css in your pages/_document.js file.

Example:

render() {
    return (
        <Html>
            <Head>
                <link href="/fonts/fonts_style.css" rel="stylesheet"/>
            </Head>
        </Html>
    )
}
Related