Sometimes, we want to prevent SQL injection in Node.js.
In this article, we’ll look at how to prevent SQL injection in Node.js.
How to prevent SQL injection in Node.js?
To prevent SQL injection in Node.js, we should be using parameterized queries.
For instance, we write
const userId = 5;
const query = connection.query('SELECT * FROM users WHERE id = ?', [userId], (err, results) => {
//...
});
to call the connection.query
method from the node-mysql-native
package.
We call it with a parameterized select statement.
We have id = ?
and pass in an array with the array of values to replace each ?
in the SQL string to escape the values we pass in to replace the ?
.
Therefore, userId
is escaped before it’s interpolated and the query is run.
Then from the results
parameter of the callback, we get the query result.
Conclusion
To prevent SQL injection in Node.js, we should be using parameterized queries.