howto

Fonts with NextJS

its easy but i needed to work it out

tags
nextjs
fonts
google

The nextjs font package is very cool, and makes it easy to have your fonts served up locally. This works just as well for local fonts that you've downloaded or something pulled straight from the google mother ship.

Lets hop to it.

Sample project

1
2
3
  cd $(mktemp -d)
  pnpx create-next-app
  cursor my-app

fonts and tailwind

app/globals.css

1
2
3
4
5
6
  
body {
  color: var(--foreground);
  background: var(--background);
  font-family: var(--font-sans);
}

Here I'ms setting font-headings to point to var(--font-national-park) which we will define below.

tailwind.config.ts

1
2
3
4
5
    theme: {
      extend: {
        fontFamily: {
          headings: ["var(--font-national-park)"],
        },

And a sample page:

app/page.tsx

1
2
3
4
5
6
7
8
9
  export default function Home() {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen">
        <h1 className="text-4xl font-headings">Hello World</h1>

        <p>This is my fancy new font.</p>
      </div>
    );
  }

Add the local font

I'm going to use the National Park Typeface

Download and the put the woff2 files in app/fonts/national-park

And then in app/layout.tsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
  import localFont from "next/font/local";

  const nationalPark = localFont({
    src: "./fonts/national-park/NationalPark-Regular.woff2",
    variable: "--font-national-park",
    display: "swap",
  });

  /* ... */

      <body className={`${nationalPark.variable} antialiased`}>{children}</body>

And done. The nationalPark.variable will handle all the font swapping magic.

Google fonts

Just as easy, in fact easier!

app/layout.tsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
  import { Fraunces } from "next/font/google";

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

  /* ... */
     

      <body className={`${fraunces.variable} antialiased`}>{children}</body>

And then tailwind.config.ts

1
2
3
  fontFamily: {
    headings: ["var(--font-fraunces)"],
  },

Previously

fragments

Starlink review

worth it

tags

Next

labnotes

astro and shadcn

new tailwind version

tags
astro
shadcn
tailwind