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.
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 π
β What is πΉedis?
— Kumar Abhirup (@kumar_abhirup) January 15, 2021
I started using it many months ago, when implementing PubSub, but it is used for many more things.
It... π
- is an In-memory data structure store
- is Used as a database, or cache store
- Provides simple data structures such as strings & arrays
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.
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.
Use the middleware!
If you read the code comments, you will get a fair idea of how things work!
For more details and complexities, take a look at the express-limiter
documentation. It's very neat.