close
close

How to calculate the limit of express applications

Rate limiting is a strategy that you can use to control traffic on a network. Limits the number of requests a user can make within a specified time period.

There are several rate limiting algorithms, each with its own trade-offs. A simple and popular method is to track the IP addresses of the requests and check how much time passes between requests. The system can then reject a request if your IP address exceeds the number of requests allowed by the limit.

This rate limiting approach is easy to build into a NodeJS-Express application, with just a few steps.

Step 1: Setting up a development environment

First, you’ll need to create and initialize an Express application.

Start by creating a project directory by running:

mkdir express-app

Then get into that directory by running:

cd express-app

Next, initialize npm, the node package manager, and create a package.json file in your app by running:

npm init -y

the -Y flag will create your package.json file with all default settings.

Next, you’ll need to install some dependencies. The dependencies required for this tutorial are:

  • ExpressJS – ExpressJS is a NodeJS framework that provides a robust set of features for web and mobile applications. Simplify the process of building backend applications with NodeJS.
  • Express Rate Limit: Express rate limit is a rate limiting middleware for ExpressJS. Limit repeated requests to public APIs and/or endpoints, such as password resets, user logins, etc.

Install the required dependencies by running:

npm install express express-rate-limit

Step 2: Create an Express app

You will need to create a basic Express server that listens for requests made to your application.

First, create a index.js file in the root directory of your project. This will be the input file for your application.

Then add the following code to your index.js proceedings:


const express = require("express");
const app = express();
const port = process.env.PORT || 3000

app.listen(port, () => {
console.log(`App running on port ${port}`);
});

This code matters Fast and create an Express application by calling express() and storing its return value in the app variable. Then listen for traffic on the port 3000 calling the listen method in the app object.

Step 3: Create Route Controllers

Next, create some route controllers that you can implement the rate-limiting solution on.

First, create a folder, paths, in the root directory of your project by running:

mkdir routes

create a file, routes.jsinside your routes folder and add the following code:

const express = require("express");
const router = express.Router();

router.get("/", (req, res) => {
res.send({ message: "Hello, this is a GET request" });
});

router.post("/add-demo", (req, res) => {
res.status(201).send({ message: "Resource created successfully" });
});

router.put("/update-demo", (req, res) => {
res.status(201).send({ message: "Resource updated sucessfully" });
});

module.exports = router;

This code matters Fastcall to router method in Fastand stores the value in a variable, router. the router The method allows you to create modular and mountable route handlers. You can create route handlers for a GET application “/“, a MAIL application “/add-demo“, and a PUT application “/update-demo”. Finally, export the router variable.

Then import the router variable in your index.js proceedings:


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

Then use it as a middleware in your index.js file:


app.use(routes);

Be sure to place the code block above before the app.listen to call.

Step 4: Implement Rate Limiting

First, create a “middleware” in the root directory of your project by running:

mkdir middleware

Then create a file called “rate-limiter.js” inside the middleware directory. Add the following code to this file:


const rateLimiter = require("express-rate-limit");

const limiter = rateLimiter({
max: 5,
windowMS: 10000,
message: "You can't make any more requests at the moment. Try again later",
});

module.exports = limiter

the rate limiter The function takes a configuration object with the conditions to limit the number of requests.

The properties in the configuration object above are:

  • maximum: This property must always be a number or a function that returns a number. Represents the maximum number of requests that a user can make within a specified time period. If this property is not set on the configuration object, the default value is 5.
  • windowsMS: This property must always be a number. Represents the length of time in which multiple requests are allowed on milliseconds. If this property is not set on the configuration object, the default value is 60000 milliseconds (one minute).
  • message: This property can be a string, a JSON object, or any other value supported by Express’s response.send method. If this property is not set on the configuration object, the default value is “Too many requests. Please try again later.”


The function will then check for repeated requests to your app. If a user exceeds the limit (maximum5) within the deadline (MS window, 10s), will block the request. It will also throw a “Too Many Requests” error with a status code of 429.

Finally, import the limiter function into your index.js and apply it as a global middleware in your application. Do this by placing app.use(limiter) above the routes middleware. This applies the rate limiting solution to all routes in your application.

app.use(limiter);

Specific speed limitation routes

You can also apply speed limiting to specific routes. You can configure them separately to reject requests made in a different time period, display a different message, etc.

For example, suppose you are implementing a user login route in your application. You may need to add rate limiting settings for the login route that differ from the settings used by the other routes.

First, you will have to remove limiter as an application level middleware and apply it because there is no middleware filter system built into ExpressJS. So even if you add a specific rate limiting solution to a route, the global middleware will still run on that route.

Next, create a new rate limit setting on your rate-limiter.js file and export it.

const signInLimiter = rateLimiter({
max: 3,
windowMS: 10000,
message: "Too many sign-in attempts. Try again later."
})

module.exports = {
limiter,
signInLimiter
}

the signInLimiter configuration object has a different number of maximum requests and an error message different from the general rate limiter.

Lastly, update your router.js file with the code block below:


const express = require("express");
const router = express.Router();
const {limiter, signInLimiter} = require("../middleware/rate-limiter")

router.get("/sign-in", signInLimiter, (req, res, next) => {
res.send({ message: "Hello, this is a GET request" });
});

router.use(limiter)

router.post("/post", (req, res) => {
res.status(201).send({ message: "Resource created successfully" });
});

router.put("/put", (req, res) => {
res.status(201).send({ message: "Resource updated sucessfully" });
});

module.exports = router;

In the code block above, you imported limiter Y signInLimiter. then you applied signInLimiter as a speed limiter specific to the “/log in” route.

Finally, placing router.use (limiter) on the rest of the routes, it applied limiter as a speed limiter for the rest of the routes.

The importance of speed limiting

Rate limiting reduces the strain on your web server by preventing it from having to process too many requests at once. It reduces bot activity, protects you from denial of service (DoS) attacks, and prevents brute force attacks.

Leave a Comment