Local fonts
overview and setup
We place the font files, such as the woff2 files, in a directory such as src/fonts.
We provide them to Next.js with localFont({}). We call localFont({}) in _app.tsx, and provide the paths to the fonts in a src array. We also set the name of the CSS variable that will hold the font stack in variable.
We assign the result to a variable, whose name is important: it determines the CSS-facing font-name, that is, the one declared in @font-face and that we may use in font-family:
import localFont from "next/font/local"
const altinnDin = localFont({
src: [
{
path: "../fonts/Altinn-DINExp.woff2",
weight: "400",
style: "normal",
},
{
path: "../fonts/Altinn-DINExp-Italic.woff2",
weight: "400",
style: "italic",
},
{
path: "../fonts/Altinn-DINExp-Bold.woff2",
weight: "700",
style: "normal",
},
],
variable: "--font-altinn-din", // set the CSS variable's name.
})
Next.js generates the @font-face rules to import each face. It sets font-display: swap by default. To remove layout shift on font swap, it modifies the fallback font such as Arial to fit the metrics of the local font we added.
@font-face {
font-family: altinnDin;
src: url("../media/Altinn_DINExp-s.p.61719b9f.woff2") format("woff2");
font-display: swap;
font-weight: 400;
font-style: normal;
}
set the font immediately with a Next.js-generated class
Next.js generates a CSS class, which, when added to an element, makes it use the local font (along with a fallback font). The class becomes available at myFont.className.
.altinndin_6897fd0e-module__QFpdhW__className {
font-family: altinnDin, altinnDin Fallback;
}
If we add the class to a high-level wrapper, the font effectively becomes the site's global font. For example, in _app.tsx:
<div className={altinnDin.className}>
<Component {...pageProps} />
</div>
expose the font as a CSS variable, by using a Next.js-generated class
The class, when added to an element, merely defines a CSS variable, whose name was defined in localFont({}). The class becomes available at myFont.variable.
.altinndin_6897fd0e-module__QFpdhW__variable {
--font-altinn-din: "altinnDin", "altinnDin Fallback";
}
We add the class to a high-level wrapper. For example, in _app.tsx:
<div className={altinnDin.variable}>
<Component {...pageProps} />
</div>
It's up to elements to set font-family with that variable:
h1 {
font-family: var(--font-altinn-din);
}