When I say being careful I mean do you rate limit calls to endpoints that you build, If not you may need to start doing so, this is to prevent excessive usage from potentially ill-configured or malicious integrators, and we'll be doing that with a library named express-rate-limit
.
You should simply install this library with npm i express-rate-limit
and now let's get to the main task.
I'll be using a controller i'll name greet
as an example, I don't want the same user to be greeted by the endpoint that is attached to this controller more than 3 times in 5 seconds.
This is my greet controller
export const greet = (req, res) => {
res.status(200).json({
status: true,
message: "Welcome"
})
}
Now to set the Limiter, you need to create an instance with the rateLimit
keyword, this rate limit will contain 3 properties which is the windowMs, max and message.
import { rateLimit } from "express-rate-limit";
const limiter = rateLimit({
windowMs: 5000,
max: 3,
message: "you can only be greeted 3 times in 5 seconds"
})
The windowMs
is the milliseconds that each call will be checked, we set ours to 5000 which is 5 seconds, the max
is the number of times the endpoint can be called and we set ours to 3 and the message is what will be returned if it exceeds the limit.
Now we are going to use the limiter we defined earlier.
import { Router } from "express";
const router = Router()
import { greet } from "../controllers/controller.js";
router.route("/greet").get(limiter, greet)
export default router
And when we test it we should get the message if it exceeds 3 calls
You've come this far, Thanks for reading.