Security Headers and CORS
Security headers
The server sends these to tell the browser to turn on its protections.
| Header | Protects against |
|---|---|
Content-Security-Policy | XSS, data injection (see 05) |
Strict-Transport-Security (HSTS) | HTTPS downgrade, SSL stripping |
X-Content-Type-Options: nosniff | MIME sniffing |
X-Frame-Options / CSP frame-ancestors | Clickjacking |
Referrer-Policy | Leaking URLs (with tokens) to other sites |
Permissions-Policy | Unwanted camera, mic and location access |
Remove X-Powered-By | Revealing the framework |
Packages
| Package | Use |
|---|---|
helmet | Sets all the headers above with good defaults |
cors | Configures 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.commatches)