To enhance security on your website (such as to block harmful scripts that could steal user passwords), one of your best options is a Content Security Policy (CSP). However, enabling a CSP can cause problems with Google Tag Manager (GTM). To continue using GTM with a CSP installed, you need to make some changes.

The only problem is that a CSP can stop Google Tag Manager from functioning correctly. This is because it is impossible for a CSP to distinguish between malicious code and code coming from Google Tag Manager. For this reason, if you want to have a CSP and continue using Google Tag Manager, you need to configure your CSP to trust Google.

How Does a CSP Work?

To understand why CSPs cause problems with Google Tag Manager, you need to understand how a CSP works.

A CSP is not part of the HTML of your page, which means it does not appear in the source code — it is possible to deliver it through HTML using meta tags, but this is not the recommended practice. Instead, you should send the CSP for a webpage in a Content-Security-Policy header of the HTTP response. To view it for any page, use the “Network” tab in the Developers Tools for your browser.

The policy for the webpage is the content of the HTTP header. This is made up of a list of directives separated by semicolons. Each directive consists of a directive name (which specifies what type of resource is being restricted) followed by a source list (which whitelists domains for the resource type).

Do You Have a CSP Issue?

Before going any further, stop and check if you are having a CSP issue. Common signs include a lack of a debug panel even in “Preview” mode, a debug panel without styles, and the inability to load Google Tag Manager along with a CSP error in the JavaScript console. If any of these are occurring, use the following script to correct the problem.

How to Modify Your CSP

To allow the resources you want to load, you need to add domains to your existing CSP — never add a second policy. You also must stick to the directive names that already exist in your policy. With those two things in mind, this is the script you’ll need to modify your policy.

To load Google Tag Manager:

‘script-src’ ‘unsafe-inline’

To build custom JavaScript variables and custom HTML tags:

‘script-src’ ‘unsafe-eval’

To enable styles and custom fonts in the Google Tag Manager debug panel:

‘style-src’ ‘unsafe-inline’

To load the Google Tag Manager logo in debug mode:

‘img-src’ ‘unsafe-inline’

These last two are unessential for the Debug Panel to be functional, but you’ll need to allow them if you want to work with the stylesheet in debug mode.

It is important to ensure complete accuracy when you modify your policy; even a minor mistake can mean that browsers will refuse to load certain types of resources. Adhere closely to the above instructions — or you may end up with a broken website.