0

For security concern, we replaced "unsafe-inline" with nonce for script-src in CSP config for the script in index.html.

    script-src 'self' 'nonce-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'

Embedded js in index.html:

    <script  nonce="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx">
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
    }

But there are still some errors in console:

enter image description here

And checking details, it seems the tags.js injecting script to the body element and is forbidden:

enter image description here enter image description here

To eliminate these errors, we have to use unsafe-inline for script-src-elem, but it is still not safe enough.

Wonder if there is a better solution to this issue? I tried search but found all about using nonce for injecting Google-Analytics code to index.html itself.

Thanks!

1 Answer 1

0

Seems to me like you've made a mistake deploying GTM. There's a nonce-aware version of the GTM snippet that allows GTM to use nonce for the scripts that it deploys. And yes, GTM must deploy scripts on the fly. That's the whole purpose of a TMS, essentially.

Here's the nonce-aware snippet:

<!-- Google Tag Manager -->
<script nonce='{SERVER-GENERATED-NONCE}'>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;var n=d.querySelector('[nonce]');
n&&j.setAttribute('nonce',n.nonce||n.getAttribute('nonce'));f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');</script>
<!-- End Google Tag Manager -->

Read more about GTM and CSP here: https://developers.google.com/tag-platform/security/guides/csp

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the reply. In our situation, we just create a global gtag function in index.html and the GA-key is read depending on different environments later and load the script using that key. So it's implemented in different places and timings. The minimized nonce-aware snippet cannot be applied directly. So looks like we are closer to this doc: developers.google.com/tag-platform/tag-manager/templates/…
And we load script like this: 'googletagmanager.com/gtag/js?id=' + environment.gaKey. Seems different to gtm.js somehow.
BTW, GTM is different to Google Analytics i think. I cannot find nonce-aware version of Google Analytics snippet. support.google.com/analytics/answer/…, seems GA4 is using googletagmanager.com/gtag/js with params

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.