Add a CSP header in Express
Generate a nonce in Express 5 middleware, store it in res.locals and send a Content-Security-Policy header on every response.
In Express the nonce has to exist before the view renders, so the template can print it, and the header has to carry the same value. A small middleware does both for every request.
import express from 'express';
import { randomBytes } from 'node:crypto';
const app = express();
app.use((req, res, next) => {
res.locals.nonce = randomBytes(16).toString('base64');
res.setHeader(
'Content-Security-Policy',
`default-src 'self'; script-src 'self' 'nonce-${res.locals.nonce}'; object-src 'none'`,
);
next();
});
app.get('/', (req, res) => {
res.send(`<script nonce="${res.locals.nonce}">console.log('ok')</script>`);
});
app.listen(3000);HTTP/1.1 200 OK
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-Qm9v8nJrX0k2yq1Zr3s5Yw=='; object-src 'none'res.locals lives for one request, so the view and the header always see the same value, and the next request gets a new one. Registering the middleware before every route matters: a route declared above it answers without the header. The value in your output will differ because it is random.
If you would rather not write this by hand, helmet accepts a function in scriptSrc that reads res.locals.nonce. Either way, never reuse one nonce across responses.