Published on

Add Google Fonts to Next.js app

Authors
google-fonts-banner

Let me start this article by saying that Google Fonts is an awesome website that let's you download free legal fonts for your website. Let's look at the steps on how to add them on Next.js app below.

Step 1: Pick your fonts

First and foremost step is to pick the font of your choice. For this article, I am picking Roboto with Thin and Regular font weight. Once you select it, copy the code that comes up for <link>. It should look something like below for your fonts.

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@100;400&display=swap" rel="stylesheet">

Step 2: Create _document.js file

Next step is to create _document.js file under /pages folder. Once created, you can add your fonts to your document like below by extending Document class.

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

class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head>
          <link rel="preconnect" href="https://fonts.googleapis.com" />
          <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
          <link
            href="https://fonts.googleapis.com/css2?family=Roboto:wght@100;400&display=swap"
            rel="stylesheet"
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

<Html>, <Head>, <Main> and <NextScript> is mandatory to render the page peroperly.

That's all you have to do to add google fonts to your Next.js app. Now you can reference Roboto font in your css like below.

body {
  font-family: 'Roboto', sans-serif;
  font-weight: 100;
}

Feel free to reach out if this doesn't work for you.