intermediate
Express security middleware
Use headers, CORS, cookies, rate limits, body limits, logging redaction, and proxy trust deliberately in Express services.
Security middleware hardens the HTTP surface: Helmet sets security headers, CORS restricts browser origins, rate limiters throttle abuse, and `trust proxy` configures correct client IP behind load balancers.
app.set('trust proxy', 1);
app.use(helmet());
app.use(cors({ origin: allowedOrigins, credentials: true }));
app.use('/api', rateLimit({ windowMs: 60_000, max: 100 }));
app.use(cookieParser());
app.use(express.json({ limit: '100kb' }));
Cookie flags (`httpOnly`, `secure`, `sameSite`) protect session tokens. Redact secrets in request logs. Body limits prevent memory exhaustion. Configure CORS explicitly — wildcard with credentials is invalid.
On interviews: name which headers Helmet sets and why, when `trust proxy` is required, and how rate limiting interacts with authenticated versus anonymous traffic.
Common pitfalls: CORS misconfiguration blamed on the frontend, logging Authorization headers, and enabling `trust proxy` without understanding spoofed `X-Forwarded-For`.
The trade-off is balancing simplicity, performance, safety, and operability — name which axis you optimized and what cost you accepted.
Checklist:
- Apply Helmet and explicit CORS policy.
- Set cookie security flags for sessions.
- Rate-limit sensitive and auth endpoints.
- Configure trust proxy only behind known proxies.