How to Use Google Fonts with a Content-Security-Policy

A Content Security Policy is an important mechanism for protecting your technology, software, and apps when they are deployed to the World Wide Web. However, if you want to provision a Content-Security-Policy when using Google Fonts, it can be quite tricky.

If you do not provision the Content-Security-Policy in the right way, your Google fonts will throw tons of errors in the Chrome Browser DevTools Network tab like this:

In the Chrome Browser Console tab, you might also see something like this if the Content Security Policy isn’t provisioned just right:

Yikes!

So how do we solve for this?

Directive #1: font-src

This determines what font scripts can load on the domain.

Google Fonts get loaded from this domain: fonts.gstatic.com — so we need to allowlist this domain in our font-src

```

font-src 'self' 
          data:
          https://fonts.gstatic.com
          ;

```

Directive #2: style-src

This determines what stylesheet scripts can load on the page. Google Fonts get loaded from this domain: fonts.gstatic.com — so we need to allowlist this domain in our style-src

```

style-src 'self' 
          https://fonts.googleapis.com
          ;

```

🥁 Drum roll…

Our Content-Security-Policy will look something like this:

```

<meta http-equiv="Content-Security-Policy" content="
        default-src 'self'; 
        font-src 'self' 
                data:
                https://fonts.gstatic.com
                ;
       style-src 'self' 
                https://fonts.googleapis.com
                ;
">
```
Previous
Previous

How to Prevent Caching on Fetch Requests to An API (Squarespace + Vanilla JS)

Next
Next

How to connect Amazon Cognito to a Content-Security-Policy