JAVASCRIPT
Implement Basic API Rate Limiting in Node.js Express
Protect your Node.js Express API from abuse and overload by implementing a simple rate-limiting middleware, allowing a defined number of requests per time window.
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
});
// Apply the rate limiter to all requests
// or specific routes (e.g., app.use('/api/', apiLimiter);)
app.use(apiLimiter);
app.get('/api/data', (req, res) => {
res.json({ message: '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 a basic API rate limiter using the `express-rate-limit` middleware. It configures the server to allow a maximum of 100 requests from a single IP address within a 15-minute window. If the limit is exceeded, the server responds with a 429 Too Many Requests status. This is crucial for protecting your API from denial-of-service attacks, brute-force attempts, and ensuring fair usage among all consumers, thereby maintaining server stability and performance. Remember to install the required package: `npm install express express-rate-limit`.