How to load and use Google Fonts in Next.js 12 + Tailwind 3

How to Add a Custom Google Font to a Next.js and Tailwind CSS App

Nikhil M

1 min read

On this page 3

Where?

In your /pages folder, you should have a _document[.js/.tsx] file. In this file, we can easily adapt the <head> section using the next/head module. This will be applied on every page by Next.js.

Next.JS Part

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

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    return { ...initialProps }
  }

  render() {
    return (
      <Html>
        <Head>
          <link
            rel="preconnect"
            href="https://fonts.gstatic.com"
            crossOrigin="true"
          />
          <link
            rel="preload"
            as="style"
            href="https://fonts.googleapis.com/css2?family=Oxygen:wght@400;500&display=swap"
          />
          <link
            rel="stylesheet"
            href="https://fonts.googleapis.com/css2?family=Oxygen:wght@400;500&display=swap"
            media="print"
            onLoad="this.media='all'"
          />
          <noscript>
            <link
              rel="stylesheet"
              href="https://fonts.googleapis.com/css2?family=Oxygen:wght@400;500&display=swap"
            />
          </noscript>
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

Tailwind Part

This is super easy in Tailwind, this just requires an extension of the default theme: In your tailwind.config.js

const defaultTheme = require('tailwindcss/defaultTheme')

module.exports = {
  theme: {
    extend: {
      fontFamily: {
        sans: ['Oxygen', ...defaultTheme.fontFamily.sans]
      }
    }
  },
  variants: {
    extend: {}
  },
  plugins: []
}

Thats it, you have done it.

This article originally appeared on lightrains.com

Leave a comment

To make a comment, please send an e-mail using the button below. Your e-mail address won't be shared and will be deleted from our records after the comment is published. If you don't want your real name to be credited alongside your comment, please specify the name you would like to use. If you would like your name to link to a specific URL, please share that as well. Thank you.

Comment via email

Share this article

Topic

More on Product Engineering

Building and shipping web products: React, Next.js, Node.js, APIs, performance and deployment.

Written by

Nikhil M

Managing Director

Entrepreneur / Privacy Freak / Humanist / Blockchain / AI / Digital Security / Online Privacy

Keep reading

Ready to build your next AI product?

Get a free consultation and project quote for AI, software or product development, tailored to your goals.

  • No-obligation consultation
  • Clear scope and timeline
  • Transparent pricing
Get your free project quote