Using Google Fonts in Next.js App

Using Google Fonts in Next.js App

About Next.js

Next.js is a React framework for building web applications that enable page routing, server-side rendering and quick loading times.

How to set up a Next.js App

Using the Git Bash terminal, run the following commands to set up the Next.js App called my-app:

# create my-app
npx create-next-app@latest my-app
# move to my-app folder
cd my-app
# start the development server
npm run dev

The above commands create a my-app folder with the following structure:

Adding and Using Google Fonts

Next.js 13 introduced a new font system, with easy access and use of Google fonts.

On the git bash terminal, install Google Fonts by typing the following command:

# install next/font
npm install @next/font

Now you can import any fonts from Google inside the src/app/layout.js file as follows:

// layout.js file
import { Trirong } from 'next/font/google'; // replace Trirong with any font of your choice

// define a function for using the above font
const trirong = Trirong({
    subsets: ['latin'],
    weight: ['300']
})

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

With that, the Trirong font is globally available to your entire my-app .

Note:

  1. Subsets refer to specific subsets of characters within the font family. Not all fonts contain all characters from all languages, and loading unnecessary characters can impact your site's performance. Google Fonts allows you to choose specific subsets of characters that are relevant to the languages you intend to support on your website. For example, if your website is in English, you might only need the "Latin" subset.

  2. Weights refer to the thickness or boldness of a font. You can choose the appropriate weight for different elements like headings and paragraphs to create visual hierarchy and emphasis.

Remarks

For Next.js version 13.2 onward, next/font has been built into Next.js making @next/font package redundant. You will therefore likely see a "Built-n next/font" Error when using previous versions of Next.js.

To resolve this error, you will need to uninstall @next/font and replace all @next/font imports with next/font in your project files. This can be done automatically using the built-in-next-font codemode as shown below:

# using terminal
npx @next/codemode built-in-font

If @next/font depedency was there in the package.json file, you can then run the following command to unistall it:

npm unistall @next/font

Conclusion

For more on Google Fonts in Next.js, read the Google Fonts in Next.js documentation.

Also, check my test-app-with-nextjs GitHub Repo on how I used the Google Font.

Thanks for reading.