API rate limit in NodeJS

In this article we will learn by example how to protect your application against slow performance and denial-of-service (DoS) attacks using rate-limit. APIs uses rate limit to ensure the safety of The API consumers and the API itself.

Why you need API rate limit?

  • Rate limit used to control user or entity that consumes API data to ensure API health and accessibility.

  • If API becomes overloaded, its performance suffers so using rate limit protect against this by rejecting requests that exceeds limit.

How rate limits work?

Rate limit act as a gatekeepers to control the amount of incoming requests or outgoing traffic. If we enforce rate limit to be come 100 requests per day if you exceed this number, error message appears in the response Too Many Requests. and you will blocked for amount of time from accessing these APIs.

Types of rate limit

  • User rate limit the most common type of rate limit, user rate limiting monitors a user’s API key,session cookie and IP address to watch the number of requests being made. If the number exceeds the limit user must wait until time frame resets.

  • Time-base rate limiting This based on region and time of day that user attempting to access a network. It exists to ensure that the strict rate limiting protocols apply only to certain periods of time,when traffic will be the highest.

  • Server rate limiting Depending on the size of the API, you may have multiple servers handling different types of requests. Server rate limiting is the process of enforcing different limits on a server-by-server basis.

Now :) time to apply by project

We will create a NodeJS application which contains POST login API with a hard coded credentials username=admin and password=admin we will protect this API from brute force attacks
you are allowed to use this API only three times per hour if you exceed this number you will blocked for one hour to access this API again.

Create a NodeJS project rateLimit and inside this project:

  • Run the following command to initiate NodeJS project npm init -y
  • Create a new file index.js which contains our express server with rate-limit code.
  • Install these following packages by running the following command npm i express express-rate-limit

express package to create http server node application,express-rate-limit it’s package for controlling API rate limit.

in index.js

const express = require("express");
const rateLimit = require("express-rate-limit");
const app = express();
app.use(express.json());
app.use(express.urlencoded({extended:false}));
const limiter = rateLimit({
    windowMs: 60 * 60 * 1000, // one hour
    max: 3 // limit each IP to 3 requests per windowMs
  });
//apply to all requests
app.use(limiter);
app.post("/login",(req,res,next)=>{
    let {username,password}=req.body;
    if(username==="admin"&&password==="admin"){
        return res.status(200).json({
            success:true,
            msg:"Login done successfully",
        })
    }else{
        return res.status(402).json({
            success:false,
            msg:"Sorry check your username and password"
        })
    }
});
app.listen(5000,()=>{
    console.log("server is running....")
})

Now run this project by typing the following command node index.js

Using postman add the following url http://localhost:5000/login and send username , password in form data to test this implementation and this logic.

This is the server in running mode

Login API with rate limit

Before exceeding number of API limit

Before exceeding rate-limit

After exceeding rate limit

Login API with rate limit

Subscribe to our Newsletter

Subscribe to tech-hour website to get all updates, new articles, new courses and projects. No spam ever. Unsubscribe at any time.