DEV Community

Jose Marcilio
Jose Marcilio

Posted on

How to use @next/font, from Next.js 13, with TailwindCSS

Recently, Next.js released their latest version, Next.js 13. One of the new features is the Fonts Optimization. It removes the external requests for custom fonts, improving performance and privacy. According to the docs:

@next/font includes built-in automatic self-hosting for any font file. This means you can optimally load web fonts with zero layout shift, thanks to the underlying CSS size-adjust property used.

This new font system also allows you to conveniently use all Google Fonts with performance and privacy in mind. CSS and font files are downloaded at build time and self-hosted with the rest of your static assets. No requests are sent to Google by the browser.

The usage is very simple:

  1. Install the package:
    pnpm add @next/font

  2. Then import it and apply to your root node:

import { Inter } from '@next/font/google';
import { PropsWithChildren } from "react";

const inter = Inter();

export default function RootLayout({ children }: PropsWithChildren) {
  return (
    <html lang="en" className={inter.className}>
      <body>{children}</body>
    </html>
  );
}
Enter fullscreen mode Exit fullscreen mode

But if you are using TailwindCSS in your project, things can be a bit different. You can't import this font directly in your tailwind.config.js. So what you need is apply the font-family to a CSS variable, and use this variable in your config.

Your layout:

import './globals.css';
import { PropsWithChildren } from "react";
import { Inter } from "@next/font/google";

const inter = Inter({ variable: "--inter-font" });

export default function RootLayout({ children }: PropsWithChildren) {
  return (
    <html className={inter.variable}>
      <head></head>
      <body>{children}</body>
    </html>
  );
}
Enter fullscreen mode Exit fullscreen mode

Your tailwind.config.js:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./app/**/*.{js,ts,jsx,tsx}",
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    fontFamily: {
      sans: ["var(--inter-font)", "ui-sans-serif", "system-ui"],
      display: ["var(--inter-font)", "Oswald"],
      body: ["var(--inter-font)", '"Open Sans"'],
    },
    extend: {},
  },
  plugins: [require("daisyui")],
};
Enter fullscreen mode Exit fullscreen mode

Hope it could help your setup!

Top comments (0)