Express.js & REST APIs
Node.js Rate Limiting
Rate limiting caps how many requests a client can make in a time window. It protects against brute-force login attempts, scraping and accidental client loops.
What is Rate Limiting in Node.js?
Rate limiting caps how many requests a client can make in a time window. It protects against brute-force login attempts, scraping and accidental client loops.
Rate Limiting example
JavaScript
import rateLimit from 'express-rate-limit';
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 300,
standardHeaders: true,
message: { error: 'Too many requests. Please try again later.' },
});
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5,
skipSuccessfulRequests: true,
});
app.use('/api', apiLimiter);
app.post('/api/auth/login', loginLimiter, login);Key points to remember
- Apply a much tighter limit to login, OTP and password-reset endpoints.
- Behind a proxy, set app.set("trust proxy", 1) or every client looks like one IP.
- Use a Redis store when running more than one process, or each has its own counter.
- Return 429 with a Retry-After header.
Common mistakes with Rate Limiting
- Forgetting trust proxy behind Nginx, so the limiter sees only the proxy IP.
- In-memory counters across clustered processes, multiplying the effective limit.
Node.js Rate Limiting— Interview Questions & FAQs
How do I rate limit only the login endpoint?+
Create a separate limiter with a low max and apply it as middleware on that route only, while a looser limiter covers the rest of the API.
