Security Headers and CORS

Security headers

The server sends these to tell the browser to turn on its protections.

HeaderProtects against
Content-Security-PolicyXSS, data injection (see 05)
Strict-Transport-Security (HSTS)HTTPS downgrade, SSL stripping
X-Content-Type-Options: nosniffMIME sniffing
X-Frame-Options / CSP frame-ancestorsClickjacking
Referrer-PolicyLeaking URLs (with tokens) to other sites
Permissions-PolicyUnwanted camera, mic and location access
Remove X-Powered-ByRevealing the framework

Packages

PackageUse
helmetSets all the headers above with good defaults
corsConfigures CORS

✅ Helmet

const helmet = require('helmet');
app.use(helmet()); // also removes X-Powered-By
app.use(helmet.hsts({ maxAge: 63072000, includeSubDomains: true, preload: true }));

CORS

CORS does not protect your server. It tells the browser which other sites may read your responses. A misconfigured CORS lets evil.com read a logged-in user's data.

❌ Vulnerable

app.use(cors({ origin: true, credentials: true })); // reflects ANY origin, with cookies
// or
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);

✅ Secure

const cors = require('cors');
const allowed = ['https://app.example.com', 'https://admin.example.com'];

app.use(cors({
  origin: (origin, cb) => cb(null, !origin || allowed.includes(origin)),
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
}));

Check your headers

Checklist

  • helmet() on every app
  • HTTPS only + HSTS
  • CORS: explicit allowlist, never * together with credentials
  • Don't use regexes like /example\.com$/ (evilexample.com matches)