Font Optimization
Published at October 1, 2019
2 min read • Edit this post

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:

JS
1// Before
2<link
3 href="https://fonts.googleapis.com/css2?family=Inter&display=optional"
4 rel="stylesheet"
5/>
6
7// After
8<style data-href="https://fonts.googleapis.com/css2?family=Inter&display=optional">
9 @font-face{font-family:'Inter';font-style:normal...
10</style>

Usage

To add a web font to your Next.js application, override next/head. For example, you can add a font to a specific page:

JS
1// pages/index.js
2
3import Head from 'next/head'
4
5export default function IndexPage() {
6 return (
7 <div>
8 <Head>
9 <link
10 href="https://fonts.googleapis.com/css2?family=Inter&display=optional"
11 rel="stylesheet"
12 />
13 </Head>
14 <p>Hello world!</p>
15 </div>
16 )
17}

or to your entire application with a Custom Document.

JS
1// pages/_document.js
2
3import Document, { Html, Head, Main, NextScript } from 'next/document'
4
5class MyDocument extends Document {
6 render() {
7 return (
8 <Html>
9 <Head>
10 <link
11 href="https://fonts.googleapis.com/css2?family=Inter&display=optional"
12 rel="stylesheet"
13 />
14 </Head>
15 <body>
16 <Main />
17 <NextScript />
18 </body>
19 </Html>
20 )
21 }
22}
23
24export default MyDocument

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.

JS
1// next.config.js
2
3module.exports = {
4 optimizeFonts: false,
5}

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

© 2022 Nam Hoang Le. All Rights Reserved. Made with 🔥 passion, a ⌨️ keyboard and Next.js
githublinkedinmailto