How to add Rate Limit in express.js
Rate limiting is a technique used to control the amount of incoming requests to a server in order to protect it from being overwhelmed or to prevent against malicious attacks such as Brute force , DoS attacks.
Project Setup
To create a new Express.js app, follow these steps:
- Open a terminal and navigate to the directory where you want to create your project.
2. Run the following command to create a new Express.js App:
mkdir express-rate-limit
cd express-rate-limit
npm init -y
npm install express express-rate-limit
4. Create a new file named app.js
and add the following code to it:
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log('Server listening on port 3000');
});
This code creates a new Express.js app that listens for incoming HTTP GET requests on the root path (/
) and responds with a "Hello, World!" message. You can run this code using node app.js
.
Now Add rate limiting to your app
To add rate limiting in our app, we need to require the express-rate-limit
module and use it to create a rate limit middleware function.
Add the following code to the top of the app.js file to require the express-rate-limit module and create a rate limit middleware function:
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 20, // Limit each ip to 20 requests
});
This rateLimit function takes an options object as an argument. The windowMs
option specifies the time frame for the rate limit, in this case 5 minutes. The max
option specifies the maximum number of requests that an IP address can make within the specified time frame.
Next, we need to apply the rate limit middleware to our Express.js app using:
app.use(limiter);
Now, if an IP address makes more than 20 requests within a 5 minute window, it will receive a response with a status code of 429 (Too Many Requests) and a message explaining that the rate limit has been exceeded.
Testing the rate limit
To test the rate limit, start the Express.js app by running the following command in the terminal:
node app.js
Then, open http://localhost:3000/ in your web browser. You should be able to make up to 20 requests within a 5-minute window before receiving a response with a status code of 429.
here you will a similar page as show below:
After refreshing the same URL more that 20 times
To customize the response that is sent when the rate limit is exceeded, you can pass a custom handler function as the handler option in the rate limit middleware. For example:
const limiter = rateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 20, // Limit each ip to 20 requests
handler: (req, res) => {
res.status(429).send({ error: 'Too many requests, please try again later' });
}
});
This will send a response with a status code of 429 and a JSON object containing an error message when the rate limit is exceeded.
You can also customize the rate limit for specific routes by applying the rate limit middleware only to those routes. For example:
app.get('/api/users', limiter, (req, res) => {
// route logic
});
This will apply the rate limit only to requests made to the /api/users route.
Full Code
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
const port = process.env.PORT || 3000;
const limiter = rateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 20, // Limit each ip to 20 requests
handler: (req, res) => {
res.status(429).send({ error: 'Too many requests, please try again later' });
}
});
app.use(limiter);
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log('Server listening on port 3000');
});
Conclusion
Rate limiting is an important tool for protecting your app from various types of attacks. It’s relatively easy to implement in an express.js application using the express-rate-limit middleware, and it can be customized to fit the needs of your application. While it’s not a foolproof solution, it can provide an important layer of protection for your app.