How to use custom fonts in Gatsby

By
on

Importing fonts used to be pretty straightforward. With modern JavaScript focused projects and build tools it can be quite confusing. This is the approach that worked for my Gatsby project.

I wanted to add custom fonts to my Gatsby project, but a lot of resources online seemed outdated. Some suggested directly importing font files in your TypeScript or JavaScript files but that didn’t work for me.

I use styled-components for CSS, but createGlobalStyle wouldn’t work for me since I use object syntax.

import { createGlobalStyle } from "styled-components"
createGlobalStyle({
"@font-face": {
// font 1
},
"@font-face": {
// font 2 would override font 1
// because the key is the same
},
})

I downloaded my fonts from Google Fonts and generated the .woff and .woff2 files with the Font Squirrel Webfont Generator.

I could have used the typeface-source-sans-pro package but I didn’t want any unused font definitions, so I briefly checked how the packages in the Typefaces repository worked and copied that. It turned out to just be a CSS file. Simple enough!

@font-face {
font-family: "Source Sans Pro";
font-style: normal;
font-display: swap;
font-weight: 400;
src:
local("Source Sans Pro Regular normal"),
local("Source Sans Pro-Regularnormal"),
url("./ssp-regular.woff2") format("woff2"),
url("./ssp-regular.woff") format("woff");
}
@font-face {
font-family: "Source Sans Pro";
font-style: normal;
font-display: swap;
font-weight: 600;
src:
local("Source Sans Pro SemiBold normal"),
local("Source Sans Pro-SemiBoldnormal"),
url("./ssp-semibold.woff2") format("woff2"),
url("ssp-semibold.woff") format("woff");
}

I then imported it in my gatsby-browser.js. This will create a new <link> tag in your <head>.

// gatsby-browser.js
import "./src/assets/fonts/index.css"

After importing the CSS file I was able to use the fonts anywhere in my CSS like my typography.js config or my Styled Components.

const MyComponent = styled.div({
fontFamily: `'Source Sans Pro', sans-serif`,
})

That’s it! I hope this helped you in any way.


Further reading

Back to blog

Say hello! 👋

If you want to talk to me about something that could interest me, you can send me an email at hey@eddy.codes. I check my inbox a couple times during the week.

You can also find me on Twitter (@eddyvinckk) or LinkedIn.

(I get a lot of messages, so sadly I can't get back to everyone)