Categories
JavaScript Answers

How to prevent SQL injection in Node.js?

Spread the love

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 can use parameterized queries.

For instance, we write

const userId = 5;
const query = connection.query(
  "SELECT * FROM users WHERE id = ?",
  [userId],
  (err, results) => {
    // ...
  }
);

to call the Node mysql package’s connection.query method with a string that has the ? placeholder for the id value.

The 2nd argument is an array with the values to fill the placeholders with.

And the last argument is a callback with the results returning the query results.

userId will be escaped before the query is made so eliminate the risk of SQL injection.

Conclusion

To prevent SQL injection in Node.js, we can use parameterized queries.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *