I am trying to rate limit my API with @NestJs/throttler. I want to set two different limit caps:
Setting either one of these rate limits is explained in the docs and is pretty straight forwad. But, setting both limitations is not articulated in the docs.
How can I rate limit my API by both time intervals?
A bit late to the discussion, but here's my take on it.The following features are now available in NestJS version 10:
@Module({
imports: [
ThrottlerModule.forRoot([
{
name: 'short',
ttl: 1000,
limit: 3,
},
{
name: 'medium',
ttl: 10000,
limit: 20
},
{
name: 'long',
ttl: 60000,
limit: 100
}
]),
],
})
export class AppModule {}
You have the flexibility to specify when you want to modify or ignore these predefined options. For example:
// Override default configuration for Rate limiting and duration.
@Throttle({ default: { limit: 3, ttl: 60000 } })
@Get()
findAll() {
return "List users works with custom rate limiting.";
}
or
@SkipThrottle()
@Controller('users')
export class UsersController {
// Rate limiting is applied to this route.
@SkipThrottle({ default: false })
dontSkip() {
return 'List users work with Rate limiting.';
}
// This route will skip rate limiting.
doSkip() {
return 'List users work without Rate limiting.';
}
}
All code examples are taken directly from the official documentation.
As I told you on Discord, with @nestjs/throttler, this functionality currently doesn't exist. You can have one or the other, or you can override the global config to be more specific for one endpoint, but there's not currently a way to have two limits set up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With