How to integrate Express-rate-limit in Node.js ?
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
// 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: 100, 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 express server" }); }); // Server Setup 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/
Output when a request doesn’t exceed the max limit of rate limiter:
Output when a request exceeds the max limit of the rate limiter:
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: