how to implement content security policy NONCE in html script tags with node and helmet
08:27 30 Nov 2021

I am having a hard time finding an answer to my question, and it is undoubtably because I don't know what to search for but I am hoping someone here can help :)

I have implemented helmet using a nonce in my node app which is hosting a react application.

Helmet implementation in node app:

app.use((req, res, next) => {
  res.locals.cspNonce = crypto.randomBytes(16).toString("hex");
  next();
});

app.use(
  helmet.contentSecurityPolicy({
    useDefaults: true,
    directives: {
      scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`],
      styleSrc: ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`],
    },
  })
);

The only place in my entire react app where I am importing scripts and stylesheets is the head of my index.html page. So my question is, what do I need to add to the script and link tags below in order for me to use the CSP with nonce correctly?

react app index.html




        

    
    

    
    
    

    
    Some title

javascript node.js content-security-policy helmet.js