JAVASCRIPT
Implement Server-Side API Rate Limiting to Prevent Abuse
Learn to implement server-side API rate limiting in an Express.js application using `express-rate-limit` to protect against brute-force attacks and service abuse.
// Install express and express-rate-limit: npm install express express-rate-limit
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
// Configure a global rate limiter for all API requests
const apiLimiter = 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
});
// Configure a stricter rate limiter for sensitive endpoints like login
const loginLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hour
max: 5, // Limit each IP to 5 login attempts per hour
message: 'Too many login attempts from this IP, please try again after an hour',
standardHeaders: true,
legacyHeaders: false,
});
// Apply the global rate limiter to all /api/ routes
// app.use('/api/', apiLimiter); // Uncomment to apply globally
// Apply a stricter rate limiter to the login endpoint
app.post('/login', loginLimiter, (req, res) => {
// Your login logic here
// For demonstration, let's assume login always succeeds or fails
const success = Math.random() > 0.5;
if (success) {
res.send('Login successful!');
} else {
res.status(401).send('Login failed: Invalid credentials.');
}
});
// A regular API endpoint protected by the global limiter (if uncommented)
app.get('/data', apiLimiter, (req, res) => {
res.json({ message: 'This is some data.' });
});
// app.listen(3000, () => console.log('Server running on port 3000'));
How it works: This Node.js snippet demonstrates implementing server-side API rate limiting using the `express-rate-limit` middleware. It shows how to define different rate limit configurations, for example, a general limit for most API routes and a stricter limit for sensitive endpoints like login. By setting `windowMs` (time window) and `max` (maximum requests), you can protect your application from brute-force attacks, denial-of-service attempts, and general API abuse, ensuring fair usage and stability.