DEV Community

Cover image for How to use @next/font globally
Michael Esteban
Michael Esteban

Posted on • Originally published at mikeesto.com

11

How to use @next/font globally

The @next/font package can download Google Fonts at build time and self-host them as a static asset. This is useful because no requests are made to Google by the client to request fonts used on the page.

However, it wasn't obvious to me how to apply the font globally. This can be achieved as follows.

app.js

import "@/styles/globals.css";

import { DM_Sans } from "@next/font/google";

const dm_sans = DM_Sans({
  display: "swap",
  subsets: ["latin"],
  weight: ["400", "500", "700"],
});

export default function App({ Component, pageProps }) {
  return (
    <>
      <style jsx global>{`
        :root {
          --dm-font: ${dm_sans.style.fontFamily};
        }
      `}</style>
      <Component {...pageProps} />
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

And then use the CSS variable in your stylesheet.

global.css

body {
  font-family: var(--dm-font);
}
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (2)

Collapse
 
forguz profile image
Nicolas Dellazzeri

Hello! Did you find any way to use this with the app folder?

Collapse
 
davewelsh79 profile image
Dave • Edited

/src/app/layout.tsx

import { Open_Sans, Playfair_Display } from '@next/font/google';

import './globals.scss';

const openSans = Open_Sans({
  display: 'swap',
  subsets: [ 'latin' ],
  weight: [ '400', '500', '700' ],
  variable: '--font-open-sans',
});

const playfairDisplay = Playfair_Display({
  display: 'swap',
  subsets: [ 'latin' ],
  weight: [ '500' ],
  variable: '--font-playfair-display',
});

const RootLayout: FC<PropsWithChildren> = ({ children }) => (
  <html lang="en" className={`${openSans.variable} ${playfairDisplay.variable}`}>
    <body>
      {children}
    </body>
  </html>
);

export default RootLayout;
Enter fullscreen mode Exit fullscreen mode

/src/app/global.scss

.foo {
  font-family: var(--font-open-sans);
}
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More