pwd > ninjaPixel/v2/man-drawer/fonts-in-next-js-13

Fonts in Next JS 13

Published

Next JS 13 has dropped with a tonne of great features, one being the new @next/font/google package which lets you self-host Google fonts, which means that Google can't track your users if you use one of their fonts. This package has also been optimised to reduce any font flickering while your user is waiting for your web font to load, the fallback font will be a system font most closely matched to your web font. Praise.

Your imported font will have a bit of a random name (e.g. "__Megrim_cb9663"), and because of that, you can't reference it directly in your CSS (for example, if you only want to use the imported font for headings). This also leads to the question of how to use multiple Google fonts on your site... The Next JS beta docs show how to set the site-wide font to a Google font, and it seems that the only way to use additional Google fonts would be to create new React components for them, which would be really annoying to have to do for all your h1 ... h6 elements etc.

I've discovered that the font directive allows you to create a CSS variable for it, and that's the key that unlocked this puzzle for me.

// layout.tsx
import './globals.css'
import {Megrim, Archivo_Narrow} from '@next/font/google';

const specialFont = Megrim({
    subsets: ["latin"],
    variable: "--font-special",
    weight: "400",
})

const regularFont = Archivo_Narrow({
    subsets: ["latin"],
    variable: "--font-regular",
    weight: "400",
})

export default function RootLayout({
                                       children,
                                   }: {
    children: React.ReactNode
}) {
    return (
        <html lang="en">
        <head/>
        <body className={`${specialFont.variable} ${regularFont.variable}`}>{children}</body>
        </html>
    )
}
/* globals.css */
h1, h2, h3, h4, h5, h6 {
    font-family: var(--font-special);
}

body {
    font-family: var(--font-regular);
}