DEV Community

The best way to load and use Google Fonts in Next.js + Tailwind

Thomas Ledoux on February 15, 2021

I was setting up a new project today with Next.js and tailwindcss, and I had to use Roboto as a font. Since it's a Google Font, I was looking int...
Collapse
 
andrej_gajdos profile image
Andrej Gajdos

I am getting Lighthouse warning message:

Warnings: A <link rel=preconnect> was found for "fonts.gstatic.com" but was not used by the browser. Only use preconnect for important origins that the page will certainly request.

Collapse
 
thomasledoux1 profile image
Thomas Ledoux

Can you see any requests going to fonts.gstatic.com in your network tab?
Maybe Google changes the CDN for their fonts...

Collapse
 
andrej_gajdos profile image
Andrej Gajdos • Edited

Yes, I see imgur.com/a/zAnDtoE

Thread Thread
 
thomasledoux1 profile image
Thomas Ledoux

That’s strange… not sure why it’s giving that warning then

Thread Thread
 
andrej_gajdos profile image
Andrej Gajdos

I guess Lighthouse changed something, but thanks for the blog post anyway.

Collapse
 
marcvangend profile image
Marc

Thanks for sharing. AFAIK, these is no pages/_document file by default, you have to create it yourself to override the default behavior.
But I'm wondering: is it really necessary here to start using a customized _document? You could also use next/head in pages/_app to add the code snippet to the head.

Collapse
 
pabloverduzco profile image
Pablo

I think it is totally allowed.

Check this out: npmjs.com/package/next-google-font...

Collapse
 
thomasledoux1 profile image
Thomas Ledoux

Hey Marc,

I haven't tested this with pages/_app yet, but I assume it would work too since you would inject the code into the

section with next/head on every page.
Collapse
 
gabrielmlinassi profile image
Gabriel Linassi

There's an eslint rule that recommends to add it to the _document file. See nextjs.org/docs/messages/no-page-c...

Collapse
 
stevereid profile image
Steve Reid

Typescript doesn't like the onLoad="this.media='all'"
I get:
Type 'string' is not assignable to type 'ReactEventHandler'.
Any ideas?

Collapse
 
thomasledoux1 profile image
Thomas Ledoux

I noticed this too, but chose to ignore it:

<link
  rel="stylesheet"
href="https://fonts.googleapis.com/css2family=Podkova:wght@400;500;700&Roboto:wght@400;500;700&display=swap"
 media="print"
 // @ts-ignore
 onLoad="this.media='all'"
/>

Enter fullscreen mode Exit fullscreen mode
Collapse
 
ninest profile image
ninest

Thanks for the write up! Is it faster if I download the fonts and reference them locally rather than importing from fonts.google.com?

Collapse
 
thomasledoux1 profile image
Thomas Ledoux

My pleasure!
I'm guessing this would be faster, as you don't have to connect to an external source to fetch the fonts.
But the CDN of Google is very fast, so I'm not sure if the difference will be noticeable.
If you want to host your fonts locally, have a look at this site: google-webfonts-helper.herokuapp.c...