'Access nonce value inside your index.html

I'm having prod.js module like this which I'm using to set content security policy

const helmet = require('helmet');
const compression = require('compression');

module.exports = function (app) {

    app.use((req, res, next) => {
        res.locals.cspNonce = crypto.randomBytes(16).toString("hex");
        next();
      });
      
    app.use(
        helmet.contentSecurityPolicy({
          useDefaults: true,
          directives: {
            scriptSrc: [ "'self'", 'js.stripe.com', 'https://checkout.stripe.com', 'js.stripe.com',  'https://billing.stripe.com', ( request, response ) => `'nonce-${res.locals.cspNonce}'` ],
            styleSrc:  ["'unsafe-inline'"],
            connectSrc:[" * 'self' https://checkout.stripe.com https://billing.stripe.com"],
            frameSrc:  ["'self'  https://checkout.stripe.com  https://billing.stripe.com https://js.stripe.com ;"],
            imgSrc:    [" 'self' blob: https://api.company.com/  data:"], 
          },
        })
      );


    app.use(compression());
};

I want to access this nonce value created in index.html inside my react app. So that I can pass it to script tags like this

React app index.html

 <!DOCTYPE html>

<html lang="en">
  <head>      

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    
    <script 
      nonce={.........//Get the nonce value here............}
    >
    </script>

    
    <title>Some title</title>


But I'm not able to figure out how to access nonce inside my Index.html.

P.S: I'm new to programming. Please let me know if you need any other info to help me with this case.

Adding additional info ----------

I'm invoking prod.js in my Index.js file inside my node project.

My Index.js looks like this

const express = require('express');
const https = require('https');
const path = require('path');
const app = express();


require('./startup/routes')(app);
require('./startup/db')();
require('./startup/config')();
require('./startup/validation')();
require('./startup/prod')(app);



Solution 1:[1]

Your nonce value will be resolved after you fetch it from your API. Here is a simplistic example of implementation:

class MyApp {
    constructor() {
        this.nonce = "";
        this.app_ready = false;
        this.fetchNonce();
    }

    setNonce(value) {
        this.nonce = value;
        this.app_ready = true;
        // Do what you have to do when your app is ready, mount your components, etc...
    }

    fetchNonce() {
        fetch("https://url/to/your/api")
            .then(response => {
               this.setNonce(response.headers.key.to.your.value)
            })
            .catch(error => {/*Handle you app state in case of error...*/})
    }

}

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 Peterrabbit