What is Express-rate-limit in Node.js ?
Last Updated :
19 Apr, 2023
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
const express = require( "express" );
const rateLimit = require( "express-rate-limit" );
const app = express();
const limiter = rateLimit({
max: 200,
windowMs: 60 * 60 * 1000,
message: "Too many request from this IP"
});
app.use(limiter);
app.get( "/" , (req, res) => {
res.status(200).json({
status: "success" ,
message: "Hello from the GeeksforGeeks express server"
});
});
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:
Share your thoughts in the comments
Please Login to comment...