Using multiple fonts across pages in Next JS
Asked Answered
P

5

5

I'm used to importing google fonts in css files and then using the font-family property. But I want to utilize the "built-in automatic self-hosting" provided by @next/font.

@next/font includes built-in automatic self-hosting for any font file.

This new font system also allows you to conveniently use all Google Fonts with performance and privacy in mind. CSS and font files are downloaded at build time and self-hosted with the rest of your static assets. No requests are sent to Google by the browser.

So far I can only import and use multiple fonts in index.js. I want to use the same fonts in another page about.js without loading the fonts again.

How can I import multiple fonts from @next/font/google and use them across pages and components?

Is there a way I can attach the fonts to particular classes or selectors?

h1 {
  font-family: "Exo 2", sans-serif;
}
Pacifism answered 22/12, 2022 at 10:40 Comment(0)
I
11

Using 2 fonts by local and google globaly

import { Manrope } from '@next/font/google'
import localFont from '@next/font/local'

const akzidenz = localFont({
  weight: '500',
  variable: '--font-akzidenz-grotesk-pro',
  src: '../../public/fonts/Akzidenz-Grotesk-Pro/AkzidenzGroteskPro- 
  MdEx.woff2',
})

const manrope = Manrope({
 weight: '400',
 subsets: [ 'latin' ],
 variable: '--font-manrope',
})

export default function App({ Component, pageProps }: AppProps) {
 return (
  <main className={`${akzidenz.variable} ${manrope.variable}`}>
   <Component {...pageProps} />
  </main>
 )
}

After that you can use in the styling of the application according to the specified variables

Injure answered 9/4, 2023 at 20:21 Comment(2)
This is how you do it while using tailwindStorekeeper
can confirm that this is working for Next.js 14 aswell, thanks!Natalee
P
5

We cannot attach @next/font/google fonts to particular classes using font-family because they have different names when imported.

element image


We can reuse fonts by doing this:

  1. Create a separate utils/fonts.js file:
import { Exo_2, Noto_Sans } from "@next/font/google";

export const titleFont = Exo_2({
  weight: ["500", "600", "700"],
  subsets: ["latin"],
});

export const textFont = Noto_Sans({
  weight: ["500", "600", "700"],
  subsets: ["latin"],
});

  1. Import the fonts required in pages/index.js:
import { textFont, titleFont } from "../utils/fonts";
  1. Use them with className property:
<main className={styles.main + " " + textFont.className}>
  <h1 className={titleFont.className}>Home Page</h1>
  <p>Hi this is the home page.</p>
</main>

  • You can do the same thing with local fonts. Just import them in fonts.js and then export their loader functions.
  • Using variable names like textFont and titleFont helps in forming a uniform system.
  • You can use the font with other styling classes by simply adding a space in between like this: {styles.main + " " + textFont.className}

Read documentation here.

Pacifism answered 22/12, 2022 at 10:40 Comment(5)
May I ask: The documentation for reusing does not seem to cater for the newer 'app' directory approach of nextjs13, which doesn't use the 'pages' dir. Is there a method with 'app' to make next/font available globally? Or must it be done by importing fonts.js on a component by component basis (which feels too tedious to be correct)?Dubose
I share the same concerns. I've tried in both the layout and template files to load Google fonts via next/font and got an error that fonts must be loaded from modules. I'm sure this is all for performance reasons. I can't imagine having to import a Google font on every page file. I still can't get my head around not having a top-most HOC like _app.js to be able to do global stuff.Blocking
@Dubose The documents have a dropdown menu at the top on the left sidebar that allows you to change between docs for App Router vs Page Router. Once I discovered this the docs properly resolved my needs for implementing next/fonts.Jephthah
@Jephthah Yes, but at the time of my comment (if I remember correctly) there was no reusing information when selecting the App documentation. It seems it's there now.Dubose
@Dubose I only added that to help others, I originally wrote a scathing review of next and their documents. I couldn't find the drop down menu I mentioned in 2024 :)Jephthah
T
1

Setting font using css

The way to set style using css is to use font variables, you pass a css variable to the parent of the element you want to use the font in and that css varaible includes the font family

import { Exo_2 } from "@next/font/google"

exo2 = Exo_2({
    weight:"400",
    variable:"--font-exo2"
})

export default function parent() {
    return <div className={exo2.variable}></div>
}

Css

.child {
   font-family: var(--font-exo2);
}
Trilingual answered 11/7, 2023 at 7:24 Comment(0)
F
0

In short, I try this method where i can use multiple fonts on my code and apply css on it also without any problem.

Here is my code :

//app/page.js

import Image from 'next/image'
import { Poppins} from '@next/font/google'
import { Anton} from '@next/font/google'
import styles from './page.module.css'

const poppins = Poppins({ weight: '400', subsets: ['latin']  })
const anton = Anton({ weight: '400', subsets: ['latin']  })

export default function Home() {
  return (
    <main className={styles.main}>
      <div  >
        <h1 className={styles.heading}><span className={anton.className}> Hello </span></h1>
      </div>
      <div  >
        <h2 className={styles.heading}><span className={poppins.className}> Hello </span></h2>
      </div>
    </main>
  )
}

You see i use heading and apply styles on it and after that i can use span in inside the heading tag and apply the fonts that i want to use

Fabrianne answered 31/1, 2023 at 14:35 Comment(0)
V
0

I found the Next.js documentation for pages to be unclear when it came to adding multiple fonts globally. However, I managed to solve the issue by injecting the custom CSS variable instead of using a wrapper and className.

import { type AppProps } from 'next/app';
import { DM_Sans, Inter } from 'next/font/google';
import Head from 'next/head';
import 'styles/globals.css';

const dmSans = DM_Sans({
  weight: ['400', '500', '700'],
  subsets: ['latin'],
});

const inter = Inter({
  weight: ['400', '500'],
  subsets: ['latin'],
});

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <>
      <Head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <style jsx global>{`
        html {
          --dm-sans-font: ${dmSans.style.fontFamily};
          --inter-font: ${inter.style.fontFamily};
        }
      `}</style>
        <Component {...pageProps} />
    </>
  );
}

export default MyApp;

Vermillion answered 11/5, 2023 at 0:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.