Never trust your users. Sanitize all input

SQL injection

If you use user input without modification, a malicious user can pass unexpected data and fundamentally change your SQL queries.

The single requirement for guarding against SQL injection is to sanitize input, also known as escaping. You can escape each input individually or use a better method known as parameter binding. https://node-postgres.com/

You can also secure your queries by using an ORM such as sequelize. It uses a promise-based approach to modify the database.

Different value types are escaped differently:

  • Numbers are left untouched. Booleans are converted to true / false. Date objects are converted to 'YYYY-mm-dd HH:ii:ss' strings. Buffers are converted to hex strings, like X'0fa5'.
  • Nested arrays are turned into grouped lists (for bulk inserts), e.g. [['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd').
  • Objects are turned into key = 'val' pairs for each enumerable property of the object. If the property’s value is a function, it is skipped. If the property’s value is an object, toString() is called on it, and the returned value is used.
  • undefined / null are converted to NULL.
  • NaN / Infinity are left as-is. MySQL does not support these, and trying to insert them as values will trigger MySQL errors until they implement support.

Client-side JavaScript is NOT a solution for validating data, ever. It can be easily modified or avoided by a malicious user with even a mediocre amount of knowledge.

You can certainly use client-side JavaScript validation to provide instant feedback and present a better user experience, but be sure to check the input on the back end to make sure everything is legit.

--

--