Question

I'm new to Node.js and don't know how sql injection gets handled? My code in Node.js is something like below:

connection.query('SELECT email FROM users WHERE firstName LIKE \'%'+firstName+'%\';', function (error, rows, fields){ someCodeHere... }

I receive inputs directly from user and put it inside of the query. I'm more concerned about sql injection here? Does Node.js do the sanitization? How to prevent sql injection in Node.js?


EDIT :
In the above link provided it's been said that we should use:

connection.escape(query);

Should I put it inside of another variable or my code should look like the below one:

connection.escape(query);
connection.query('SELECT email FROM users WHERE firstName LIKE \'%'+firstName+'%\';', function (error, rows, fields){ someCodeHere... }

No correct solution

OTHER TIPS

I would recommend using ? placeholders which performs escaping.

var query = 'SELECT email FROM users WHERE firstName LIKE \'%?%\';';
connection.query(query, [firstName], function (error, rows, fields){
  //someCodeHere... 
});

Also, you may want to not set multipleStatements to true. It is false by default, but as noted in the readme, it is susceptible to SQL injections. Whether or not that is the case when input is escaped, I'm not sure.

multipleStatements: Allow multiple mysql statements per query. Be careful with this, it exposes you to SQL injection attacks. (Default: false)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top