Back to writing

How I make SQL injection harder to reach

SQL injection is one of those risks that can sound like a distant textbook example until a small shortcut turns request data into part of a database command. The useful lesson for me has been simple: data should stay data all the way to the database.

I do not think of this as one clever filter that catches bad strings. It is a boundary with several layers. The most important layer is how the query is made; the others make mistakes and abuse less likely to travel far.

When a value becomes part of the query

SQL injection happens when untrusted input is joined into SQL text and the database is allowed to interpret that input as syntax. A search term, route parameter, filter, login field or report option can all become the entry point if the application builds a query with string concatenation.

The problem is not that a person typed a quote or a special character. The problem is that the application gave their value a chance to change the meaning of the command. OWASP’s guidance makes the same distinction: the primary defence is a parameterised query, not trying to remove every suspicious character.

// The value changes the SQL text: do not do this.
const query = "SELECT id, email FROM users WHERE email = '" + email + "'";

// The SQL stays fixed; the driver binds the value separately.
const result = await pool.query(
  "SELECT id, email FROM users WHERE email = $1",
  [email],
);

Prepared statements and the parameter APIs provided by database drivers or a well-used ORM keep the command and its values separate. That is the part I do not compromise when a query needs to be written by hand.

Make the boundary narrow and clear

I still validate input, but for a different reason. It makes the contract explicit: which fields are accepted, which type each one has, how long it can be, and which values belong to a finite set. A page number is a positive integer; a UUID has a known shape; a status or sort direction should come from an allow-list.

In a NestJS application, I prefer to reject malformed request input at the route boundary with a validation pipe rather than let it drift into a service. A generic middleware can prepare a request, but it does not have the same handler-level knowledge of a DTO. The service can then focus on a valid application request and its business rules. This is close to the boundary approach I wrote about in Where TypeScript stops being enough.

Parameters cover values, not SQL identifiers. When a query genuinely needs a dynamic column, table, direction or operator, I do not pass arbitrary text through. I map a small public input to a fixed internal choice:

const sortColumns = {
  newest: "created_at DESC",
  name: "name ASC",
};

const orderBy = sortColumns[input.sort] ?? sortColumns.newest;
// orderBy is chosen by us, never supplied as SQL by the caller.

That distinction has saved me from treating all dynamic queries as equally safe. A bound email address and an arbitrary ORDER BY fragment are different problems.

Give a mistake less power

Input validation and parameter binding are the main path. I add other limits so that one mistake has a smaller blast radius. The application database account gets only the permissions its job needs. Read paths do not need schema-changing privileges; a reporting connection does not need the same access as a worker that changes data.

I also keep errors useful to the caller without returning raw database details. Detailed context belongs in protected logs with a request ID, not in a response that teaches someone about tables, columns or connection settings.

Rate limiting is useful here, but I try to name its role accurately. It can slow automated probing and reduce repeated pressure on a login, search or public API. It does not make a concatenated query safe and it is not a permanent “block this IP” button. Behind a proxy, the real client address must be configured correctly, and a distributed application needs shared rate-limit state rather than one counter per process. A WAF or edge control can add another layer for known bad traffic; neither replaces fixing the query.

Keep the safe path easy to review

The review question I come back to is small: can I point to the place where input becomes a value, rather than SQL? If the answer is unclear, I slow down. I look for raw query helpers, string interpolation, dynamic filters and the database role that will run the statement.

No layer makes a product invulnerable. But parameterised queries, narrow runtime validation, deliberate permissions, understandable errors and proportionate rate limits make SQL injection much harder to reach—and make the next change easier to review with confidence.

Working on something similar? Let's talk