REST API Security: CORS, Helmet, Rate Limiting, and Input Sanitization
CORS, helmet, rate limiting, express-rate-limit, input sanitization, XSS prevention, NoSQL injection, security headers, HTTPS
REST API Security: CORS, Helmet, Rate Limiting, and Input Sanitization
A REST API exposed to the internet is a target for abuse. Authentication proves identity, but security goes deeper — preventing injection attacks, cross-origin misuse, brute-force attacks, and data exposure. This lesson covers the security layer every production REST API must have.
Security Headers with Helmet
npm install helmet
app.use(helmet());Helmet sets HTTP security headers that protect against common attacks: X-Frame-Options prevents clickjacking, X-Content-Type-Options prevents MIME sniffing, Content-Security-Policy restricts resource loading, and Strict-Transport-Security enforces HTTPS.
CORS Configuration
npm install cors
app.use(cors({
origin: process.env.ALLOWED_ORIGINS.split(','),
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true
}));Never use cors({ origin: '*' }) for authenticated APIs — this allows any website to make credentialed requests to your API. Always explicitly whitelist allowed origins in production.
Rate Limiting
npm install express-rate-limit
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
standardHeaders: true,
message: { success: false, error: { code: 'RATE_LIMIT_EXCEEDED' } }
});
app.use('/api', limiter);
const authLimiter = rateLimit({ windowMs: 60 * 60 * 1000, max: 10 });
app.use('/api/auth', authLimiter);Input Sanitization
npm install express-mongo-sanitize xss-clean
app.use(mongoSanitize());
app.use(xss());express-mongo-sanitize strips MongoDB operators like $where from inputs. xss-clean removes HTML tags to prevent stored XSS attacks.
