CodePark/ questions / Injection attacks
START PRACTICINGPRACTICE
Backend question · Auth & security › Injection attacks

What is the correct fix for this query?

const sql = `SELECT * FROM users WHERE email = '${req.body.email}'`;
const rows = await db.query(sql);
Use a parameterised query: db.query("SELECT * FROM users WHERE email = $1", [req.body.email])

Use a parameterised query. The driver sends the SQL text and the values separately. So the database always treats the input as data, and the input can never change the query's structure.

"Escape single quotes with
replace(/'/g, "''")" is the tempting wrong option. Hand-made escaping is fragile. It can break across different databases, character encodings, and contexts like number fields. OWASP strongly advises against relying on it.