How to Rate Limit your Express API EndpointsAvatar

How to Rate Limit your Express API Endpoints



The featured image of this article is from Unsplash.

This won't be a long tutorial, but a small, very self explanatory code snippet, that you can easily read and learn by yourself.

Rate Limit your Express API Endpoints

๐Ÿšถโ€โ™‚๏ธ Quick Walkthrough

Step 1

Install express, express-limiter and also install Redis to set up a Redis Client. Redis Client will be created using ioredis.

Why do you need Redis? Here's why ๐Ÿ‘‡


Step 2

Import express and create an express app instance. Now, create a limiter instance. We will use express-limiter for this.

const limiter = expressLimiter(app, redisClient)

Make sure you spawned a Redis Client, read how to do that here.

This limiter instance will now help us create a limiterForApi to define Rate Limit rules to use it for your routes as a middleware.

Step 3

Define the rules. Create the middleware.

const limiterForApi = limiter({
  onRateLimited(_req, res) {
    return res.status(429).send({ error: { message: "Rate limit exceeded" } })
  },

  total: 200,
  expire: 1000 * 60 * 60,
  lookup: ["headers.data.user._id"]
})

The above middleware sets the API rate limit at 200 requests per hour per User ID. If you want to rate limit per IP Address, you can add the IP Address header name in the lookup array.

Step 4

Use the middleware!

Here's the complete code snippet

If you read the code comments, you will get a fair idea of how things work!

Rate Limit your Express API Endpoints

For more details and complexities, take a look at the express-limiter documentation. It's very neat.


Discuss on Twitter ๏น’ Edit this article ๏น’ Connect with me on Discord


Subscribe to Kumar's Newsletter