JavaScript

Rate limiting in Express

Hello. In this tutorial, we will understand how to implement a simple rate-limiting in a simple nodejs application using express.

1. Introduction

With the increase in digital security, there are many reasons for protecting the api’s such as saving costs in the cloud or restricting the api usage. The express-rate-limit is a simple library that helps to quickly build a rate-limiting in nodejs. You can read more about this package here.

1.1 Setting up Node.js

To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.

Fig. 1: Verifying node and npm installation

2. Rate limiting in Express

To set up the application, we will need to navigate to a path where our project will reside and I will be using Visual Studio Code as my preferred IDE.

Let us take a look at the code structure.

Fig. 2: Application code structure

2.1 Setting up dependencies

Navigate to the project directory and run npm init -y to create a package.json file. This file holds the metadata relevant to the project and is used for managing the project dependencies, script, version, etc. Replace the generated file with the code given below –

package.json

{
  "name": "rate-limiter",
  "version": "1.0.0",
  "description": "Understanding rate limiting in node and express",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "node",
    "express",
    "rate-limiter",
    "express-rate-limit",
    "request-ip"
  ],
  "author": "geeks",
  "license": "MIT",
  "dependencies": {
    "express": "^4.17.3",
    "express-rate-limit": "^6.3.0",
    "request-ip": "^2.1.3"
  },
  "devDependencies": {
    "nodemon": "^2.0.15"
  }
}

2.2 Setting up dummy data

Create a file named – todos.js responsible to return the mock data to the client. The below is omitted for brevity but you can download the entire file from the Downloads section.

todos.js

const todos = [
  {
    userId: 1,
    id: 1,
    title: "delectus aut autem",
    completed: false
  },
  {
    userId: 1,
    id: 2,
    title: "quis ut nam facilis et officia qui",
    completed: false
  },
  {
    userId: 1,
    id: 3,
    title: "fugiat veniam minus",
    completed: false
  },
  {
    userId: 1,
    id: 4,
    title: "et porro tempora",
    completed: true
  }

  // omitted for brevity
];

module.exports = todos;

2.3 Setting up the implementation file

This file describes the main implementation (i.e. the driver code). Each request api response for the below endpoint will consist of the `RateLimit` header that will determine the total api calls and the chances left. Once the request count is breached an error message will be thrown to the client.

index.js

const express = require("express");
const limiter = require("express-rate-limit");
const ip = require("request-ip");

const todos = require("./todos");

// setting up express server
const app = express();
app.use(ip.mw());

const apiLimiter = limiter({
  windowMs: 60 * 1000, // 1 minute
  max: 5, // limit each ip to 5 requests per window
  legacyHeaders: false, // Return rate limit info in the `RateLimit-*` headers
  standardHeaders: true, // Disable the `X-RateLimit-*` headers
  statusCode: 429,
  message: {
    error:
      "Too many accounts created from this IP, please try again after a few minutes."
  },
  keyGenerator: (req, res) => req.clientIp // IP address from requestIp.mw(), as opposed to req.ip
});

// apply rate limiter at endpoints

// http get - http://localhost:3005/todos
app.get("/todos", apiLimiter, (req, res) => {
  res.send({
    status: "ok",
    todos: todos
  });
});

// driver code
const SERVER_PORT = 3005;
app.listen(SERVER_PORT, () => {
  console.log(`Service endpoint = http://localhost:${SERVER_PORT}`);
});

3. Run the Application

To run the application navigate to the project directory and enter the following command as shown below in the terminal.

Run command

$ npm run dev

If everything goes well the application will be started successfully at the service endpoint – http://localhost:3005

4. Application endpoints

The application exposes the below endpoints that you can explore around the application with the help of the postman tool. You can also download the postman collection from the Downloads section and import it into the tool for an easy setup.

Application endpoints

// application endpoint

// http get - http://localhost:3005/todos

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

5. Summary

In this tutorial, we saw the implementation of rate-limiting an api. You can download the source code from the Downloads section.

6. Download the Project

This was a tutorial to secure the restful apis in a nodejs and express application.

Download
You can download the full source code of this example here: Rate limiting in Express

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button