How do I add google fonts to a gatsby site
Getting started with Gatsby - when I add a link tag to public/index.html with the google font it works in development mode. When I build the site the index.html gets reset. So I guess there is another proper way to add the font?
Solution 1:
You can also use react-helmet, which is discussed in the gatsby tutorial.
Include a google fonts link element within the helmet component.
Like this:
<Helmet>
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet"/>
</Helmet>
I ended up going down this route because I had already done some styling manually, and when I tried using Typography it made a bunch of changes that would have taken me a while to undo.
Solution 2:
Add the following to the top of src/layouts/index.css
for example to import the 'Roboto' font by Google
@import url('https://fonts.googleapis.com/css?family=Roboto');
html {
font-family: 'Roboto', sans-serif;
}
This will then be handled by the gatsby build process and included in the final production version of the site.
Solution 3:
I was under the impression Typefaces was the way to go. No extra (blocking) network requests.
As long as you can find your typeface- font on NPM
Solution 4:
If you are using Material UI in combination with Gatsby, here is the optimal way:
Add the CDN href in combination with React Helmet
as suggested in the Material UI documentation and the official Material UI Gatsby example from their github repository:
Create a file RootLayout.jsx
(or name it however you want):
import React from "react";
import { Helmet } from "react-helmet";
import CssBaseline from "@material-ui/core/CssBaseline";
export default function RootLayout({ children }) {
return (
<>
<Helmet>
<meta
name="viewport"
content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no"
/>
<link rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,600&display=swap" />
</Helmet>
{children}
</>
);
}
Add this code to your gatsby-browser.js
:
export const wrapRootElement = ({ element }) => <RootLayout>{element}</RootLayout>;
Add the same code snippet to your gatsby-ssr.js
:
export const wrapRootElement = ({ element }) => <RootLayout>{element}</RootLayout>;
Explanation
The code in the layout is wrapped around your React app using the Gatsby Browser and SSR API. This way the font is available throughout your whole Gatsby app.
Link to Gatsby Browser API
Link to Gatsby SSR API
Solution 5:
You can prefetch fonts with this plugin https://github.com/escaladesports/gatsby-plugin-prefetch-google-fonts This way in the build phase, the plugin will fetch your fonts and store it locally so you can serve them from your server or CDN.