SQL injection in node-postgres queries

SQL injection in node-postgres queries

Description

A request value concatenated into SQL passed to node-postgres can change how the database interprets the query.

Potential impact

A changed condition can bypass access checks or expose, modify or delete records within the database account’s privileges.

Remediation

Pass fixed SQL and a separate values array to client.query. Validate input types and formats, and bind values when using an ORM or query builder. Choose table and column names from a server-side allow-list because value parameters cannot represent them.

Examples

In CommonJS, put the await calls inside an async function. Ensure the connection closes even if the query fails.

Before

javascript
const { Client } = require('pg')
const client = new Client()
await client.connect()
let query = 'SELECT * FROM users WHERE id = ' + userInput;
const res = await client.query(query);
await client.end();

After

javascript
const { Client } = require('pg')
const client = new Client()
await client.connect()
const res = await client.query('SELECT * FROM users WHERE id = $1', [userInput]);
await client.end();

$1 refers to userInput, the first entry in the values array.

References