Express ships with sensible defaults for routing but no defaults for security. A vanilla express() app responds without X-Frame-Options, Content-Security-Policy, or Strict-Transport-Security, accepts unlimited request bodies, has no rate limiting, and tells the world its version via X-Powered-By. This walks through the security middleware stack that closes those gaps and what each header actually buys you in production.
How to verify
See what headers your service emits today:
curl -sI http://127.0.0.1:3000/ | grep -E 'X-|Strict|Content-Security|Powered'
curl -s -X POST -d "$(head -c 50000000 /dev/urandom | base64)" \
-H "Content-Type: text/plain" http://127.0.0.1:3000/echo # body size test
for i in {1..200}; do curl -s -o /dev/null -w "%{http_code}\n" \
http://127.0.0.1:3000/login; done | sort | uniq -c # rate-limit response
curl -sI -H "Origin: https://evil.example" http://127.0.0.1:3000/api | grep -i access-control
If X-Powered-By: Express is in the response, Helmet is not installed. If a 50 MB POST returns 200, you have no body limit. If 200 logins return 200 every time, you have no rate limit on auth.
What’s happening
The security middleware stack lives at the front of the request pipeline. Helmet sets a curated default set of HTTP response headers that mitigate clickjacking, XSS, MIME-type confusion, and information disclosure. express-rate-limit tracks request counts per IP (or per user) and returns 429 when a threshold is crossed. cors controls which cross-origin browsers are allowed to read responses. express.json({ limit }) and express.urlencoded({ limit }) bound the body size to stop trivial DoS. None of these prevent application-layer bugs; they harden the perimeter so application bugs are not also amplifiable.
The right order matters. Helmet first (so its headers attach to everything including 4xx errors), CORS second (so OPTIONS preflights complete before auth runs), rate limit third (so per-IP limits hit before expensive auth lookups), then auth, then routes.
The procedure
-
Install the standard set:
npm install helmet cors express-rate-limit express-slow-down -
Wire them in the right order at the top of your app:
import express from 'express'; import helmet from 'helmet'; import cors from 'cors'; import rateLimit from 'express-rate-limit'; const app = express(); app.disable('x-powered-by'); // explicit, even with Helmet app.set('trust proxy', 1); // honor X-Forwarded-For from proxy app.use(helmet({ contentSecurityPolicy: { directives: { defaultSrc: ["'self'"], scriptSrc: ["'self'"], imgSrc: ["'self'", 'data:'], connectSrc: ["'self'", 'https://api.example.com'], }, }, hsts: { maxAge: 31536000, includeSubDomains: true, preload: true }, })); app.use(cors({ origin: ['https://app.example.com', 'https://admin.example.com'], credentials: true, methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], })); app.use(express.json({ limit: '1mb' })); app.use(express.urlencoded({ extended: true, limit: '1mb' })); -
Add rate limiting. Different routes need different limits — auth is the strictest:
const authLimiter = rateLimit({ windowMs: 15 * 60_000, max: 10, // 10 attempts per 15 min per IP standardHeaders: true, legacyHeaders: false, skipSuccessfulRequests: false, }); const apiLimiter = rateLimit({ windowMs: 60_000, max: 100, standardHeaders: true, }); app.use('/auth/', authLimiter); app.use('/api/', apiLimiter); -
For distributed deployments, replace the default in-memory store with Redis so the count is shared across replicas:
npm install rate-limit-redis ioredisimport RedisStore from 'rate-limit-redis'; import { Redis } from 'ioredis'; const redis = new Redis(process.env.REDIS_URL); const apiLimiter = rateLimit({ store: new RedisStore({ sendCommand: (...a) => redis.call(...a) }), windowMs: 60_000, max: 100, }); -
Add slow-loris protection. The default Express server keeps connections open with no read timeout — a slow client can hold a connection for minutes. Set explicit timeouts:
const server = app.listen(3000); server.headersTimeout = 65_000; // must be > requestTimeout server.requestTimeout = 60_000; server.keepAliveTimeout = 30_000;
Common pitfalls
- A loose CSP (
'unsafe-inline','unsafe-eval') makes the header decorative. Audit the actual values and tighten progressively. UseReport-Onlymode first to gather violation reports without breaking the app. trust proxyis required forreq.ipto reflect the real client behind a reverse proxy. Without it, rate limiting sees only the proxy IP and applies one budget to all users.- Rate limit by IP is bypassable behind shared NAT and CDNs. For auth endpoints, also rate limit by username — even before a successful login.
cors({ origin: '*' })pluscredentials: trueis a misconfiguration the browser rejects. If you need credentials, list explicit origins.- Helmet’s defaults change between major versions. Pin the version and re-test headers when upgrading; v6 to v7 removed some headers as defaults.
For a deeper review of supply-chain risk in the same service, see npm audit and Snyk. In the engagements Stack Harbor runs, the security middleware stack is templated — every new Express service starts with Helmet, CORS, rate limit, and Redis-backed limits already wired, and we audit headers in CI as part of managed operations so a configuration drift doesn’t quietly weaken the perimeter.