How to integrate Express-rate-limit in Node.js ?
Last Updated :
01 Apr, 2021
Rate limiting prevents the same IP from making too many requests that will help us prevent attacks like brute force. The express-rate-limit is the npm package for limiting the request from the user.
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
Module Installation: Run the following command to install the express and express-rate-limit module:
npm i express express-rate-limit
Project directory: The project structure will look like this:
app.js
const express = require( "express" );
const rateLimit = require( "express-rate-limit" );
const app = express();
const limiter = rateLimit({
max: 100,
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 express server"
});
});
const port = 8000;
app.listen(port, () => {
console.log(`app is running on port ${port}`);
});
|
Run app.js file using the following command:
node app.js
Output: We will see the following output on the terminal screen.
app is running on http://localhost:8000/
The header of the response object has 2 fields X-RateLimit-Limit and X-RateLimit-Remaining which stores the max and remaining request from the user:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...