I was wondering if we can achieve Rate Limiting of IP and Request Body (same some username) separately (Either one if fulfilled should give me Error 429) for same controller function (Route).
Tried Using following packages –
"nestjs-throttler-storage-redis": "^0.3.0"
"@nestjs/throttler": "^4.0.0",
"ioredis": "^5.3.2"
app.module.ts –
ThrottlerModule.forRoot({
ttl: process.env.IP_VELOCITY_TTL as unknown as number, // 24 hours in seconds
limit: process.env.IP_VELOCITY_COUNT as unknown as number, // X number requests per ttl per key (IP address in this case)
storage: new ThrottlerStorageRedisService(new Redis()),
}),
In Respective Module.ts –
{
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
controller.ts –
@Throttle(3, 60 * 60)
But this is not sufficient as this is blocking all the requests post 3 times!
Can anybody suggest me to achieve this in Right way ?
2
Answers
The trick was to overwrite
ThrottlerGuard
Class like below -You’ll need to create your own guard that
extends ThrottlerGuard
and overrides thegetTracker
method so that it returns thisip
andreq.body.username
combo. Something likeThen, instead of
useClass: ThrottlerGuard
you can useuseClass: ThrottleIpBodyGuard