Easy Method: How to add Next 13 Optimized next/font with Tailwind CSS

Surjith S M

Surjith S M

· 1 min read

Next.js 13 introduced a new feature that made it easier to implement Google or custom fonts into their projects using the next/font package. Let's see how to implement this in both /app directory and /pages directory.

App Directory

First import your font from google and add the required class to the <html> tag using the RootLayout page. See the code below.


import { Inter } from "next/font/google";

const inter = Inter({
  subsets: ["latin"],
  variable: "--font-inter",
  display: "swap"
});


export default function RootLayout({children}) {
  return (
    <html
      lang="en" 
      className={inter.variable}>
      <body>
        {children}
      </body>
    </html>
  );
}

Now, in tailwind.config.js, you can use them as follows:

/** @type {import('tailwindcss').Config} */

const { fontFamily } = require("tailwindcss/defaultTheme");

module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
    "./app/**/*.{js,ts,jsx,tsx}",
  ],

  theme: {
    extend: {
      fontFamily: {
        sans: ["var(--font-inter)", ...fontFamily.sans],
      },
    },
  },
  plugins: [],
};

That's it. The font will now be available globally on our projects.

Pages Directory

If you are using Pages Directory with Tailwind CSS, implementing custom fonts can be a bit of a challenge. The official documentation suggests wrapping a div with a className, but not every developer wants to go that route. In this blog post, I'll show you an easy alternative method for implementing custom fonts in Next.js with Tailwind CSS.

First, open _app.js and import the google font or local font using next/font. Then add a <style> tag inside the return function to create our custom :root variable.

See example code:

// pages/_app.js

import "@/styles/globals.css";
import { Inter } from "next/font/google";

const inter = Inter({ subsets: ["latin"] });
 
export default function App({ Component, pageProps }) {
  return (
    <>
      <style jsx global>
        {`
:root {
--font-inter: ${inter.style.fontFamily}; } `} </style> <Component {...pageProps} /> </> ); }

Now, in tailwind.config.js, you can use them as follows:

/** @type {import('tailwindcss').Config} */

const { fontFamily } = require("tailwindcss/defaultTheme");

module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
    "./app/**/*.{js,ts,jsx,tsx}",
  ],

  theme: {
    extend: {
      fontFamily: {
        sans: ["var(--font-inter)", ...fontFamily.sans],
      },
    },
  },
  plugins: [],
};

That's it. We are done. Now our custom font is available globally without any extra class or div.

Subscribe to Newsletter

Provide your email to get email notification when we launch new products or publish new articles