How To Implement rate limiting in Node.js

Ahmed salman
5 min readJan 11, 2024

--

In this topic, our focus will be on a specific defense mechanism: Rate Limiting.

As we navigate through the intricate details, we will uncover how rate limiting becomes a formidable shield in the face of DDoS attacks. Understanding its nuances is essential for fortifying your Node.js applications against potential threats and ensuring a resilient and secure online presence.

What is rate limiting?

Rate limiting is a technique used to control the amount of incoming or outgoing traffic within a network. In this context, network refers to the line of communication between a client (e.g., a web browser) and our server (e.g., an API).

Thus, it is a technique that allows us to handle user requests based on some specified constraint such that:

  • There is better flow of data
  • There is a reduced risk of attack, i.e., improved security
  • The server is never overloaded
  • Users can only do as much as is allowed by the developer

For example, we might want to limit the number of requests an unsubscribed user can make to a public API to 1,000 requests per month. Once the user exceeds that number, we can ignore the request and throw an error indicating that the user has exceeded their limit.

In Node.js ,how we can implement rate limiting?

To implement rate limiting in a Node.js environment using Express, you can use the express-rate-limit middleware package. Here's an example of how you can set up rate limiting for your Express application:

const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();// Create a limiter object to define the rate limit rules
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
});
// Apply the limiter to all requests
app.use(limiter);
// Your routes and other middleware// Start the server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});

In the above example, we create a limiter object using express-rate-limit middleware. The windowMs option sets the time frame for which the requests are counted (in this case, 15 minutes), and the max option specifies the maximum number of requests allowed per windowMs time frame (in this case, 100 requests).

By using app.use(limiter) middleware, the rate limit rules will be applied to all requests in your Express application.

Remember to install the express-rate-limit package by running npm install express-rate-limit before running the above code.

This implementation will help control the number of requests a client can make within the specified time frame, mitigating the impact of DDoS attacks by limiting the rate at which requests are accepted.

To implement rate limiting for a specific endpoint in a Node.js environment using Express and the express-rate-limit middleware, you can modify your code as follows:

const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
// Create a limiter object to define the rate limit rules
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
});
// Apply the limiter to a specific endpoint
app.get('/api/endpoint', limiter, (req, res) => {
// Handle the endpoint logic here
});
// Your other routes and middleware
// Start the server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});

In the above example, we apply the limiter middleware specifically to the /api/endpoint route using the limiter object as a middleware function. This ensures that the rate limit rules will only be applied to that specific endpoint.

Remember to install the express-rate-limit package by running npm install express-rate-limit before running the above code.

This implementation will help control the number of requests a client can make to the /api/endpoint route within the specified time frame, mitigating the impact of DDoS attacks by limiting the rate at which requests are accepted.

To create middleware for rate limiting in a Node.js environment using Express and the express-rate-limit package, you can follow the steps below:

  1. Install the express-rate-limit package by running npm install express-rate-limit.
  2. Create a new JavaScript file, e.g., rateLimitMiddleware.js, and import the necessary modules:
const rateLimit = require('express-rate-limit');
  1. Define the rate limit rules for each endpoint by creating separate limiter objects. For example, you can define loginLimiter, registerLimiter, and homepageLimiter:
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 10, // limit each IP to 10 requests per windowMs
});
const registerLimiter = rateLimit({
windowMs: 24 * 60 * 60 * 1000, // 24 hours
max: 5, // limit each IP to 5 requests per windowMs
});
const homepageLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hour
max: 100, // limit each IP to 100 requests per windowMs
});
  1. Export the created limiters:
module.exports = {
loginLimiter,
registerLimiter,
homepageLimiter,
};
  1. In your main index.js or app.js file, import the rateLimitMiddleware.js file and use the defined limiters as middleware for the respective routes. For example:
const express = require('express');
const app = express();
const { loginLimiter, registerLimiter, homepageLimiter } = require('./rateLimitMiddleware');
app.post('/login', loginLimiter, (req, res) => {
// Handle login logic here
});
app.post('/register', registerLimiter, (req, res) => {
// Handle registration logic here
});
app.get('/', homepageLimiter, (req, res) => {
// Handle homepage logic here
});
// Your other routes and middleware
app.listen(3000, () => {
console.log('Server is running on port 3000');
});

By using the loginLimiter, registerLimiter, and homepageLimiter middleware functions, the rate limit rules will be applied to the corresponding routes.

Remember to install the express-rate-limit package by running npm install express-rate-limit before running the code.

This implementation will help control the number of requests a client can make to the specific endpoints within the specified time frames, mitigating the impact of DDoS attacks by limiting the rate at which requests are accepted.

At the end i hope you enjoy reading and don hesitate to follow me on LinkedIn and discuss in another topic

--

--

Ahmed salman
Ahmed salman

No responses yet