next.js fonts: how to eliminate layout shift - By Sourav Mishra (@souravvmishra)

tired of your text jumping around on load? here is how to use next/font to fix cls and optimize your fonts.

BySourav Mishra2 min read

fonts are usually the heaviest things on a page. if you load them wrong, your text flashes and the layout shifts everywhere.

let's see how next/font fixes this instantly.


why use next/font?

the built-in next/font package is magic because:

  1. it self-hosts: no weird google server requests.
  2. zero layout shift: it creates a perfect fallback font so nothing jumps around.
  3. preloads: critical fonts are ready immediately.

1. setting up google fonts

always try to use variable fonts so you only download one file for all font weights.

// app/layout.tsx
import { Inter } from "next/font/google";
import "./globals.css";

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

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

2. hooking it up to tailwind

just update your config to listen to that CSS variable we just made.

// tailwind.config.ts
import { fontFamily } from "tailwindcss/defaultTheme";

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

now font-sans uses your optimized font. super easy.


3. what about local fonts?

if you have custom brand fonts, use next/font/local.

import localFont from "next/font/local";

const myFont = localFont({
  src: [
    {
      path: "./fonts/MyFont-Regular.woff2",
      weight: "400",
    },
    {
      path: "./fonts/MyFont-Bold.woff2",
      weight: "700",
    },
  ],
  variable: "--font-brand",
});

pro tip: always use subsets: ["latin"] so you don't download random alphabets you don't use.

so yeah, just use next/font and you'll never worry about layout shifts again.

want more performance tips? check out my react suspense guide.

Share this post

Cover image for next.js fonts: how to eliminate layout shift

You might also like

See all