JAVASCRIPT
Protect API Endpoints with Server-Side Rate Limiting
Implement server-side API rate limiting in Node.js Express applications to prevent abuse, brute-force attacks, and denial-of-service attempts.
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
const port = 3000;
// Basic rate limiter configuration
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
});
// Specific, stricter rate limiter for login attempts
const loginLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hour
max: 5, // Allow 5 login attempts per hour per IP
message: 'Too many login attempts from this IP, please try again after an hour',
standardHeaders: true,
legacyHeaders: false,
});
// Apply the general API rate limiter to all requests under /api/
app.use('/api/', apiLimiter);
// Apply the stricter login rate limiter to the login endpoint
app.post('/api/login', loginLimiter, (req, res) => {
// Handle login logic
res.send('Login successful (simulated)');
});
// A regular API endpoint (will be covered by apiLimiter)
app.get('/api/data', (req, res) => {
res.send('Here is your data!');
});
app.get('/', (req, res) => {
res.send('Welcome to the homepage. Try /api/data or /api/login');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
How it works: This snippet demonstrates how to implement server-side rate limiting in a Node.js Express application using the `express-rate-limit` middleware. Rate limiting is crucial for protecting API endpoints from various forms of abuse, including brute-force attacks, denial-of-service (DoS) attempts, and excessive resource consumption. It works by restricting the number of requests a user (typically identified by their IP address) can make within a specified time window. The example shows a general `apiLimiter` for most API calls and a more stringent `loginLimiter` specifically for login attempts, which are often targets of brute-force attacks. The `windowMs` defines the time window, and `max` sets the maximum number of requests allowed within that window.