Using Google Fonts in Next.js 10.2+

Photo by Alexander Andrews on Unsplash

To use Google Fonts in a Next.js application you would typically either create a custom Document file or create a custom Head component where you would use a regular HTML link tag to download the font:

This approach worked perfectly fine, however it had one disadvantage — for every font that needed to be downloaded the browser had to make an extra round trip to fetch the font declarations at run time. There were several plugins trying to solve this issue, next-google-fonts being a popular one.

Depending on the scale and type of your project it was most likely only a very minor performance issue, but since Next.js 10.2 this is no longer the case. This version comes with Automatic Webfont Optimization support when using web fonts (limited to Google Fonts and Typekit for now), which automatically inlines font CSS at build time, eliminating the round trip and thus improving performance.

The optimization comes out of the box and requires no further configuration. Below you can see an example of adding a Google Web Font by creating a custom _document file.

In case you do not want Next.js to automatically optimize your fonts, you can opt-out in the next.config.js file:

Happy coding!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store