SQL injection in a Next.js API route
SQL injection happens when user input is pasted straight into a SQL string. The attacker sends input that changes what the query means, so it is no longer "find this user" but "find every user" or "log me in as admin".
AI coding tools often generate string-built queries because they are the shortest thing that works, which is exactly how this bug gets shipped.
Why it matters
On a login endpoint, an input like ' OR 1=1-- can make the query return the first user (often an admin), bypassing the password entirely. On other endpoints the same trick can read every table, or with stacked queries, delete data. One un-parameterised query is enough to lose the whole database.
What does a vulnerable query look like?
If you see user input concatenated into the SQL text, it is vulnerable:
- Bad: db.query("select * from users where email = '" + email + "'")
- Good: db.query("select * from users where email = $1", [email])
- The rule: values always go in as parameters, never glued into the string.
Use parameterised queries (or your ORM/query builder) so user input is always sent as a value, never as part of the SQL text. This closes the whole class of bug, not just one input.
- Find every query that concatenates or interpolates user input into SQL.
- Rewrite them as parameterised queries with placeholders ($1, ?, or named params).
- Prefer your ORM or query builder, which parameterises by default.
- Re-scan to confirm the endpoints are no longer injectable.
// Bad - the input becomes part of the query
const { rows } = await db.query(
"select * from users where email = '" + email + "'"
);
// Good - the input is passed as a parameter
const { rows } = await db.query(
'select * from users where email = $1',
[email]
);
FAQ
Does using Supabase or an ORM protect me automatically?
Mostly yes. The Supabase client and ORMs like Prisma and Drizzle parameterise inputs for you. You reintroduce the risk the moment you drop to raw SQL and build the string by hand.
Is escaping the input enough?
No. Manual escaping is easy to get wrong and easy to forget. Parameterised queries are the reliable fix because the database, not your string handling, keeps data and code separate.