Skip to content

Next.js - How to optimize fonts

Posted on:May 3, 2022 at 00:00:00

Hey there! There is now next/font that does this way better. Use that instead

When using 3rd party fonts we have to make sure they are optimized, in the times before Next.js 10.2 you had to manually optimize them for example:

<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
    href="https://fonts.googleapis.com/css2?family=Merriweather+Sans&display=swap"
    rel="stylesheet"
/>
<link
    href="https://fonts.googleapis.com/css2?family=Squada+One:wght@400&display=swap"
    rel="stylesheet"
/>

After 10.2 Next.js can now optimize Google fonts and Typekit with a variety of font optimization, inside your _document.js you can now provide the font:

import Document, { Html, Head, Main, NextScript } from 'next/document'

class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head>
          <link
            href="https://fonts.googleapis.com/css2?family=Inter&display=optional"
            rel="stylesheet"
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

You can even provide the preferred display options as a query parameter :

Here are some articles you might like