ExpressJS - Rate Limiting



Rate Limiting is a security measure which helps maintaining the stability, security and performance of a web application. For example, consider the following scenarios:

  • Too many requests− if a server receives 100 request in a time span of 1 second which it is not capable to handle, then performance will be deteriorated.

  • Brute Force Attack− If 100 requests comes from a single user in a very little timespan, it may be the case of brute-force attack.

Using express-rate-limit dependency

In express applications, we can use express-rate-limit as a dependency to implement rate limiting. express-rate-limit middleware controls the rate of incoming requests to an express application. Following are two important parameters of express-rate-limit.

  • windowMs− Time in milliseconds. Rate limits applies during this time. For example, to define a window of 10 minutes, we can set windowMs as 10 * 60 * 1000.

  • max− Maximum number of requests allowed from a single IP address within the time window. If more requests come, then rate limit will be triggered.

Installing express-rate-limit dependency

We can use the following command to install above express-rate-limit dependency using npm.

npm install express-rate-limit

Initialize express-rate-limit and use

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

var app = express();

// configure rate limiter with a time window of 10 minutes
// and maximum 3 requests
const limiter = rateLimit({
  windowMs: 10 * 60 * 1000,
  max: 3,
});

app.use(limiter);

app.get('/', function(req, res){
   res.send("Hello world!");
});

app.listen(3000);

Save the file, go to your terminal and type the following.

nodemon index.js
[nodemon] 3.1.9
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node index.js`

This will start the server. To test this app, open your browser and go to http://localhost:3000 and a message will be displayed as in the following screenshot.

Hello world

Now refresh the page 4 times, browser will show the error message.

Error Rate Limit
Advertisements