GTM not propagating nonce to Custom HTML tags

In order to add the nonce attribute to the Custom HTML scripts, it must be first defined as a GTM variable:

  1. Add id="gtmScript" to the nonce-aware version of GTM snippet – this will be used to target the element and capture nonce.
<script id="gtmScript" nonce="{GENERATED_NONCE}">
  // GTM function
</script>
  1. In GTM, create a new variable that will capture the nonce.
    Use DOM Element type, and select the ID of the GTM snippet.

GTM Variable configuration for nonce


Now that the nonce variable is available in the GTM, add it to the Custom HTML script.

<script nonce="{{nonce}}">
  console.log("CSP-allowed script with nonce:", "{{nonce}}");
</script>

If the tag is not firing, check the Support document.write. This can be a key step in Single Page Applications.
The GTM Custom HTML script is now nonce-allowed and fires as expected.
Of course, any assets used by this script will now need to be allowed in the CSP header.

GTM Custom HTML configuration


Script within a script

Many tracking scripts are creating and firing additional script within themselves.
These will also be blocked as inline-scripts.
Find out where and how they are created, and add nonce to them as well.

Usually, the code looks similar to this:

var script = document.createElement("script");
script.type = "text/javascript";
script.async = true;
script.src = "https://tracking.js";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(script, s);

Edit this part of the code and insert the nonce variable, in the same manner along with other attributes.

script.nonce = "{{nonce}}";

Again, pay attention and whitelist any necessary assets that are now being blocked from this newly allowed script.

That’s it – Custom HTML script is now fully CSP-allowed.


Source and disclaimer: I’m the author of expanded dev.to guide

Leave a Comment