Using Web Fonts
This guide covers how to add fonts from web services to your Gatsby site.
Prerequisites
This guide uses the Gatsby default starter.
Adding web fonts
Some examples of web font services include Google Fonts and Typekit Web Fonts.
gatsby-plugin-web-font-loader
gatsby-plugin-web-font-loader
is a Gatsby plugin which makes it easy to add web fonts using the popular Web Font Loader library. It supports loading fonts from Google Fonts, Typekit, Fonts.com, and Fontdeck, as well as self-hosted web fonts.
How to use Web Font Loader with Typekit
You can add Typekit Web Fonts to your project by using the gatsby-plugin-web-font-loader and your Adobe Fonts project id. For example, this is how you can add Futura to your project.
First, install the Gatsby plugin with npm:
Or with yarn:
Then, create an environment variable to store your Adobe Fonts project ID. (Make sure this file is in your .gitignore
file so your ID doesn’t get committed!) For example, if your Adobe Fonts project ID is abcdefg
, your .env
file will look like this:
Now you can add the gatsby-plugin-web-font-loader
plugin to your gatsby-config.js
file, located in your root directory. In your plugin configuration, pass in the environment variable you created.
Next, add the typeface name to the appropriate font-family
value in your CSS.
Self-host Google Fonts with Fontsource
Fontsource is a project to provide open source fonts from Google Fonts as NPM Packages.
You can decrease your site’s loading time by self-hosting fonts, saving ~300 milliseconds on desktop to 1+ seconds on 3G connections.
This example shows how to install the Open Sans font. If you have a different Google Font you want to use, you can find the corresponding package in NPM or the packages directory in the Fontsource repository.
Run
npm install @fontsource/open-sans
to install the necessary package files.Then within your app entry file or site component, import the font package. It is recommended you import in your site’s gatsby-browser.js file.
If you wish to select a particular weight or style, you may specify it by changing the import path.
Note: The weights and styles a font includes is shown in each package’s README file.
- Once it’s imported, you can reference the font name in a CSS stylesheet, CSS Module, or CSS-in-JS.
Other resources
- Check out the Using Google Fonts Gatsby recipe.
- Here’s a great article on why it’s important to keep your environment variables secret.