Next.js Discord

Discord Forum

Font optimization problem

Unanswered
Cuvier’s Dwarf Caiman posted this in #help-forum
Open in Discord
Cuvier’s Dwarf CaimanOP
Hi. Does anyone know how to optimize local fonts? I am using Next.js with Sass modules.

In my _fonts.scss file I define the variables and then import and use them in each styles file of each of my components.

(The .mkv is a video showing the problem)

7 Replies

What version of nextjs are you using?
Cuvier’s Dwarf CaimanOP
13.4.3
The way to optimize your font in Next.js 13 is:

// layout.tsx
import localFont from 'next/font/local'

const wallop = localFont({
  src: [
    {
      path: './Wallop-Medium.woff2',
      weight: '600',
      style: 'normal',
    },
  ],
  variable: "$wallop",
  display: "swap"
})


Then you can make this font available by adding it to body className.

// layout.tsx
export default function RootLayout({ children } : { children: React.ReactNode }) {
  return (
    <html lang="en" className={`${wallop.variable} other-classes`}>
      <body>{children}</body>
    </html>
  )
}

Source: https://nextjs.org/docs/app/building-your-application/optimizing/fonts#local-fonts
Cuvier’s Dwarf CaimanOP
Thanks, as you can see I use two font styles in my app, that way it would work as a "default" font? Then if I want to place the other style, do I do it from SASS or using "roobert.variable" in the label?
You can add as many fonts as you want:

const wallop = localFont({
  src: [
    {
      path: './Wallop-Medium.woff2',
      weight: '600',
      style: 'normal',
    },
  ],
  variable: "$wallop",
  display: "swap"
})

const roobert = localFont({
  src: [
    {
      path: './Roobert-Medium.woff2',
      weight: '600',
      style: 'normal',
    },
  ],
  variable: "$roobert",
  display: "swap"
})

export default function RootLayout({ children } : { children: React.ReactNode }) {
  return (
    <html lang="en" className={`${wallop.variable} ${roobert.variable} other-classes`}>
      <body>{children}</body>
    </html>
  )
}
Cuvier’s Dwarf CaimanOP
Thanks!!
Don't forget to mark this as answered to clean the forum. @Cuvier’s Dwarf Caiman