Skip to content

Limit API requests in express.js

In this tutorial we are going to use an npm package called express-rate-limit. Install it using the following command.

npm install express-rate-limit

This library provides a brute-force protection for express routes by rate-limiting incoming requests, increasing the delay with each request in a fibonacci-like sequence.

Example

const rateLimit = require("express-rate-limit");


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

//  apply to all requests
app.use(limiter);
Advertisements

Rate-limiter for a route

const rateLimit = require("express-rate-limit");


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

//  apply to all requests
app.use("/user",limiter);

See also  How to Dockerize your node.js application?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.