JAVASCRIPT
Implement API Rate Limiting in Express.js
Protect your Node.js Express API from brute-force attacks and abuse by setting up effective rate limiting on specific endpoints using `express-rate-limit`.
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
const port = 3000;
// Apply to all requests
// const globalLimiter = rateLimit({
// windowMs: 15 * 60 * 1000, // 15 minutes
// max: 100, // Limit each IP to 100 requests per windowMs
// message: 'Too many requests from this IP, please try again after 15 minutes',
// standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
// legacyHeaders: false, // Disable the `X-RateLimit-*` headers
// });
// app.use(globalLimiter);
// 1. Create a rate limiter specific to a login route
const loginLimiter = rateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 5, // Allow 5 login attempts per IP per 5 minutes
message: 'Too many login attempts from this IP, please try again after 5 minutes',
standardHeaders: true,
legacyHeaders: false,
});
// 2. Apply the rate limiter to the specific route
app.post('/login', loginLimiter, (req, res) => {
// In a real app, you'd process login credentials here
console.log('Login attempt received from IP:', req.ip);
res.send('Login attempt processed.');
});
// A general public route (no rate limit applied by default)
app.get('/public', (req, res) => {
res.send('This is a public route.');
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
console.log(`Try accessing /login multiple times to hit the rate limit.`);
});
How it works: This Node.js snippet demonstrates how to implement rate limiting for specific API endpoints in an Express.js application using the `express-rate-limit` middleware. By configuring a `loginLimiter` that allows only 5 requests within a 5-minute window per IP, it effectively mitigates brute-force attacks on sensitive routes like login pages. When the limit is exceeded, the server responds with a custom message, protecting resources and improving application resilience against abuse.