- Published on
Google Fonts with Fontsource for Your Gatsby Site
2 min read- Authors
- Name
- Kulwinder Uppal
- @Twitter/kulwindernzU
There are many different ways to add fonts, such as Google Fonts, to your Gatsby blog/website. One way is to install the Gatsby font-loader plugin and configure the Google Fonts API to specify the required web font.
Another approach is to use self-hosted Google fonts with the Fontsource npm package. In this example, we will demonstrate how to use Fontsource to load custom fonts.
Why Google fonts with Fontsource
Opting for self-hosted Google fonts (Fontsource) instead of the Gatsby gatsby-omni-font-loader plugin
can help improve your site's loading time.
Adding Google Fonts with Fontsource in Three Simple Steps
To add a custom font like Poppins to your site, follow these three straightforward steps. You can select your preferred font by visiting the Fontsource site.
Prerequisites
You need to have a Gatsby project set up, with or without a starter library.
Step 1:Install the Fontsource NPM package
Under your project's root folder, run the following command in your terminal to install the Poppins
font.
npm install @fontsource/poppins
Step 2:Import the Font
Locate the gatsby-browser.js file at the root of your project and import the desired font(s):
import '@fontsource/poppins/200.css';
import '@fontsource/poppins/400.css';
import '@fontsource/poppins/600.css';
import '@fontsource/poppins/700.css';
import '@fontsource/poppins/800.css';
You can specify any weight and style by modifying the import path. To explore other available font weights and styles, visit Fontsource's Documentation
Step 3:Use the Font in Your CSS or CSS-in-JS
After completing the import, the final step is to reference the font name in your stylesheet or CSS module:
body {
font-family: 'Poppins', sans-serif;
}
Reload your site to confirm that the font has changed to 'Poppins'.