GuardAPI Logo
GuardAPI

Fix NoSQL Injection in NestJS

NoSQL Injection in NestJS occurs when untrusted input is passed directly into Mongoose or TypeORM query filters without validation. Attackers leverage MongoDB operators like $ne, $gt, or $where to bypass authentication or dump databases. If you're using 'any' types in your controllers, you're likely pwned.

The Vulnerable Pattern

@Post('auth')
async login(@Body() body: any) {
  // VULNERABLE: Attacker sends { "user": { "$ne": "" }, "pass": { "$ne": "" } }
  // Mongoose executes: db.users.find({ user: { $ne: '' }, pass: { $ne: '' } })
  const user = await this.userModel.findOne({ 
    username: body.user, 
    password: body.password 
  });
  return user;
}

The Secure Implementation

The fix involves two layers of defense. First, define strict Data Transfer Objects (DTOs) using 'class-validator'. By applying @IsString(), you prevent attackers from passing an object containing NoSQL operators. Second, configure the NestJS ValidationPipe with 'whitelist: true' to strip any properties not explicitly defined in the DTO. This ensures that even if an attacker attempts to inject a nested object, the validator will either reject the request or cast the input to a literal string, rendering the NoSQL operator harmless.

import { IsString, IsNotEmpty } from 'class-validator';

export class LoginDto { @IsString() @IsNotEmpty() username!: string; @IsString() @IsNotEmpty() password!: string; }

// In main.ts: app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }));

@Post(‘auth’) async login(@Body() loginDto: LoginDto) { // SECURE: ValidationPipe enforces strings. Operator objects are rejected. const user = await this.userModel.findOne({ username: loginDto.username, password: loginDto.password }).lean(); return user; }

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

Your NestJS API might be exposed to NoSQL Injection

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.