Content Security Policy (CSP)
Examples


Using Google Analytics GA4 with CSP

Don't forget to update your Content-Security-Policy HTTP response header when using Google Analytics.

Step 1 - Create JS File

Create a JS file: /js/google-analytics.js to store the contents of the Google Analytics Script:

    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'ABC12345');    

Note that you will need to change ABC12345 to match your google analytics tag.

If you really want to use the inline script tag then you will have to implement a CSP Nonce or a CSP Hash to allow it to execute it.

Step 2 - Create a CSP Policy

Here's a minimal policy to allow google analytics 4:

default-src 'none';script-src 'self' www.googletagmanager.com/gtag/js; connect-src www.google-analytics.com;

Step 3 - Update your HTML

Now you can insert something like this in your HTML:

<script async src="https://www.googletagmanager.com/gtag/js?id=G-ABC12345"></script>
<script src="/js/google-analytics.js"></script>

Again make sure you update the ABC12345 value to match your google analytics tag id.

How it works

Let's break down how our policy works:

As you can see it is not terribly difficult to create a CSP policy that works with Google Analytics 4.

Google Analytics in Different Regions

We have found that in the EU region, google analytics may use a different endpoint, such as region1.google-analytics.com

In that case you may need to add region1.google-analytics.com to your connect-src policy, or you could potentially use *.google-analytics.com instead.

CSP Developer Field Guide

CSP Developer Field Guide

Want to learn the ins and outs CSP? Grab a copy of the CSP Developer Field Guide. It's a short and sweet guide to help developers get up to speed quickly.

Grab a Copy

Struggling to stay on top of security advisories?

Advisory Week is a weekly roundup of all the security advisories published by the major software vendors.