question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unable to use self-hosted fonts using NextJS

See original GitHub issue

I am compiling SCSS and externalizing the resulting CSS into a file using sass-loader and extract-text-webpack-plugin in next.config.js. The compiled CSS file is being emitted into the .next folder. I also have some static resources, i.e. images and fonts that I’m referencing in the stylesheet. These static resources are also being compiled into the .next folder using the file-loader plugin in next.config.js.

However, when the page loads in the browser, I get a 404 on these resources because NextJS seems to prepend their paths with a /_next/webpack/ in the compiled CSS file:

http://54.197.22.181/_next/webpack/52a802f51895f840821c1083434f3d84.ttf

Is there any workaround to this issue? I really need to use SASS and keep the compiled CSS as an external file as against embedded style. So, the CSS-in-JS model isn’t what I’m comfortable with.

For reference, my project is hosted at https://github.com/amitsch666/nano.

Here’s the relevant rule I have in my next.config.js:

{ test: /\.(ttf|eot|png)$/, loader: 'file-loader' }

Here’s the font declaration in my scss file:

@font-face {
	font-family: 'Lemonada';
	src: url('../static/fonts/Lemonada/Lemonada-Regular.ttf');
	src: url('../static/fonts/Lemonada/Lemonada-Bold.ttf');
	src: url('../static/fonts/Lemonada/Lemonada-SemiBold.ttf');
	src: url('../static/fonts/Lemonada/Lemonada-Light.ttf');
}
  • I have searched the issues of this repository and believe that this is not a duplicate.

Update: I have managed to make my site work by routing all _next/webpack/static/ requests to /.next/static in my Express middleware. However, this still seems a tad hackish to me and would love to hear if someone has a more “standard” solution.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:13
  • Comments:19 (2 by maintainers)

github_iconTop GitHub Comments

42reactions
arunodacommented, Jul 28, 2017

One question?

Cant we use urls like this?

@font-face {
	font-family: 'Lemonada';
	src: url('/static/fonts/Lemonada/Lemonada-Regular.ttf');
	src: url('/static/fonts/Lemonada/Lemonada-Bold.ttf');
	src: url('/static/fonts/Lemonada/Lemonada-SemiBold.ttf');
	src: url('/static/fonts/Lemonada/Lemonada-Light.ttf');
}
17reactions
srghmacommented, Aug 26, 2017

Ok, I have found proper configuration, and Its fucking weird, because next don’t support custom webpack loaders, explanations in comments

    // Image task to use images in component directory
    config.module.rules.push({
      test: /\.(png|jpe?g|gif)$/i,
      use: [
        // using emit-file-loader just to shut up 'Cannot find module',
        // it will make copy of image in component directory
        {
          loader: 'emit-file-loader',
          options: {
            name: 'dist/[path][name].[ext]'
          }
        },
        // this will create image copy, that we will use,
        // output path - '/.next/static/longhash.png'
        // url - '/_next/static/longhash.png'
        {
          loader: 'url-loader',
          options: {
            outputPath: 'static/',
            publicPath: '/_next/',
            limit: 1000
          }
        },
        {
          loader: 'image-webpack-loader',
          options: {
            gifsicle: {
              interlaced: false
            },
            optipng: {
              optimizationLevel: 7
            },
            pngquant: {
              quality: '65-90',
              speed: 4
            },
            mozjpeg: {
              progressive: true,
              quality: 65
            }
          }
        }
      ]
    })

server/index.js

const express = require('express')
const next = require('next')
const path = require('path')

const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare()
.then(() => {
  const server = express()
  const staticDir = path.resolve(__dirname, '..', '.next/static')
  server.use('/_next/static', express.static(staticDir))

  server.get('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(port, (err) => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})

working example you can find here

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to use self-hosted fonts face using NextJS?
This is what I usually do: Put the fonts in public/static somewhere. In the same folder as the fonts put a CSS file...
Read more >
Basic Features: Font Optimization - Next.js
CSS and font files are downloaded at build time and self-hosted with the rest of your static assets. No requests are sent to...
Read more >
How to self-host fonts in NextJS - Level Up Coding
Using a Tailwind class to set our custom font. That's it, folks. This is how you can use custom fonts with NextJS.
Read more >
How to use self-hosted fonts face using NextJS?-Reactjs
[Solved]-How to use self-hosted fonts face using NextJS?-Reactjs ... styles.css # font files are in the same directory @font-face { font-family: 'Avenir'; ...
Read more >
Using Self-hosted Fonts in Nextjs | Hosh'ki Tsunoda
First, you need to create a /fonts folder inside /public folder and add all the fonts you wish to use( .eot, .woff, .woff2,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found