Contents

Using Google Fonts with Nextjs and TailwindCSS


Web projects use system default fonts if we don’t speficy fonts to them. Therefore, same project may look different depends on system or browser. My prefered way to add custom fonts to site is using google fonts. One of my all time favarite fonts is Inter, it looks pleased in all screens.

Unsurprisingly, I came across same problem as my previous post about adding fontawesome icons to nextjs project when I tried to add google fonts to my nextjs project. A little bit research shows there are 3 differeny ways to do it:

  1. Add google fonts cdn link
  2. Add through @import CSS rule
  3. Use npm package
  4. Host fonts locally

Chose font family and sizes

First we need to go to google fonts to choose a font family and their sizes. Here I am choosing Inter and size 100-600. The link is https://fonts.google.com/specimen/Inter?query=inter#standard-styles. On the right side, there will be selected sizes and font embedding methods show up.

google fonts

Nextjs doesn’t have normal index.html template file but has a _document.js file instead. A custom ducoment is commonly used to augment nextjs applications' html and body tags. Details can be found at their custom document documentation.

In short, we need to create a file ./pages/_documents.js and add google fonts link to the default document. The end result will look like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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 href="https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700&display=swap" rel="stylesheet">
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

Add through @import CSS rule

On the google fonts website, @import is another embedding method beside <link>. I usually create a standard nextjs project through yarn create next-app. Nextjs uses App component to initialize pages. This is done through ./pages/_app.js in empty nextjs project. The following is the default content of _app.js file. We can keep it the same and import google font CSS in ../styles/globals.css (first line of _app.js). More about customizing App can be found here.

1
2
3
4
5
6
7
import '../styles/globals.css'

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp

Go to globals.css and add this to the first line:

1
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700&display=swap');

Of course we are not limited to the globals.css file, anything like custom.css can also be used and import google fonts. Just remember to import that CSS file into _app.js. This is my favarite way to use google fonts with nextjs because I am also import fontawesome CSS into my globals.css.

Use npm package

There is a npm package next-google-fonts helps for loading google fonts fast and asynchronously into nextjs projects. If you don’t mind adding another npm package to take care of this task then this is a good option.

I think this is an overhead as it needs not only adding a npm package but also a custom Head component. The details can be found on its github documention.

Host fonts locally

This is an old fashion way for adding fonts. Download selected fonts file from google fonts and put it into public/fonts folder. Then the fonts can be frefered by @font-face CSS rule.

1
2
3
4
5
6
7
@font-face {
  font-family: 'Inter';
  font-style: normal;
  font-weight: 400;
  font-display: swap;
  src: local('Inter'), url(/fonts/Inter.woff2) format('woff2');
}

Add fontfamily to tailwind

Now the font family is added to nextjs. The final step is let tailwind know we want to use this new font. This can be done through tailwindcss configuration.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// tailwind.config.js
const defaultTheme = require('tailwindcss/defaultTheme')

module.exports = {
    theme: {
      fontFamily: {
       'sans': ['Inter', ...defaultTheme.fontFamily.sans],
      }
    }
    variants: {
      extend: {
        // enable for hover and focus variats
       fontFamily: ['hover', 'focus'],
      }
    }
}

Now we are all set!