GuardAPI Logo
GuardAPI

Fix API Rate Limit Exhaustion in NestJS

API Rate Limit Exhaustion (CWE-770) is a low-effort, high-impact vector for DoS and resource exhaustion. In the NestJS ecosystem, default controllers lack ingress control, allowing attackers to hammer expensive endpoints, drain database pools, or brute-force credentials. We mitigate this by implementing the ThrottlerGuard to enforce strict request quotas per IP address.

The Vulnerable Pattern

@Controller('auth')
export class AuthController {
  @Post('login')
  async login(@Body() dto: LoginDto) {
    // VULNERABILITY: No rate limiting. 
    // An attacker can send 10,000 requests/sec to brute-force passwords or crash the service.
    return this.authService.validateUser(dto);
  }
}

The Secure Implementation

The fix utilizes '@nestjs/throttler'. First, we register the ThrottlerModule globally to define baseline Time-To-Live (TTL) and request limits. We then apply the ThrottlerGuard either globally or via the @UseGuards decorator. For sensitive endpoints like '/login', we use the @Throttle decorator to override global settings with stricter constraints (e.g., 3 attempts per minute), effectively neutralizing automated brute-force and flooding attacks.

// 1. In AppModule: 
@Module({
  imports: [
    ThrottlerModule.forRoot([{
      ttl: 60000, // 1 minute
      limit: 5,   // max 5 requests per TTL
    }]),
  ],
  providers: [
    { provide: APP_GUARD, useClass: ThrottlerGuard },
  ],
})
export class AppModule {}

// 2. In AuthController: @Controller(‘auth’) export class AuthController { @Throttle({ default: { limit: 3, ttl: 60000 } }) @Post(‘login’) async login(@Body() dto: LoginDto) { // SECURE: ThrottlerGuard intercepts the request. // Exceeding limits returns a 429 Too Many Requests. return this.authService.validateUser(dto); } }

System Alert • ID: 1184
Target: NestJS API
Potential Vulnerability

Your NestJS API might be exposed to API Rate Limit Exhaustion

74% of NestJS apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.