Fix SQL Injection (Legacy & Modern) in AdonisJS
AdonisJS's Lucid ORM provides a strong defense-in-depth, but developers frequently bypass these protections by using raw queries for complex logic. In both legacy (v4) and modern (v5/v6) versions, the primary SQL injection vector is string interpolation within raw query methods. To secure the application, you must treat all user-supplied data as untrusted and enforce parameterization at the driver level.
The Vulnerable Pattern
// VULNERABLE: String interpolation in raw queries allows query hijacking const username = request.input('username'); const user = await Database.raw(`SELECT * FROM users WHERE username = '${username}'`);
// VULNERABLE: Legacy Lucid ‘whereRaw’ with template literals const results = await Database.from(‘posts’).whereRaw(title LIKE '%${request.input('search')}%');
The Secure Implementation
The vulnerability exists because string interpolation merges executable SQL code with data, allowing an attacker to inject malicious payloads (e.g., "' OR '1'='1") that alter the query logic. By utilizing '?' placeholders or the Fluent Query Builder, the database driver sends the SQL command and the data in separate packets. This ensures the database engine treats the input strictly as a literal value, effectively neutralizing any embedded SQL commands.
// SECURE: Using Fluent Query Builder (Automatic Parameterization) const username = request.input('username'); const user = await Database.from('users').where('username', username).first();// SECURE: Parameterized Raw Queries using placeholders (?) const userRaw = await Database.raw(‘SELECT * FROM users WHERE username = ?’, [username]);
// SECURE: Modern whereRaw with value binding const results = await Database.from(‘posts’).whereRaw(‘title LIKE ?’, [%${request.input('search')}%]);
Protect your AdonisJS API
Don't rely on manual checks. GuardAPI's Gemini 3 Pro engine detects SQL Injection (Legacy & Modern) and logic flaws in seconds.
Run Automated AuditVerified 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.