Changing Fonts in Next.js
A Step-by-Step Guide to Implementing Google Fonts in Your Next.js Application
Fonts play a crucial role in web design, influencing the readability, aesthetics, and overall user experience of your application. Recently, while working on an assessment in Next.js, I faced a challenge with changing the font (I forgot how to do it lol ๐). After some research, I found a straightforward solution. Here's how it's done.
Step 1: Initialise a next app ๐ฆ
Next.js provides a convenient way to integrate Google Fonts through the next/font
package. To get started, you need to install it if you haven't already:
npx create-next-app@latest
Step 2: Import Google Fonts โจ๏ธ
Next, import your desired Google Font into your application. In this example, we'll use the Poppins font.
import { Poppins } from "next/font/google";
import "./globals.css";
Step 3: Configure the Font โ๏ธ
Configure the font with the desired options such as subsets, display, and weight. Here's how to set up the Poppins font with specific weights and subsets:
const poppins = Poppins({
subsets: ["latin"],
display: "swap",
weight: ["400", "500"],
});
Explanation:
subsets: Specifies the character subsets to include. In this case, we're including the "latin" subset.
display: Controls how the font is displayed while loading. "swap" ensures that text remains visible during font loading.
weight: Defines the font weights to include. We're including weights 400 (normal) and 500 (medium).
Step 4: Apply the Font ๐๏ธ
To apply the font to your entire application, use the font configuration in your root layout component. Wrap your application content with the <body>
tag that includes the font's class name.
export default function RootLayout({ children }) {
return (
<html lang="en">
<body className={poppins.className}>{children}</body>
</html>
);
}
Explanation:
- poppins.className: This class name applies the configured Poppins font to the body of your HTML document, ensuring that all text within your application uses this font.
Complete Example
Here's the complete code for changing the font in your Next.js application:
javascriptCopy codeimport type { Metadata } from "next";
import { Poppins } from "next/font/google";
import "./globals.css";
const poppins = Poppins({
subsets: ["latin"],
display: "swap",
weight: ["400", "500"],
});
export const metadata: Metadata = {
title: "Change font in nextjs",
description: "Example next app",
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body className={poppins.className}>{children}</body>
</html>
);
}
Changing fonts in Next.js is straightforward with the next/font
package. By following these steps, you can enhance the typography of your application, making it more visually appealing and user-friendly. Experiment with different fonts and configurations to find the perfect match for your design.
I hope this guide helps you as much as it helped me during my assessment. Happy coding. ๐ค