express-rate-limit – catching the message

0
120

Express Rate Limit is an npm package which provides a flexible rate limiting middleware.

Here is some code followed by an explanation and some gotchas 🙂

// What to do when our maximum request rate is breached
const limitReached = (req: express.Request, res: express.Response) => {
 log.warn({ ip: req.ip }, ‘Rate limiter triggered’)
 renderError(req, res) // Your function to render an error page
}
// Options for our rate limiter
const options: RateLimist.Options = {
 windowMs: 60000, // 1 minute
 max: 5,
 onLimitReached: limitReached, // called once when max is reached
 handler: limitReached, // called for each subsequent request once max is reached
}
const rateLimiter = RateLimit(options)
// Attach our rate limiter to an Express route
router.post(
 ‘/login’
 rateLimiter,
 loginPostHandler
)

LEAVE A REPLY

Please enter your comment!
Please enter your name here