Using Google Fonts with Next.js and Tailwind CSS

Fortunately, Next.js version 13.2 has added a new built-in feature for more efficient font usage. This feature makes it super easy to use Google Fonts.

The next/font system has its own automatic feature that hosts each font file automatically. With this feature, web fonts are optimized and loaded without any layout changes.

Also, this font system provides easy access to all Google Fonts while maintaining privacy and efficiency. During the build process, CSS and font files are hosted along with other static files automatically and no requests are sent to Google.

To get started, import the font you would like to use from next/font/google as a function. It's recommend using variable fonts for the best performance and flexibility.

To use the font in all your pages, add it to _app.js file under pages directory as shown below.

import type { AppProps } from 'next/app'
import { Vazirmatn } from 'next/font/google'
import '../styles/globals.css'

const vazirmatn = Vazirmatn({
  subsets: ['latin', 'arabic'],
  variable: '--font-vazirmatn',
})

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <>
      <div className={`${vazirmatn.variable} font-sans`}>
        <Component {...pageProps} />
      </div>
    </>
  )
}

export default MyApp

In the following example, the Vazirmatn font is being used (you can use any font from Google). Similar to the above example, load your desired font using the variable option with a custom name for your CSS variable. Then, use vazirmatn.variable to add the CSS variable to your template code.

Finally, add the CSS variable to your Tailwind CSS configuration.

const { fontFamily } = require('tailwindcss/defaultTheme')

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    './pages/**/*.{js,ts,jsx,tsx}',
    './components/**/*.{js,ts,jsx,tsx}',
  ],
  theme: {
    extend: {
      fontFamily: {
        sans: ['var(--font-vazirmatn)', ...fontFamily.sans],
      },
    },
  },
  plugins: [],
}