Skip to content
jshacks.dev
Security

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.

1 min read
Summarize in AI

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.

server.jsJavaScript
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);
Text
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.

Also inNode.js
Share

More snippets

Testing

Group tests with describe in node test

Group related tests with describe and it from node:test, nest suites, and run setup with beforeEach, all without installing a framework.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.