How to Add Custom Local Fonts in Next.js ? (original) (raw)
Last Updated : 23 Sep, 2024
Adding custom fonts in Next.js project enhances the typography. It also improves the performance as the fonts are loaded directly from project assets.
They can be integrated by importing font files into a project, defining @font-face rules in CSS, and applying them across components for consistent styling and branding.
In this article, we will learn to add Custom Fonts to our Next.js project.
Approach
**To add custom local font in Next js we will **place the font files in public/fonts, define @font-face rules in fonts.css, import this CSS into your app, and apply font-family in components for cohesive branding and design consistency.
Steps to add Custom Fonts in Next.js
**Step 1: Initialize Next App
Create a new next project using the command below. (Make sure you have npm and node installed)
npx create-next-app myproject
**Step 2: Create fonts Directory
Open the project in your code editor, and create a new folder in the root directory called **fonts.
**Step 3: Arrange Required Fonts
If you already have the fonts, then skip this step. Download the required fonts from Google Fonts.
For this article, we are downloading **Rubik font from google fonts.
**Step 4: Move font to the fonts directory
Now move all the fonts to the ****/fonts** directory, so that we can add a relative path in our CSS to access these fonts.
**Project Structure:
**Step 5: Integreate using CSS
Add CSS to create a custom font family for these fonts. We'll add this CSS in global styles so that the whole application can access these fonts, but you can also add fonts for a specific web page.
CSS `
/* /styles/global.css */
@font-face { font-family: 'Rubik'; src: url('../fonts/rubik/Rubik-Regular.ttf'); font-weight: normal; font-style: normal; }
@font-face { font-family: 'Rubik'; src: url('../fonts/rubik/Rubik-Bold.ttf'); font-weight: bold; font-style: normal; }
@font-face { font-family: 'Rubik'; src: url('../fonts/rubik/Rubik-Italic.ttf'); font-weight: normal; font-style: italic; }
`
We can also add multiple font weights and font styles for the same font family as shown above.
**Step 6: Test the added fonts
Let's test this font in our ****./pages/index.js** file (Home page). We'll remove all the boilerplate code for simplicity and add its styles to ****./styles/Home.module.css** .
CSS `
/* styles/Home.module.css */
.testFont { font-family: 'Rubik', sans-serif; font-weight: bold; color: green; font-size: 3rem; }
JavaScript
// pages/index.js
import styles from "../styles/Home.module.css";
export default function Home() { return
Hello Geeks
; }`
**Step to run the app: Use the below command to run the application
npm run dev
**Output: