Open In App

What is Express-rate-limit in Node.js ?

Last Updated : 19 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Node.js is an open-source and cross-platform runtime environment built on Chrome’s V8 JavaScript engine for executing JavaScript code outside of a browser. You need to recollect that NodeJS isn’t a framework, and it’s not a programming language. It provides an event-driven, non-blocking (asynchronous) I/O and cross-platform runtime environment for building highly scalable server-side applications using JavaScript.

In this article, we will learn about the Express-Rate limit.

Express Rate Limit: Rate limiting prevents the same IP address from making too many requests that will help us prevent attacks like brute force. 

Required Dependency:

npm install express-rate-limit

Project Setup: Run the following sets of commands to create a folder and initialize the project.

mkdir test-project
cd test-project
npm init -y

Project Structure:

 

Example: Write the below code in the App.js file.

Javascript




// Express is node framework that helps
// in setting up the server and routing.
const express = require("express");
 
// The express-rate-limit is for
// limiting the incoming request.
const rateLimit = require("express-rate-limit");
 
// App variable store the express module.
const app = express();
 
// Creating a limiter by calling rateLimit function with options:
// max contains the maximum number of request and windowMs
// contains the time in millisecond so only max amount of
// request can be made in windowMS time.
const limiter = rateLimit({
    max: 200,
    windowMs: 60 * 60 * 1000,
    message: "Too many request from this IP"
});
 
// Add the limiter function to the express middleware
// so that every request coming from user passes
// through this middleware.
app.use(limiter);
 
// GET route to handle the request coming from user
app.get("/", (req, res) => {
    res.status(200).json({
        status: "success",
        message: "Hello from the GeeksforGeeks express server"
    });
});
 
// Server Setup
const port = 8000;
app.listen(port, () => {
    console.log(`app is running on port ${port}`);
});


Steps to run the application: Run the below command in the terminal:

node app.js

Output: We will see the following output on the terminal screen.

app is running on http://localhost:8000/
  • Output when a request doesn’t exceed the max limit of the rate limiter:

 

  • Output when a request exceeds the max limit of the rate limiter:

 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads