'Adding nonce to content security policy in a react app

I'm adding content security policy to make google tag manager work. As per instructions, using nonce is recommended.

So inside my Index.html, I have added content security policy like this

<meta http-equiv="Content-Security-Policy" script-src 'nonce-{GENERATED_NONCE}'" />

As, someone quite new to programming, I don't understand how to dynamically change nonce value inside .html file. As it needs to be uniquely generated for each client.

I tried generating nonce value like below in index.js. I'm not sure whether adding it here is right nor I don't know how to bring this value into index.html.

const GENERATED_NONCE = crypto.randomBytes(16).toString("base64");.

Can someone help me?



Solution 1:[1]

Do you have a backend infrastructure in place? If so, instead of placing CSP headers in HTML you can set http headers from your backend which will allow randomly generated nonce to set to the header.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 livesamarthgupta