by Sai gowtham

How to add fonts to a Gatsby app

In this tutorial, we are going to learn about how to add the custom fonts to a gatsby app.

Adding local fonts

  1. Open the gatsby project in your favorite code editor.
  2. Create a new folder called fonts inside the src folder.
  3. Download the fonts locally and place them inside the fonts folder.
  4. Open your layout.css file and load the font by referencing its path like this.
layout.css
@font-face {
    font-family: 'Oxygen';
    src: local('Oxygen'), url(../fonts/Oxygen/Oxygen-Regular.ttf) format('truetype');
}

Here I added an Oxygen font.

Now, we can use this font in the css classes like this.

main.css
.title{
    font-family: Oxygen, serif;
    color: #0004;
}

Adding google fonts

If you like to use google fonts (API) instead of local fonts, you need to install a new plugin called gatsby-plugin-google-fonts that adds the font stylesheet to a <head> tag of every page in your gatsby app.

Run the following command to install the plugin.

npm i gatsby-plugin-google-fonts

Now, add the following configuration to the gatsby-config.js file by replacing it with your font name.

gatsby-config.js
module.exports = {

  plugins: [
    {
      resolve: `gatsby-plugin-google-fonts`,
      options: {
        fonts: [
          `Oxygen`        ],
        display: 'swap'
      }
    }
  ]
}

you can also specify font weights like this.

gatsby-config.js
module.exports = {

  plugins: [
    {
      resolve: `gatsby-plugin-google-fonts`,
      options: {
        fonts: [
          `Oxygen\:300,400,700`,        ],
        display: 'swap'
      }
    }
  ]
}

you can also add the multiple fonts like this.

gatsby-config.js
module.exports = {

  plugins: [
    {
      resolve: `gatsby-plugin-google-fonts`,
      options: {
        fonts: [
          `Oxygen\:300,400,700`,
          `Red Rose`, // second font        ],
        display: 'swap'
      }
    }
  ]
}

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course