← Back to Node.js, page 9

nodejs-0161 · Easy fresher

What does helmet do in an Express app, and which security headers matter most?

helmet is Express middleware that sets a group of HTTP security headers and removes X-Powered-By. The important ones are Content-Security-Policy (limits where scripts and other content can load from, reducing XSS impact), Strict-Transport-Security (forces HTTPS), X-Content-Type-Options: nosniff, frame protection (frame-ancestors or X-Frame-Options), Referrer-Policy and Cross-Origin policies. Defaults are a good start, and the CSP needs tuning for your app.

Full answer

helmet is a collection of small middleware functions. app.use(helmet()) turns on sensible defaults.

Headers that matter

  • Content-Security-Policy (CSP): a list of allowed sources for scripts, styles, images, frames and connections. A strict policy (no inline scripts, nonces or hashes instead) greatly reduces the damage of an XSS bug. It is the most powerful and the hardest to configure.
  • Strict-Transport-Security (HSTS): tells browsers to use HTTPS only for a period (max-age). Only send it over HTTPS and test before enabling includeSubDomains and preload.
  • X-Content-Type-Options: nosniff stops browsers from guessing a different content type (for example executing an upload as script).
  • Frame protection: CSP frame-ancestors (or X-Frame-Options) prevents clickjacking.
  • Referrer-Policy limits what URL data leaks to other sites.
  • Cross-Origin-Opener-Policy, Cross-Origin-Resource-Policy and similar headers isolate your pages from other origins.
  • X-Powered-By: Express is removed (it only helps attackers pick exploits).

Practical advice

  • Headers are a second line of defence. They do not replace input validation, output encoding and patching.
  • An API that only returns JSON needs fewer headers than a site that serves HTML. Still set nosniff and HSTS.
  • Use CSP in report-only mode first (Content-Security-Policy-Report-Only), watch the reports, then enforce.
  • Set headers at the reverse proxy or CDN if you have one, but do not set them twice with different values.
  • Scan with securityheaders.com or an automated test that checks the response headers.
javascript
const express = require('express');
const helmet = require('helmet');

const plain = express();
plain.get('/', (req, res) => res.send('plain'));

const protectedApp = express();
protectedApp.use(helmet({
  contentSecurityPolicy: { directives: { defaultSrc: ["'self'"], scriptSrc: ["'self'"], objectSrc: ["'none'"], frameAncestors: ["'none'"] } },
}));
protectedApp.get('/', (req, res) => res.send('protected'));

const serve = (app) => new Promise((resolve) => { const s = app.listen(0, '127.0.0.1', () => resolve(s)); });

(async () => {
  for (const [name, app] of [['without helmet', plain], ['with helmet', protectedApp]]) {
    const server = await serve(app);
    const res = await fetch('http://127.0.0.1:' + server.address().port + '/');
    console.log('--', name);
    for (const header of ['x-powered-by', 'content-security-policy', 'strict-transport-security', 'x-content-type-options', 'referrer-policy', 'cross-origin-opener-policy']) {
      console.log(' ', header.padEnd(28), res.headers.get(header) ?? '(not set)');
    }
    server.close();
  }
})();

The same route is served with and without helmet, and the security headers are printed for each. Install first with npm install express helmet (run here with express 5.3.0, helmet 8.3.0). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): -- without helmet x-powered-by Express content-security-policy (not set) strict-transport-security (not set) x-content-type-options (not set) referrer-policy (not set) cross-origin-opener-policy (not set) -- with helmet x-powered-by (not set) content-security-policy default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'none';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests strict-transport-security max-age=31536000; includeSubDomains x-content-type-options nosniff referrer-policy no-referrer cross-origin-opener-policy same-origin

Key points

  • helmet sets a group of security headers and removes X-Powered-By.
  • CSP limits script sources and reduces XSS damage.
  • HSTS forces HTTPS; nosniff stops content type guessing.
  • Headers are a second line of defence, not a fix for XSS.
  • Try CSP in report-only mode first.

Common mistakes

  • Adding helmet and believing XSS is solved.
  • Enabling HSTS preload without testing every subdomain.
  • A CSP with unsafe-inline that gives no protection.
  • Leaving X-Powered-By on.
  • Setting different header values in the proxy and in the app.

Follow-ups

  • How do nonces make inline scripts safe under a CSP?
  • What does HSTS preload mean?
  • Which headers matter for a JSON-only API?

Tips

  • Name CSP, HSTS and nosniff first.
  • Say that headers are defence in depth.
  • Mention report-only mode.