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:

<link href="https://fonts.googleapis.com/css2family=Lato&display=swap" rel="stylesheet" />

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:

next.config.js

Happy coding!

--

--

--

Fullstack JavaScript Developer | UI&UX Enthusiast

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to Create Animated URLs with JavaScript

How I Analyzed All NPM Dependency Licenses in One Go

Adding CORS headers in API Management via Policy

Build a Responsive Slideout Drawer

Quicktip: PC System Shutdown after Rendering — Houdini

Lit-Html and Responsible Advocacy

45 NPM Packages to Solve 16 React Problems

Angular: Set up jQuery in Your StackBlitz Project Without Any Errors

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
Adrian-Gabriel Manduc

Adrian-Gabriel Manduc

Fullstack JavaScript Developer | UI&UX Enthusiast

More from Medium

Starting with Next.js

How to configure EsLint in Nextjs?

How to configure EsLint in Nextjs By Rajdeep Singh

Simplifying Lazy Loading in Next.js

NextJs. What Next?