What is SQL injection, and how does using parameterized queries in Node.js prevent it?
Short answer
SQL injection occurs when untrusted user input is concatenated directly into a SQL query string, letting an attacker craft input that changes the query's actual meaning (like appending "OR 1=1" to bypass a WHERE clause, or appending a second malicious statement).
Advertisement
AModel answer
SQL injection occurs when untrusted user input is concatenated directly into a SQL query string, letting an attacker craft input that changes the query's actual meaning (like appending "OR 1=1" to bypass a WHERE clause, or appending a second malicious statement). Parameterized queries send the query structure and the user-supplied values separately to the database driver, which treats values strictly as data, never as executable SQL syntax, making injection through that input impossible regardless of what characters it contains.
// Vulnerable: user input concatenated directly into the query
const result = await pool.query(`SELECT * FROM users WHERE email = '${userInput}'`);
// Safe: parameterized query, value passed separately
const result = await pool.query('SELECT * FROM users WHERE email = $1', [userInput]);Real-world example
A security audit finds a login endpoint vulnerable to SQL injection through its unescaped, string-concatenated email lookup query; switching to a parameterized query with the email passed as a separate bound parameter eliminates the vulnerability entirely without changing the query's logic.
Likely follow-ups
- Why doesn't simply escaping quote characters manually provide the same guarantee as a properly parameterized query?
- Do NoSQL databases have an equivalent injection risk, and if so, what does it look like?
Related topics