Adding Google Font in Next.js

Last updated on 2 Sep, 2022

Next.js has a default Document structure using which it renders all pages. We can override that structure using pages/_document.js.

For this article, let us try adding Luckiest Guy Google font. Here is the link code which I got from Google.

<link rel="preconnect" href="" />
<link rel="preconnect" href="" crossorigin />

We need to add above code in pages/_document.js. Here is the complete contents of the file:

import Document, { Html, Head, Main, NextScript } from "next/document";

class MyDocument extends Document {
  render() {
    return (
          <link rel="preconnect" href="" />
          <link rel="preconnect" href="" crossOrigin />
          <Main />
          <NextScript />

export default MyDocument;

In order to make valid JSX syntax, we need to add closing tags(/>) for all <link/>s. Also crossorigin needs to be changed to crossOrigin to fix eslint errors.

Ok! Now, all pages can use the font family to show Luckiest Guy font. In my case, create-next-app created a styles/globals.css for global style setting. I therefore need to update the font-family there.

body {
  padding: 0;
  margin: 0;
  font-family: "Luckiest Guy", cursive;

We can now place any text in any page in the site to check if the new font is applied. For me, my header in home page looks like this:

Google font