How to prevent SQL injection in Node.js and Python
Updated 8 November 2026 · 6 min read
SQL injection is decades old and still near the top of the OWASP Top 10. It happens when user input becomes part of the SQL text itself. AI coding assistants make it easy to slip in, because template strings look clean and work in testing.
How it happens
// Looks fine, isn't
db.query(`SELECT * FROM users WHERE email = '${req.body.email}'`);
If someone sends ' OR '1'='1 as the email, the query becomes ... WHERE email = '' OR '1'='1' and returns every user. With a little more effort an attacker can read other tables or change data.
The fix is always the same idea: send the SQL and the values separately, so the database never treats a value as code. That is a parameterized query.
Node.js
node-postgres (pg):
const { rows } = await pool.query("SELECT * FROM users WHERE email = $1", [req.body.email]);
mysql2:
const [rows] = await conn.execute("SELECT * FROM users WHERE email = ?", [req.body.email]);
Prisma: normal queries are safe by default.
const user = await prisma.user.findUnique({ where: { email: req.body.email } });
For raw SQL in Prisma, use the tagged template prisma.$queryRaw, which parameterizes values. Avoid $queryRawUnsafe with user input.
const users = await prisma.$queryRaw`SELECT * FROM users WHERE email = ${req.body.email}`;
Python
psycopg (PostgreSQL):
cur.execute("SELECT * FROM users WHERE email = %s", (email,))
Note the comma: the values go in a tuple as the second argument. Writing "... %s" % email builds the string yourself and is injectable again.
sqlite3:
cur.execute("SELECT * FROM users WHERE email = ?", (email,))
SQLAlchemy:
from sqlalchemy import select, text
session.execute(select(User).where(User.email == email))
session.execute(text("SELECT * FROM users WHERE email = :email"), {"email": email})
Avoid f-strings inside text(...).
Table names, column names and sort order
Parameters only work for values. You can’t pass a table name, a column name or ASC/DESC as a parameter. If those depend on user input, map them from a fixed list:
const SORT = { name: "name", created: "created_at" } as const;
const col = SORT[req.query.sort as keyof typeof SORT] ?? "created_at";
const dir = req.query.dir === "asc" ? "ASC" : "DESC";
await pool.query(`SELECT * FROM users ORDER BY ${col} ${dir} LIMIT $1`, [limit]);
Here the interpolated parts can only ever be one of your own strings.
Fixed text from your own code
Not every interpolated query is dangerous. This is safe, because HAS_SITE is a constant written in the code:
HAS_SITE = "COALESCE(domain, '') != ''"
cur.execute(f"SELECT COUNT(*) FROM companies WHERE {HAS_SITE}")
It stays safe only as long as nobody later changes HAS_SITE to include user input. A comment saying so helps the next person.
Other layers that help
- Give the app’s database user only the permissions it needs, so an injection can’t drop tables.
- Validate input shape early (an email looks like an email, an id is a number).
- Log and alert on database errors, which often show up first during an attack.
These reduce the damage. They don’t replace parameterized queries.
What Lintsure checks
The SQL query built from strings rule flags SQL built with template strings, f-strings, +, % or .format(). It marks a Gap when the inserted value looks like request input (req, params, body, query and similar) and Partial when it may be fixed text from your own code, so you can confirm. It relates to SOC 2 CC7.1, ISO 27001 A.8.28 and GDPR Art. 32.
Check your own code
Lintsure runs these checks on your machine and never uploads your code.
npx lintsure scanThis guide is our own reading of public texts, written for software teams. It is not legal advice and it doesn't cover your whole obligation, only the parts code can show. Ask a qualified person before any audit or decision. Disclaimer