Onjsdev

Share


How To Use Google Fonts In NextJS

How To Use Google Fonts In NextJS


By onjsdev

Jan 23rd, 2024

It is now easier than before to import Google fonts into NextJs applications. Let's see how to achieve this.

How To Use Google Fonts In Next

The next/font module automatically optimizes your fonts and removes external network requests for better performance. Font files is downloaded at build and no request is sent to Google by the browser.

To integrate a Google Font into your Nextjs application:

  • Import a font from Google Fonts using the next/font module.
  • Then create a font instance with specific subsets and weights.
  • Lastly, add the class name derived from the font instance to the body of the HTML document. This suggests that the selected font styles will be applied to the entire body of the document.

For example:

import Nav from "@/components/nav";
import Menu from "@/components/menu";
import Footer from "@/components/footer";

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

const roboto = Roboto({subsets:['latin'], weight:['300', '700']});

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body className={roboto.className}>
        <Nav></Nav>

        <main className="container px-4 mx-auto">
          <Menu></Menu>

          {children}
        </main>
        <Footer></Footer>
      </body>
    </html>
  );
}

With Tailwind CSS

It is also easy to create a utilty class of a google font with TailwindCSS. Here are steps to achive this:

  • Create the font instance with custom CSS variable
  • Add the custom CSS variable to your HTML document
  • Lastly, in tailwind config file, extends the default font family with the custom CSS variable
import Nav from "@/components/nav";
import { Roboto } from "next/font/google";
import Menu from "@/components/menu";
import Footer from "@/components/footer";

const roboto = Roboto({
  subsets: ["cyrillic"],
  weight: "300",
  variable: "--font-roboto",
});

export default function RootLayout({ children }) {
  return (
    <main className={`${roboto.variable} font-sans`}>
         <Menu></Menu>
         {children}
     </main>
  );
}

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    './pages/**/*.{js,ts,jsx,tsx}',
    './components/**/*.{js,ts,jsx,tsx}',
    './app/**/*.{js,ts,jsx,tsx}',
  ],
  theme: {
    extend: {
      fontFamily: {
        sans: ['var(--font-roboto)'],
      },
    },
  },
  plugins: [],
}

Now, you can use the font-sans tailwind classes to apply the font to your text.

Conclusion

In conclusion, The next/font/google package allows you to downland your fonts in build and use them in your nextjs website without sending any request to the Google, enabling more performance and privacy.

Thank you for reading.