Fix SQL Injection (Legacy & Modern) in Express
SQL Injection in Express is a rookie mistake that still sinks production ships. Whether you're using legacy callbacks or modern async/await, the root cause is the same: treating untrusted user input as executable code. If you're concatenating strings to build queries, you're handing the keys to your database to anyone with a browser. We stop this by enforcing a strict separation between the SQL command and the data context.
The Vulnerable Pattern
const express = require('express'); const mysql = require('mysql2'); const app = express(); const db = mysql.createConnection({ /* config */ });// HIGH SEVERITY: Classic SQLi via string interpolation app.get(‘/user’, (req, res) => { const userId = req.query.id; const query =
SELECT * FROM users WHERE id = '${userId}';db.query(query, (err, results) => { if (err) throw err; res.json(results); }); });
// Payload: /user?id=1’ OR ‘1’=‘1
The Secure Implementation
The fix is simple: Parameterized Queries. Instead of building a raw string, we use placeholders (? for MySQL, $1, $2 for PostgreSQL). When you pass the user input as a separate array, the database driver sends the query template and the data to the engine in two distinct phases. The database treats the input strictly as a literal value, not executable SQL syntax. This renders payloads like 'OR 1=1' harmless, as they are searched for as literal strings rather than logic gates. For modern stacks, always use 'pool.execute()' in mysql2 or the equivalent in 'pg' to leverage prepared statements at the protocol level.
const express = require('express'); const mysql = require('mysql2/promise'); const app = express();// SECURE: Using Parameterized Queries (Prepared Statements) app.get(‘/user’, async (req, res) => { try { const userId = req.query.id; const pool = await mysql.createPool({ /* config */ });
// The '?' is a placeholder; the driver handles escaping and typing const [rows] = await pool.execute( 'SELECT * FROM users WHERE id = ?', [userId] ); res.json(rows);
} catch (err) { res.status(500).send(‘Internal Server Error’); } });
Your Express API
might be exposed to SQL Injection (Legacy & Modern)
74% of Express apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
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.