In my landing page(ejs) I have the snippet of google tag manager, but I have the CSP that doesn't allow inline scripts.. on the server-side(app.js) I generate on each request a nonce id.
const nonceToken = 'nonce-' + crypto.randomBytes(16).toString('base64');
the code:
app.get('/', (req, res) => {
res.render('index', {
nounceToken: nonceToken
})
});
this is the snippet inside the ejs file:
<!-- Google Tag Manager -->
<script>(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; f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'GTM-*******');</script>
<!-- End Google Tag Manager -->
in the helmet options :
app.use(helmet.contentSecurityPolicy({
useDefaults: true,
directives: {
"script-src-elem": ["'self'", "https://unpkg.com/scrollreveal", "https://www.googletagmanager.com/gtm.js?id=GTM-*******"],
"form-action": 'self',
"script-src": 'nonce-' + nonceToken,
}
}));
Errors given in the console of Google:
The source list for Content Security Policy directive 'script-src-elem' contains a source with an invalid path: '/gtm.js?id=GTM-*******'. The query component, including the '?', will be ignored.
and also:
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src-elem 'self' https://unpkg.com/scrollreveal https://www.googletagmanager.com/gtm.js?id=GTM-*******". Either the 'unsafe-inline' keyword, a hash ('sha256-1KheQ9YFAlUN7PPKDGu2i9+u4UTLBUuJvOgrQJPK1lg='), or a nonce ('nonce-...') is required to enable inline execution.
i have tried a tons of times to find a solution to that but nothing..