How to rate limit the API requests in Express
In this tutorial, we are going to learn about how to rate limit the number of API requests made by an each user in express app.
What is Rate Limit?
A rate limit is the number of API requests an app or user can make within a given time period. If this limit is exceeded, the app or user will not be allowed to make any API requests until the given time period is finished.
Installing express-rate-limit
To rate limit the requests, first we need to install a new package called express-rate-limit
, which is a rate limiting middleware for express and node.js apps.
Run the following command to install the package.
npm install express-rate-limit
Rate limiting the requests
In this example, we are rate limiting each ip address to 50 requests for 15 minutes.
const express = require("express");
const rateLimit = require("express-rate-limit");const app = express();
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 50, // limit each IP to 50 requests per windowMs
message: "Too many requests, please try again after 15 minutes"
// this above message is shown to user when max requests is exceeded
});
app.use(limiter); // rate limiting applies to all routes
app.get("/users", (req, res) => {
res.send('hello')
});
app.listen(3000, () => console.log(`App is running`));
Rate limiting the particular routes
If you want to rate limit a particular routes in your app instead of all routes, for example the same user (ip) is creating too many accounts or booking too many tickets, and you need to block them for a specific time.
const express = require("express");
const rateLimit = require("express-rate-limit");const app = express();
app.get("/users", (req, res) => {
res.send('hello')
});
const accountLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hour
max: 6, // limit each IP to 6 requests per windowMs
message: "Too accounts created, please try again after 1 hour"
});
app.post('/create-account', accountLimiter, (req, res) => { // your logic
res.send('account is created');
});
app.listen(3000, () => console.log(`App is running`));
In the above code, we have passed the accountLimiter
middleware as a second argument to the /create-account
route handler function, so that if any user makes more than 6
requests in 1 hour that user is not allowed to make any requests until 1 hour is finished.