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:
JS1// Before2<link3 href="https://fonts.googleapis.com/css2?family=Inter&display=optional"4 rel="stylesheet"5/>67// After8<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:
JS1// pages/index.js23import Head from 'next/head'45export default function IndexPage() {6 return (7 <div>8 <Head>9 <link10 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
.
JS1// pages/_document.js23import Document, { Html, Head, Main, NextScript } from 'next/document'45class MyDocument extends Document {6 render() {7 return (8 <Html>9 <Head>10 <link11 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}2324export 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.
JS1// next.config.js23module.exports = {4 optimizeFonts: false,5}
Related
For more information on what to do next, we recommend the following sections: