API Rate Limiter in Node.js
API Rate Limiting is an essential mechanism for controlling and limiting the number of requests an API can receive from a client within a specific time frame. It helps prevent abuse, protects server resources, and ensures fair usage for all users. In this article, we will explore how to implement an API Rate Limiter in Node.js using the express-rate-limit middleware.
Prerequisites :
To follow along with this tutorial, you should have a basic understanding of Node.js, npm (Node Package Manager), and have a Node.js project set up with Express.
Setting Up the Project :
- Create a new directory for your project and navigate to it in the terminal.
- Initialize a new Node.js project by running the command : npm init -y
- Install the required dependencies : npm install express express-rate-limit
Implementing the API Rate Limiter :
- Open your main application file (e.g., index.js) and import the necessary dependencies :
const express = require('express');
const rateLimit = require('express-rate-limit');
- Create an instance of the rate limiter middleware and configure it :
const limiter = rateLimit({
windowMs: 60 * 1000, // 1 minute
max: 100, // Maximum number of requests
message: 'Too many requests from this IP, please try again later.',
});
Here, we set the windowMs property to define the time window (in milliseconds) within which the maximum number of requests ( max ) is allowed. In this example, we allow a maximum of 100 requests per minute. If a client exceeds this limit, they will receive the error message specified in the message property.
- Apply the rate limiter middleware to the desired routes in your application :
const app = express();
// Apply the rate limiter middleware to the specific route(s)
app.use('/api', limiter);
// Define your API routes below
app.get('/api/users', (req, res) => {
// Handle the API logic for retrieving users
});
// Start the server
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
In this example, we apply the rate limiter middleware to the /api route. You can modify the route path to match your specific API endpoints. Requests made to these routes will be subjected to the rate limiting rules defined in the limiter middleware.
Here, we set the windowMs property to define the time window (in milliseconds) within which the maximum number of requests ( max ) is allowed. In this example, we allow a maximum of 100 requests per minute. If a client exceeds this limit, they will receive the error message specified in the message property.
In this example, we apply the rate limiter middleware to the /api route. You can modify the route path to match your specific API endpoints. Requests made to these routes will be subjected to the rate limiting rules defined in the limiter middleware.