Script Valley
REST API Development: Beginner to Production
Testing, Documentation, and Production DeploymentLesson 6.3

Rate limiting and security headers for production APIs

express-rate-limit, helmet, CORS with cors package, rate limit headers, trust proxy, X-RateLimit headers, brute force protection, Content-Security-Policy

Rate Limiting and Security Headers

Every production API needs rate limiting to prevent abuse and security headers to prevent web-based attacks. Both are two npm installs away.

Helmet โ€” Security Headers

npm install helmet

// Add as first middleware
app.use(helmet());
// Sets: X-Content-Type-Options, X-Frame-Options, HSTS,
//       Content-Security-Policy, and more โ€” 11 headers in one line

CORS

npm install cors

app.use(cors({
  origin: process.env.ALLOWED_ORIGINS?.split(',') || '*',
  methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));

Rate Limiting

npm install express-rate-limit

const rateLimit = require('express-rate-limit');

// Global limit
app.use(rateLimit({ windowMs: 60 * 1000, max: 100 }));

// Strict limit for auth endpoints
app.use('/auth', rateLimit({ windowMs: 15 * 60 * 1000, max: 10 }));

In production behind a reverse proxy (Nginx, AWS ALB), set app.set('trust proxy', 1) so rate limiting uses the real client IP from X-Forwarded-For rather than the proxy IP. Without this, all traffic appears to come from one IP and rate limiting breaks.

Up next

Environment variables and config management for APIs

Sign in to track progress

Rate limiting and security headers for production APIs โ€” Testing, Documentation, and Production Deployment โ€” REST API Development: Beginner to Production โ€” Script Valley โ€” Script Valley