[Solved] How to import custom google fonts in NextJS 13? Link tags not working – Javascript

by
Ali Hasan
google-fonts next.js reactjs

Quick Fix: To use Google fonts on a Next 13+ project, you can use the next/font/google module to import the fonts in your layout file and then apply the font to elements using CSS.

The Problem:

How to import custom Google Fonts in NextJS 13? Using link tags doesn’t seem to work anymore.

The Solutions:

Solution 1: Using `next/font/google`

To import custom Google fonts in NextJS 13, you can utilize the `next/font/google` package. Here’s how you implement it:

  1. Import `Poppins` from `next/font/google`.
  2. Configure the font using `Poppins({})`, specifying attributes like subsets, display, weight, etc.
  3. Export the font configuration and your metadata in `app/layout.js`.
  4. In `RootLayout`, wrap your page content within `<html>` and `<body>` tags, adding the font’s variable (`–font-poppins`) to the HTML class.
  5. In your CSS files, use `var(–font-poppins)` as the font family for your elements.

This method ensures that the font is loaded and optimized for your NextJS 13+ application.

Solution 2: GlobalCSS Style Import

In Next.js 13, the recommended approach is to import custom Google fonts in a global CSS file. This approach involves the following steps:

  1. Create a global.css file: Create a CSS file named global.css in the /styles directory of your project.

  2. Import the Google Fonts CSS URL: In the global.css file, import the Google Fonts CSS URL using an @import rule. For example:

@import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap');
  1. Import the global.css file: In the _app.js file, import the global.css file. This will make the imported Google Fonts available globally in your application. For example:
import '../styles/global.css'
  1. Use the font: You can now use the imported Google font in your application’s CSS and UI components. For example:
body {
  font-family: 'Poppins', sans-serif;
}

This approach allows you to import custom Google fonts and make them globally available without using <link> tags.

Q&A

How to import custom Google fonts in NextJS 13 without Link tags

Add dependency and create a custom font file

Where to define font family in new NextJS projects

Define font family variables outside the component

Video Explanation:

The following video, titled "Turning a Figma Design into a Real Website using HTML and CSS ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

... solve coding problems, write content and more ‍ Enhance AI: https://app.enhanceai.ai/ Learn Design for Developers! A book I've created ...