skip to Main Content

I am trying to use the "next" way of adding fonts. However I feel like the way they explain it seems extremely complicated just to preload a font.

I tried to export a function creating the font and then using the variable tag to create a css var. This doesnt work, I have imported the font into my page.js file. Then I exported a const function creating the font with this variable;

import { Oxygen } from "next/font/google";

export const oxygen = Oxygen({
    display: 'swap',
    variable: '--font-oxygen',
    subsets: ['latin'],
})

Then tried to use it in the linked css style sheet setting the font family to the exact var using;

font-family: var(--font-oxygen);

I am trying to learn Nextjs and this is just putting me off. It wont work, I dont want to set the class name of my html attributes to the font class name either unless I am doing it all wrong.

2

Answers


  1. If this is a font used in your entire application you can import the font in index.js (when using Pages Router) or in the layout.js in your app folder (when using App Router). You don’t have to add it to your CSS.

    Then add classname={oxygen.className}

    For Pages Router example;

    import { Oxygen } from 'next/font/google'
     
    const oxygen = Oxygen({ 
        display: 'swap',
        variable: '--font-oxygen',
        subsets: ['latin'],
    })
     
    export default function MyApp({ Component, pageProps }) {
      return (
        <main className={oxygen.className}>
          <Component {...pageProps} />
        </main>
      )
    }
    
    Login or Signup to reply.
  2. You are supposed to use the font’s font.variable method, not the font.className method.

    import { Oxygen } from 'next/font/google'
     
    const oxygen = Oxygen({ 
        display: 'swap',
        variable: '--font-oxygen',
        subsets: ['latin'],
    })
     
    export default function MyApp({ Component, pageProps }) {
      return (
        <main className={oxygen.variable}> // USE .variable, NOT .className
          <Component {...pageProps} />
        </main>
      )
    }
    

    Now, you can add that variable to any css class:

    .text {
      font-family: var(--font-oxygen);
    }
    

    Note: This works with app router, but I am unsure if it works for page router.

    This should preload the font as well, which means that it does not flicker when the page loads.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search