JAVASCRIPT
Server-Side API Rate Limiting with `express-rate-limit`
Implement robust server-side rate limiting in Express.js applications to prevent brute-force attacks and abuse, ensuring API stability and fair resource usage.
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
// Apply to all 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
});
// Apply to specific routes, e.g., authentication
const authLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hour
max: 5, // Limit each IP to 5 requests per hour for auth
message: 'Too many authentication attempts from this IP, please try again after an hour',
standardHeaders: true,
legacyHeaders: false,
});
app.use('/api/', apiLimiter); // Apply to all API routes
app.post('/login', authLimiter, (req, res) => {
// Handle login logic
res.send('Login attempt processed.');
});
app.get('/', (req, res) => {
res.send('Welcome!');
});
// Example API route
app.get('/api/data', (req, res) => {
res.json({ message: 'Here is your data!' });
});
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 server-side API rate limiting using the `express-rate-limit` middleware for Node.js. It helps protect your application from brute-force attacks, denial-of-service (DoS) attempts, and general abuse by limiting the number of requests a user can make within a specified timeframe. Different limits can be applied to various routes, such as stricter limits for sensitive endpoints like login.