Content-Security-Policy
HTTP response header when using Google Analytics.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.
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;
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.
Let's break down how our policy works:
default-src 'none';
- this is setting our default CSP policy to block everything. You'll find the CSS and images will not load with this policy, you may want to loosen the policy and set it to 'self'
.
script-src 'self' www.googletagmanager.com;
- The script-src directive allows the /js/google-analytics.js
script to load via the 'self'
keyword. The policy also allows any script to scripts to load on the www.googletagmanager.com domain. We could make that more restrictive by specifying the full script URL in the policy.connect-src www.google-analytics.com;
- The connect-src policy allows google analytics to make a XHR (XMLHttpRequest, aka AJAX request) under the domain www.google-analytics.com in order to send the analytics data. We could also make this more restrictive by using the full url: https://www.google-analytics.com/g/collect
in the policy. The risk in using the full url is that if Google ever changes the endpoint url, we would need to update our policy.As you can see it is not terribly difficult to create a CSP policy that works with Google Analytics 4.
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.
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 CopyAdvisory Week is a weekly roundup of all the security advisories published by the major software vendors.