10 minutes read

Limit Number of Requests in Node Js Express

Summary:To prevent resources abuse it is very important to limit the number of requests an IP address can make to the server. In this post, we will look at simple steps to limit the number of requests in Node js.

Rate limiting helps to prevent a large number of requests to the server. It can be of many reasons such as intentional or unintentional.

Suppose you are building a client application and due to some loop or any other error, the application makes thousands of requests in seconds. If you have implemented proper rate-limiting then it can be fixed in the early phase.

Firstly we need to install Express Rate Limit by the following command.

npm i express-rate-limit

And then the actual implementation in index.js file.

const limiter = rateLimit({
  windowMs: 1 * 60 * 1000, // 1 minutes
  max: 500, // limit each IP to 500 requests per windowMs
});

app.use(limiter);

The above configuration will limit the number of requests to 500 requests per minute for an IP address.

Join Our Youtube Channel

Subscribe