Self hosting Google Fonts for better caching

Vaibhav Sharma


December 05, 2018

Self hosting Google Fonts for better caching

Just a month ago a college fresher came to me showing her newly made React app, bootstrapped using create-react-app. As we got into discussing performance, she told me that everything was almost 100 on except for Browser Caching. That was because of Google Analytics and Google Fonts. And, it’s not just about browser caching, a lot of times Google Fonts have files that will probably be of no use to us. For example, extra language support. Although not much can be done about Google Analytics, I told her a little hack that will make the ‘Google Fonts’ problem disappear very easily. Since starter kits like create-react-app and Gatsby JS provide support for caching and service workers, we’re better off self-hosting.

For this tutorial, we’ll be assuming the following:

  • This is a create-react-app project
  • We need to include Montserrat font from Google Fonts.

Let’s begin, by selecting the font on for us that will be Montserrat.


Next, we copy the URL in the href attribute of the example code. Open the URL from your browser and you’ll see a CSS file, with the code to include the font-face.


We see here that there are quite a few font files that the API pulled. Let’s say for this article that we don’t need the Vietnamese support. So, we just copy the Latin and Cyrillic parts of the stylesheet. In the code, we see, there’s a URL for the font file. We download the fonts using that URL and keep them in a local project folder. Now, all we need to do is replace the URL from the cloud-hosted to the relative address of the locally stored file.

src: local('Montserrat Regular'), local('Montserrat-Regular'), url( format('woff2');


src: local('Montserrat Regular'), local('Montserrat-Regular'), url(../fonts/JTUSjIg1_i6t8kCHKm459WlhyyTh89Y.woff2) format('woff2');

create-react-app allows us to directly import CSS files, we just import our stylesheet in the javascript.

import './styles.css';

And, that’s all we need to do, create-react-app automatically takes care of caching and service worker. This works for other libraries like Gatsby JS as well. That’s all for this article.

Copyright © 2018-2024 The Leaky Cauldron Blog. All Rights Reserved.