Express-rate-limit in Node.js: Return JSON Response on Rate Limit Errors
express-rate-limit
is a popular middleware for Express.js that helps protect your server by controlling how often a client can make requests. It commonly used to prevent abuse and reduce the risk of attacks like denial-of-service (DoS) and brute-force attempts.
By setting a limit on the number of requests allowed within a specific time window (e.g. 100 requests per hour),you can ensure fair usage of your API and maintain overall server performance. This makes it an essential tool for any production-grade Node.js application.
Built-In Rate Limiting
Control how many requests each IP address can make within a defined time window — helping you prevent abuse and overloading.
Fully Customizable
You can tailor everything from error messages to HTTP status codes, giving you full control over how rate limits are enforced and communicated.
Simple Integration
Designed to work seamlessly with Express.js, express-rate-limit
can be added to your API with just a few lines of code.
Highly Flexible Configuration
Apply different rate limits to specific routes or HTTP methods, making it ideal for APIs with varying access needs.
Create a folder structure and navigate for the project.
mkdir express-app
cd express-app
Initialize the NodeJs project inside the express-app folder.
npm init -y
Install the required dependencies by the following command:
npm install express-rate-limit
src/app.js or app.js
// app.js
const express = require("express");
const rateLimit = require("express-rate-limit");
const app = express();
const limiter = rateLimit({
max: 200,
windowMs: 60 * 60 * 1000,
handler: (req, res) => {
res.status(429).json({
status: false,
message: "Too many requests from this IP, please try again later."
});
return apiResponse(res, 429, "Too many requests from this IP, please try again later.");
}
});
app.use(limiter);
app.get("/", (req, res) => {
res.status(200).json({
status: true,
message: "Learning Node js"
});
});
const port = 3000;
app.listen(port, () => {
console.log(`app is running on port ${port}`);
});
Did you know you can clap multiple times? 🥰 If this story added value to your day, please show your support by giving it a 👏 clap, sharing it with others, or even sponsoring my work. Your appreciation means the world to me!