Using Google fonts in Gatsby

July 02, 2020

I styled the html in JSX using a vanilla css stylesheet that I imported into my src/pages/index.js. I am styling the page for my laptop screen. Pixels are hardcoded and I will have to figure out how to make it responsive to different screen sizes later.

I wanted to pick 2 fonts for the landing page and picked Spectral and Roboto from https://fonts.google.com.

I picked Spectral first, and then looked at font pairings and picked Roboto. Select the style of the font you want and on the right you will see an embed link. I picked Spectral Light 300, and that gave me an embed link of:

<link href="https://fonts.googleapis.com/css2?family=Spectral:wght@300&display=swap" rel="stylesheet">

and the CSS rule:

font-family: 'Spectral', serif;

Keep in mind that a Gatsby site is supposed to be blazing fast and if you embed the URL to fetch the font, that will slow you down.

So what’s the solution?

A gatsby plugin!! gatsby-plugin-prefetch-google-fonts is your friend.

Follow the instructions in the link above to install the plugin and add it to gatsby-config.js.

My gatsby-config.js looks like this:

module.exports=
{
plugins: [
...,
{
resolve: `gatsby-plugin-prefetch-google-fonts`,
options: {
fonts: [
{
family : `Spectral`,
variants: [ `200`,`300`, `400`],
subsets: [`latin`],
},
{
family: `Roboto`,
variants: [`300`, `400`,`500`],
},
],
},
},
]
}

Use it in your CSS like this:

font-family: Spectral, serif; font-weight: 300;

Remember to prune the font variants in gatsby-config.js and keep it to the bare minimum that you actually use on your site.

Here is what my website looks like now. If you refresh the page and watch carefully, you will see that the browser displays the default serif and san-serif fonts first before loading Spectral/Roboto at the top of the landing page.


tufan.io
Making it simple to create, manage & secure cloud applications.