Send html with nonce for each script and style tag on each request This working code inserts a nonce attribute and value for each style and script tag inside an HTML file, for each GET request. It is using Express. nonce1 and dirViews are already defined. limiter is for rate limiting and is a node module found on npm.

//on get homepage
app.get('/', limiter.middleware(), function(req, res, next) {
    //send an edited index.html containing nonces
    fs.readFile(dirViews+'/index.html', 'utf8', function(err, html){
        let newHTML = html.replace(/&lt;script/g, '&lt;script nonce="'+nonce1+'"').replace(/&lt;style/g, '&lt;style nonce="'+nonce1+'"');
        res.send(newHTML);
    });
});


I am unsure if this is the correct way to do this (set nonce attributes on each GET request), and whether my code follows best practices.
I am unsure if this is the correct way to do this (set nonces on each get)


Yes, it is


  Remember that nonces must be regenerated for every page request and they must be unguessable.


In terms of best practises, couple of things I'd recommend:


Move your nonce manipulation into it's own middleware
Cache your page content, don't read it from disk every time


The end result would look something like:

csp.js

const path = require('path');
const fs = require('fs');

const cache = new Map();

const getHtml = path =&gt; new Promise((resolve, reject) =&gt;
  fs.readFile(path, 'utf-8', (err, contents) =&gt; {
    if (err) return reject(err);

    cache.set(path, contents);
    return resolve(contents);
  }));

const csp = page =&gt; async (req, res, next) =&gt; {
  const pagePath = path.join(dirViews, page);
  let html = cache.get(pagePath);
  if (!html) {
    html = await getHtml(pagePath);
  }
  html = html.replace(/&lt;script/g, `&lt;script nonce="${nonce1}"`)
    .replace(/&lt;style/g, `&lt;style nonce="${nonce1}"`);
  res.send(newHTML);
}

export default csp;


app.js

app.get('/', limiter.middleware(), csp('index.html'))