Using nonces in Google Tag Manager scripts

We have made some changes recently to our Content Security Policy with regards to Google Tag Manager (see this pull request). We now use the nonce approach (as recommended by Google), which means that some updates might be necessary to your Discourse site and/or GTM tags. This guide will help you make these adjustments.


Remove the 'unsafe-inline' directive

On your Discourse instance, you can now remove the entry for 'unsafe-inline'. This directive is ignored by browsers if the policy includes a nonce- value.

Update scripts to include the nonce variable

In your GTM account, you need to ensure that the nonce value is passed to any custom scripts you may have under Custom HTML tags. (If you don’t have any Custom HTML tags, you can stop here, you’re already done.)

1. Capture the nonce value in a variable

Create a new variable in GTM with the following details:

Variable name: nonce (all lowercase)
Element ID: data-google-tag-manager
Attribute name: data-nonce

2. Include the nonce variable in scripts under custom HTML tags

If you previously had scripts like this:

<script type="text/javascript">
  // your script code here
</script>

you need to add a nonce attribute to the opening tag, like so:

<script type="text/javascript" nonce="{{nonce}}">
  // your script code here
</script>

3. Ensure “Support document.write” is enabled

Only the new rendering engine supports the nonce method, so you need to make sure this checkbox is checked:


And that’s it, now you can Save and Publish your changes and then head over to your Discourse instance and make sure there are no CSP errors in the browser console.

3 Likes