Rate limiting is a technique used to control the rate at which clients can make requests to a server. Implementing rate limiting in an Express.js application can help prevent abuse, protect against DoS attacks, and ensure fair usage of resources. Here's a basic example of how you can implement rate limiting as middleware in an Express.js application using the express-rate-limit
package.
express-rate-limit
package:bashnpm install express-rate-limit
javascriptconst express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
// Define a rate limit middleware
const limiter = 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 later.',
});
// Apply the rate limiter middleware to all routes or a specific route
app.use(limiter);
// Your routes go here
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
In the example above:
windowMs
defines the time window for which the rate limit applies (15 minutes in this case).max
specifies the maximum number of requests allowed within the defined time window.message
property sets the message that will be sent in the response when a user exceeds the rate limit.Customize the rate limit parameters according to your application's needs. You may want to adjust the windowMs
and max
values based on your desired rate limiting policy.
Make sure to place the rate limiter middleware before your routes, so it gets executed before any route handlers.
This example provides a basic rate-limiting setup. You can explore additional options provided by the express-rate-limit
package for more advanced configurations, such as handling rate limit exceeded errors or excluding certain routes from rate limiting.