I'm referring to this article to create content security policy. By flipping the the existing calls to react-scripts in npm scripts and Adding config-overrides.js file in the root directory, I'm able to dynamically create nonce value
My config.overrid.js file looks like this
const {override} = require('customize-cra');
const cspHtmlWebpackPlugin = require("csp-html-webpack-plugin");
const cspConfigPolicy = {
'img-src': [" 'self' blob: https://api.company.com/ data:"],
'script-src': ["'self' https://abc.stripe.com js.stripe.com https://billing.stripe.com https://www.googletagmanager.com" ],
'connect-src':[" * 'self' https://checkout.stripe.com https://billing.stripe.com"],
'frame-src': ["'self' https://checkout.stripe.com https://billing.stripe.com https://js.stripe.com ;"],
};
function addCspHtmlWebpackPlugin(config) {
if(process.env.NODE_ENV === 'production') {
config.plugins.push(new cspHtmlWebpackPlugin(cspConfigPolicy));
}
return config;
}
module.exports = {
webpack: override(addCspHtmlWebpackPlugin),
};
Dynamically created nonce value during build time
<meta http-equiv="Content Security Policy directive: "style-src 'self' 'nonce-DpAw3sfasvaX12pPA==' 'nonce-Hf+DsdsdP324242d7ySSSDSDA=='".
For nonce-aware version of GTM snippet, I need to pass nonce value to GTM snippet like this. Read about it here
<!-- 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 --
But I'm not able to figure out how to get this nonce value in index.html so that I can pass it to the GTM Snippet.