๐ฅ๐ฎ๐๐ฒ ๐๐ถ๐บ๐ถ๐๐ถ๐ป๐ด ๐๐ป ๐ก๐ฒ๐๐๐๐ฆ ๐ช๐ถ๐๐ต ๐๐ฟ๐ฎ๐ฝ๐ต๐ค๐ Rate limiting protects your APIs from brute-force attacks and abusive traffic. When using GraphQL in NestJS, all requests go through a single endpoint. This makes it hard for standard HTTP route-based middleware to differentiate between operations.
To implement rate limiting in a NestJS GraphQL application, you can use the @nestjs/throttler package. Here's how:
- Install the @nestjs/throttler package using npm install @nestjs/throttler
- Create a custom guard to override the getRequestResponse method
- Import the ThrottlerModule into your main application module and register your custom guard globally
You can define a default limit for all endpoints. For example, 1000 requests per 15 minutes. You can also use the @Throttle() decorator to override the default limits on specific resolvers.
Key benefits of this setup:
- Global protection against abuse
- Context awareness for GraphQL requests
- Granular control over sensitive operations like authentication
Source: https://dev.to/nikeshdahal/rate-limiting-in-nestjs-with-graphql-gc