GuardAPI Logo
GuardAPI

Fix SQL Injection (Legacy & Modern) in NestJS

SQL Injection in NestJS isn't dead; it just evolved. While TypeORM and Sequelize offer abstraction layers, developers frequently bypass them with 'raw' escape hatches for complex logic, re-introducing classic string-concatenation sinks. If you are using template literals inside a .query() or getRawMany() call, you are providing an open door for RCE or data exfiltration via UNION-based or Time-based blind payloads.

The Vulnerable Pattern

@Injectable()
export class UserService {
  constructor(@InjectRepository(User) private repo: Repository) {}

async findByLegacy(id: string) { // DANGER: Raw string interpolation bypasses the driver’s sanitization return await this.repo.query(SELECT * FROM users WHERE id = ${id}); }

async searchDynamic(filter: string) { // DANGER: QueryBuilder is safe, but not if you manually concat strings into .where() return await this.repo.createQueryBuilder(‘user’) .where(“user.name LIKE ’%” + filter + ”%’”) .getMany(); } }

The Secure Implementation

The vulnerability lies in the confusion between SQL commands and data. String concatenation merges them, allowing an attacker to manipulate the Abstract Syntax Tree (AST) of the query. By using parameterized queries ($1) or QueryBuilder placeholders (:name), the database driver sends the SQL template and the user data in separate packets. The DB engine then treats the input strictly as a literal value, never as executable code. In NestJS, always audit .query(), .getRawMany(), and any QueryBuilder method where input isn't strictly passed as a secondary parameter object.

@Injectable()
export class UserService {
  constructor(@InjectRepository(User) private repo: Repository) {}

async findByModern(id: string) { // SECURE: Use parameterized arrays in raw queries return await this.repo.query(‘SELECT * FROM users WHERE id = $1’, [id]); }

async searchSecure(filter: string) { // SECURE: Use QueryBuilder with named parameters return await this.repo.createQueryBuilder(‘user’) .where(‘user.name LIKE :name’, { name: %${filter}% }) .getMany(); } }

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

Your NestJS API might be exposed to SQL Injection (Legacy & Modern)

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.