Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
40 prioritized NestJS best practices across architecture, DI, security, performance, testing, and microservices.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
rules/security-rate-limiting.md
1---2title: Implement Rate Limiting3impact: HIGH4impactDescription: Protects against abuse and ensures fair resource usage5tags: security, rate-limiting, throttler, protection6---78## Implement Rate Limiting910Use `@nestjs/throttler` to limit request rates per client. Apply different limits for different endpoints - stricter for auth endpoints, more relaxed for read operations. Consider using Redis for distributed rate limiting in clustered deployments.1112**Incorrect (no rate limiting on sensitive endpoints):**1314```typescript15// No rate limiting on sensitive endpoints16@Controller('auth')17export class AuthController {18@Post('login')19async login(@Body() dto: LoginDto): Promise<TokenResponse> {20// Attackers can brute-force credentials21return this.authService.login(dto);22}2324@Post('forgot-password')25async forgotPassword(@Body() dto: ForgotPasswordDto): Promise<void> {26// Can be abused to spam users with emails27return this.authService.sendResetEmail(dto.email);28}29}3031// Same limits for all endpoints32@UseGuards(ThrottlerGuard)33@Controller('api')34export class ApiController {35@Get('public-data')36async getPublic() {} // Should allow more requests3738@Post('process-payment')39async payment() {} // Should be more restrictive40}41```4243**Correct (configured throttler with endpoint-specific limits):**4445```typescript46// Configure throttler globally with multiple limits47import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler';4849@Module({50imports: [51ThrottlerModule.forRoot([52{53name: 'short',54ttl: 1000, // 1 second55limit: 3, // 3 requests per second56},57{58name: 'medium',59ttl: 10000, // 10 seconds60limit: 20, // 20 requests per 10 seconds61},62{63name: 'long',64ttl: 60000, // 1 minute65limit: 100, // 100 requests per minute66},67]),68],69providers: [70{71provide: APP_GUARD,72useClass: ThrottlerGuard,73},74],75})76export class AppModule {}7778// Override limits per endpoint79@Controller('auth')80export class AuthController {81@Post('login')82@Throttle({ short: { limit: 5, ttl: 60000 } }) // 5 attempts per minute83async login(@Body() dto: LoginDto): Promise<TokenResponse> {84return this.authService.login(dto);85}8687@Post('forgot-password')88@Throttle({ short: { limit: 3, ttl: 3600000 } }) // 3 per hour89async forgotPassword(@Body() dto: ForgotPasswordDto): Promise<void> {90return this.authService.sendResetEmail(dto.email);91}92}9394// Skip throttling for certain routes95@Controller('health')96export class HealthController {97@Get()98@SkipThrottle()99check(): string {100return 'OK';101}102}103104// Custom throttle per user type105@Injectable()106export class CustomThrottlerGuard extends ThrottlerGuard {107protected async getTracker(req: Request): Promise<string> {108// Use user ID if authenticated, IP otherwise109return req.user?.id || req.ip;110}111112protected async getLimit(context: ExecutionContext): Promise<number> {113const request = context.switchToHttp().getRequest();114115// Higher limits for authenticated users116if (request.user) {117return request.user.isPremium ? 1000 : 200;118}119120return 50; // Anonymous users121}122}123```124125Reference: [NestJS Throttler](https://docs.nestjs.com/security/rate-limiting)126