GuardAPI Logo
GuardAPI

Fix Unrestricted Resource Consumption in NestJS

Unrestricted resource consumption in NestJS is a low-effort DOS vector. Default configurations often lack request rate limits and allow massive payloads, letting an attacker exhaust CPU cycles or heap memory with minimal effort. To harden the service, you must implement global rate limiting and enforce strict body size constraints at the middleware level.

The Vulnerable Pattern

@Controller('analytics')
export class AnalyticsController {
  @Post('report')
  async processReport(@Body() largeData: any) {
    // VULNERABILITY: No rate limiting and no body size restriction.
    // An attacker can send 100MB JSON payloads 1000 times per second,
    // crashing the Node.js process via heap exhaustion.
    return this.analyticsService.compute(largeData);
  }
}

The Secure Implementation

The fix involves two layers of defense. First, we use 'ThrottlerModule' to implement a ThrottlerGuard, which prevents request flooding by tracking IP addresses and limiting hits within a Time-To-Live (TTL) window. Second, we configure the underlying Express/Fastify adapter via 'app.use(json({ limit: '10kb' }))' to reject oversized payloads before they are even parsed. This prevents V8 from attempting to allocate massive strings in memory, mitigating 'Payload Too Large' (413) attacks that lead to process crashes.

// main.ts
import { NestFactory } from '@nestjs/core';
import { json } from 'express';

async function bootstrap() { const app = await NestFactory.create(AppModule); // FIX: Enforce payload limits at the entry point app.use(json({ limit: ‘10kb’ })); await app.listen(3000); }

// app.module.ts @Module({ imports: [ ThrottlerModule.forRoot([{ ttl: 60000, limit: 10, // FIX: Max 10 requests per minute per IP }]), ], }) export class AppModule {}

// analytics.controller.ts @Controller(‘analytics’) export class AnalyticsController { @UseGuards(ThrottlerGuard) @Post(‘report’) async processReport(@Body() validatedData: ReportDto) { return this.analyticsService.compute(validatedData); } }

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

Your NestJS API might be exposed to Unrestricted Resource Consumption

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.