JAVASCRIPT
Implementing API Rate Limiting to Prevent Abuse
Protect your API endpoints from brute-force attacks and abuse by implementing effective rate limiting using the `express-rate-limit` middleware in Node.js.
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
// 1. Basic API Rate Limiter
// Allow 100 requests per 15 minutes per IP
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
});
// 2. Stronger Rate Limiter for Login/Authentication Routes
// Allow 5 requests per 5 minutes per IP for sensitive routes
const loginLimiter = rateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 5, // Limit each IP to 5 login attempts per windowMs
message: 'Too many login attempts from this IP, please try again after 5 minutes',
standardHeaders: true,
legacyHeaders: false,
});
// Apply the basic rate limiter to all /api/ requests
app.use('/api/', apiLimiter);
// Apply the stronger login limiter to specific authentication routes
app.post('/login', loginLimiter, (req, res) => {
// Your login logic here
// For demonstration, let's simulate a login attempt
const { username, password } = req.body;
if (username === 'user' && password === 'pass') {
res.status(200).send('Login successful!');
} else {
res.status(401).send('Invalid credentials.');
}
});
app.get('/api/data', (req, res) => {
res.send('This is some API data (rate limited).');
});
app.get('/', (req, res) => {
res.send('Welcome! Try accessing /api/data or POSTing to /login.');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
How it works: This snippet demonstrates how to implement API rate limiting in an Express.js application using the `express-rate-limit` middleware. Rate limiting protects against brute-force attacks, denial-of-service (DoS) attempts, and general API abuse by restricting the number of requests a single IP address can make within a specified time window. The example shows how to configure a general limiter for API routes and a more stringent one for sensitive endpoints like login, providing clear messages when limits are exceeded.