JAVASCRIPT
Implementing API Rate Limiting with Express.js Middleware
Protect Node.js API endpoints from abuse, brute-force attacks, and DDoS. Implement effective rate limiting using `express-rate-limit` middleware, ensuring stable service availability and preventing server overload.
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
});
// Apply to specific (e.g., login) routes
const loginLimiter = rateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 5, // Limit each IP to 5 login requests per windowMs
message: 'Too many login attempts from this IP, please try again after 5 minutes',
standardHeaders: true,
legacyHeaders: false,
});
// Apply the global rate limit to all requests
app.use(globalLimiter);
// Public route
app.get('/', (req, res) => {
res.send('Welcome to the API! This route is rate-limited globally.');
});
// Login route with a stricter rate limit
app.post('/login', loginLimiter, (req, res) => {
// Simulate login logic
res.send('Login attempt processed.');
});
// Another public route
app.get('/data', (req, res) => {
res.json({ message: 'This is some data.' });
});
// Start the server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log('Try accessing /login multiple times quickly to see rate limit in action.');
});
How it works: Rate limiting is a crucial security measure that restricts the number of requests a user can make to a server within a given timeframe. This Node.js snippet demonstrates how to implement rate limiting in an Express.js application using the `express-rate-limit` middleware. By applying different limits to various endpoints (e.g., a stricter limit for login attempts), you can mitigate brute-force attacks, prevent API abuse, and ensure your server remains responsive and available even under high load or malicious activity.