Authentication and SecurityLesson 5.4
Securing Express APIs: helmet, rate limiting, and CORS
helmet headers, express-rate-limit, CORS configuration, HTTPS enforcement, XSS protection, clickjacking prevention
Three Security Layers Every API Needs
Helmet sets a dozen HTTP security headers in one line. Always add it before other middleware.
npm install helmet express-rate-limit corsconst helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const cors = require('cors');
app.use(helmet());
app.use(cors({
origin: ['https://myapp.com'],
methods: ['GET', 'POST', 'PATCH', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
standardHeaders: true,
legacyHeaders: false,
message: { error: 'Too many requests, slow down' }
});
app.use('/api/', limiter);
const authLimiter = rateLimit({ windowMs: 60 * 60 * 1000, max: 5 });
app.use('/api/login', authLimiter);The auth limiter prevents brute-force attacks on login โ 5 attempts per hour per IP is enough for legitimate users and painful for attackers.
