Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache fonts in NextJs?

I have two fonts which I am trying to display to the user, while there's no FOIT, and instead I am having a FOUT I'd like user not to re-download fonts each time they revisit the page.

I have added Font observer to add additional FOUT fallback functionality. _document.js

  componentWillMount() {
    if (process.browser) {
      const html = document.documentElement;
      html.classList.add('fonts-loading');
      const fontPoppins = new FontFaceObserver('Poppins');
      fontPoppins.load(null, 5000).then(() => {
        console.log('Poppins font has loaded.');
        html.classList.remove('fonts-loading');
        html.classList.add('fonts-loaded');
      }).catch(() => {
        html.classList.remove('fonts-loading');
        html.classList.add('fonts-failed');
      });
      const fontAvenir = new FontFaceObserver('Avenir');
      fontAvenir.load(null, 5000).then(() => {
        console.log('Avenir font has loaded.');
      }).catch(() => {
        html.classList.remove('fonts-loading');
        html.classList.add('fonts-failed');
      });
    }
  }
... (more code here)

render ( code here ) ...

// Additional FOUT?
        <Head>
          <link
            href="https://fonts.googleapis.com/css?family=Poppins:200,300,400,600,700,800,900&display=swap"
            rel="preload"
            as="font"
          />
           ... (more code here)
        </Head>

styles.css

html {
  font-family: sans-serif;
  -webkit-font-smoothing: antialiased;
}

.fonts-loaded html {
  font-family: Avenir, sans-serif;
}


@font-face {
  font-family: Avenir;
  src: url('/static/fonts/Avenir.ttc');
  font-display: swap;
  font-style: normal;
}

@font-face {
  font-family: Poppins;
  src: url('/static/fonts/Poppins-Regular.ttf');
  font-weight: 400;
  font-style: normal;
  font-display: swap;
}
like image 667
Alex Avatar asked Nov 07 '22 15:11

Alex


1 Answers

Use next.js custom server and you can set cache-control for each files.

https://github.com/zeit/next.js/#custom-server-and-routing

const parsedUrl = parse(req.url, true)
const { pathname, query } = parsedUrl

if(pathname === '/static/fonts/Avenir.ttc' || pathname === '/static/fonts/Poppins-Regular.ttf') {
    res.setHeader('Cache-Control', 'public,max-age=31536000');
}

For Google Font its look like cache-control had set already.

like image 76
vedsmith92 Avatar answered Nov 14 '22 07:11

vedsmith92