How to Use Placeholders in Node.js to Stop SQL Injection

If you are building a JavaScript back end with PostgreSQL, the pg library is a common choice. This how-to shows the one habit that matters most for safety: putting user values into queries with placeholders.

What you need

Steps

  1. Install the library:
npm install pg
  1. Connect using a connection string from an environment variable (see how to keep a connection string in an environment variable):
const { Pool } = require("pg");
const pool = new Pool({ connectionString: process.env.DATABASE_URL });

A pool keeps a few connections open and reuses them, which is the normal way to use pg in a web app.

  1. Write a query with numbered placeholders:
async function findBooksByAuthor(author) {
  const result = await pool.query(
    "SELECT id, title FROM books WHERE author = $1 ORDER BY title",
    [author]
  );
  return result.rows;
}

$1 means "the first value in the array". A second value would be $2, and so on. The values array is sent separately from the SQL text.

  1. Use it with input from a web request (Express-style example):
app.get("/books", async (req, res) => {
  const books = await findBooksByAuthor(req.query.author);
  res.json(books);
});

Whatever someone types in ?author=..., it is only ever compared as text.

  1. Insert with several placeholders:
await pool.query(
  "INSERT INTO books (title, author) VALUES ($1, $2)",
  [title, author]
);

How to check it worked

The unsafe pattern to avoid

// never do this
pool.query("SELECT * FROM books WHERE author = '" + req.query.author + "'");
// template strings are just as unsafe
pool.query(`SELECT * FROM books WHERE author = '${req.query.author}'`);

Things placeholders cannot do

You want to varyPlaceholder?What to do instead
A value (author, id, date)Yes$1, $2
A column to sort byNoCheck against a list such as ["title", "year"] in code
A table nameNoChoose it in code, never from input
A list of valuesYes, as an arrayWHERE id = ANY($1) with an array value

Next steps

Read our short questions and plain answers on SQL injection for the reasons behind each rule.

A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.

Related pages on this site