advanced
CORS, CSP, and secure headers
Configure CORS narrowly, deploy CSP as a defense-in-depth policy, and set security headers for transport, framing, MIME sniffing, and referrer behavior.
Security headers harden browser behavior. Deploy as a consistent set — gaps leave holes.
| Header | Purpose | |--------|---------| | Strict-Transport-Security | Force HTTPS | | Content-Security-Policy | Limit script/style/load origins | | X-Content-Type-Options: nosniff | Block MIME sniffing | | Referrer-Policy | Control leaked referrer | | Permissions-Policy | Disable unused APIs (camera, geolocation) |
app.use((_req, res, next) => {
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
res.setHeader('Content-Security-Policy', "default-src 'self'; frame-ancestors 'none'");
next();
});
CORS is not authentication — narrow `Access-Control-Allow-Origin` to known frontends. CSP complements output encoding; start report-only, fix violations, enforce.
On interviews: difference between CORS and CSP; HSTS preload caveats; why `X-XSS-Protection` is obsolete.
Common pitfalls: permissive `default-src *`; reflecting Origin without validation; missing HSTS on API-only subdomains used by browsers.
The trade-off is balancing simplicity, performance, safety, and operability — name which axis you optimized and what cost you accepted.
Checklist:
- HSTS after full HTTPS coverage.
- CSP with nonces or hashes for inline scripts.
- Minimal CORS allowlist; credentials need explicit origin.
- Set security headers in one middleware module.