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:
- Import `Poppins` from `next/font/google`.
- Configure the font using `Poppins({})`, specifying attributes like subsets, display, weight, etc.
- Export the font configuration and your metadata in `app/layout.js`.
- In `RootLayout`, wrap your page content within `<html>` and `<body>` tags, adding the font’s variable (`–font-poppins`) to the HTML class.
- 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:
-
Create a
global.css
file: Create a CSS file namedglobal.css
in the/styles
directory of your project. -
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');
- Import the
global.css
file: In the_app.js
file, import theglobal.css
file. This will make the imported Google Fonts available globally in your application. For example:
import '../styles/global.css'
- 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.
... solve coding problems, write content and more Enhance AI: https://app.enhanceai.ai/ Learn Design for Developers! A book I've created ...
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.
... solve coding problems, write content and more Enhance AI: https://app.enhanceai.ai/ Learn Design for Developers! A book I've created ...