Open In App

How to Add Custom Local Fonts in Next.js ?

Last Updated : 05 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Next.js is a full-stack React-based framework, unlike a traditional react app where the entire application is loaded and rendered on the client, Next.js allows the first-page load to be rendered by the server which is great for SEO & Performance. 

Some of the key features of Next.js are: 

  • Image Optimization
  • Easy Page Routing
  • Out of the box Typescript support.
  • Easy deployment
  • Static Site Generation

You can learn more about Next here. In this article, we will learn to add Custom Fonts to our Next.js project.

Step 1: Create a new next project using the command below. (Make sure you have npm and node installed)

npx create-next-app myproject

Step 2: Open the project in your code editor, and create a new folder in the root directory called fonts.

Step 3: 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: 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: 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. 

/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: 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 .

./pages/index.js




import styles from '../styles/Home.module.css'
  
export default function Home() {
 return (
   <h1 className={styles.testFont}>Hello Geeks</h1>
  )
}


./styles/Home.module.css




.testFont {
  font-family: 'Rubik' , sans-serif;
  font-weight: bold;
  color: green;
  font-size: 3rem;
}


Output: 

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads