Skip to content

Latest commit

 

History

History
91 lines (67 loc) · 2.86 KB

font-optimization.md

File metadata and controls

91 lines (67 loc) · 2.86 KB
description
Next.js supports built-in web font optimization to inline font CSS. Learn more here.

Font Optimization

Since version 10.2, Next.js has built-in web font optimization.

By default, Next.js will automatically inline font CSS at build time, eliminating an extra round trip to fetch font declarations. This results in improvements to First Contentful Paint (FCP) and Largest Contentful Paint (LCP). For example:

// Before
<link
  href="https://fonts.googleapis.com/css2?family=Inter&display=optional"
  rel="stylesheet"
/>

// After
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<style data-href="https://fonts.googleapis.com/css2?family=Inter&display=optional">
  @font-face{font-family:'Inter';font-style:normal...
</style>

Usage

To add a web font to your Next.js application, add the font to a Custom Document.

// pages/_document.js

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

Although it's possible to add fonts in a page with next/head it comes with some drawbacks:

  • It only applies the font to that particular page.
  • The font optimization will only work on page load, not on client side navigation.
  • It won't work with a streaming architecture.

Thus it's highly recommended to add the font in a Custom Document, like in the code snippet above.

Automatic Webfont Optimization currently supports Google Fonts and Typekit with support for other font providers coming soon. We're also planning to add control over loading strategies and font-display values.

See Google Font Display for more information.

Note: Font Optimization does not currently support self-hosted fonts.

Disabling Optimization

If you do not want Next.js to optimize your fonts, you can opt-out.

// next.config.js

module.exports = {
  optimizeFonts: false,
}

Related

For more information on what to do next, we recommend the following sections: