I am using pm2 (in cluster mode) and redis. I want route level rate limit configuration. The docs mention that redis property must be set if we have fastify-rate-limit on more than one server which I'm assuming applies to me as I'm using pm2.
Here's my fastify configuration:
const createClient = require('redis').createClient;
fastify.register(require('@fastify/rate-limit'), {
global : false,
redis: createClient("redis://redis_url")
})
An example route on which I'm testing the rate limit.
fastify.get('/hello',{
config: {
rateLimit: {
max: 1,
timeWindow: '1 minute'
}
}
}, async (req, reply) => {
reply.send("world")
})
However, it isn't working. I am able to hit the /hello
route more than once per minute.
How may I fix this?
Here is the same issue
You need to await
the plugin to make it works.
await fastify.register(require('@fastify/rate-limit'), {
global : false,
redis: createClient("redis://redis_url")
})
fastify.get('/hello', { ... })
This is needed due onRoute
hook and it is part of the fastify@4
breaking changes: https://www.fastify.io/docs/latest/Guides/Migration-Guide-V4/#synchronous-route-definitions-2954