JAVASCRIPT
Implement API Rate Limiting with Express.js
Protect your Node.js API from abuse and denial-of-service attacks by implementing efficient rate limiting using the `express-rate-limit` middleware.
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
// Basic rate limiter: 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',
headers: true, // Send X-RateLimit-* headers
standardHeaders: true, // Set `RateLimit-Limit`, `RateLimit-Remaining`, `RateLimit-Reset` headers
legacyHeaders: false, // Disable the `X-RateLimit-*` headers.
});
// Apply the rate limiting middleware to all requests (or specific routes)
app.use(apiLimiter);
// Apply a stricter rate limiter to authentication routes
const authLimiter = rateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 10, // limit each IP to 10 requests per windowMs for auth routes
message: 'Too many authentication attempts from this IP, please try again after 5 minutes',
headers: true,
standardHeaders: true,
legacyHeaders: false,
});
app.post('/login', authLimiter, (req, res) => {
res.send('Login attempt received.');
});
app.get('/api/data', (req, res) => {
res.json({ message: 'This is some data.' });
});
app.get('/', (req, res) => {
res.send('Welcome to the rate-limited API!');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
How it works: This Node.js snippet demonstrates how to implement API rate limiting in an Express.js application using the `express-rate-limit` middleware. It sets a global limit of 100 requests per 15 minutes for all API calls and a stricter limit of 10 requests per 5 minutes specifically for login routes. Rate limiting protects your API from brute-force attacks, denial-of-service attempts, and general abuse by throttling requests from individual IP addresses.