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


πŸ† About me

I am Kumar Abhirup, a 17-year-old JavaScript Developer, founder of Beam.
To connect, you may DM me on twitter.

Love what I write? Subscribe to Kumar & Thoughts and stay updated about my content in general, lol.


If you like what I write on my blog and twitter,
I bet you gonna love the stuff I'll be mailing you!
I don't spam, really!