Integrating Express-rate-limit in Node.js

Node.jsJavascriptWeb DevelopmentFront End Technology

Rate-limiting is becoming important day by day to prevent websites from DOS & DDOS attacks. The rate-limiting prevents the system from any type of fake requests or other brute force attacks. Rate limiting limits the number of times an IP can make requests. The expressrate-limit is the npm package to limit the number of requests from a user.

Installing the rate-limit module

Run the below command to install the express rate-limiting module in your application.

npm install --save express-rate-limit

Example

Create a file with name – rateLimit.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −

node rateLimit.js

rateLimit.js

// Importing the express dependency
const express = require("express");

// Importing the express-rate-limit dependency
const rateLimit = require("express-rate-limit");

// Storing the express function in variable application
const applicaion = express();

// Calling the ratelimiter function with its options
// max: Contains the maximum number of requests
// windowsMs: Contains the time in milliseconds to receive max requests
// message: message to be shown to the user on rate-limit
const limiter = rateLimit({
   max: 5,
   windowMs: 60 * 60 * 1000,
   message: "Too many request from this IP"
});

// Adding the rate-limit function to the express middleware so
// that each requests passes through this limit before executing
applicaion.use(limiter);

// GET route for handling the user requests
applicaion.get("/", (req, res) => {
   res.status(200).json({
      status: "SUCCESS",
      message: "Welcome to TutorialsPoint !"
   });
});

// Server Setup
const port = 8000;
applicaion.listen(port, () => {
   console.log(`app is running on port ${port}`);
});

Output

C:\home\node>> node rateLimit.js

After running the node application, go to your browser and hit localhost:8000

You will see a similar page as shown below.

Try hitting or refreshing the same URL more than 5 times and you will receive the below error.

raja
Published on 20-May-2021 11:19:23
Advertisements