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
- Node.js installed
- a PostgreSQL database you can practise on, local or hosted
- a project folder where you have run
npm init -y
Steps
- Install the library:
npm install pg
- 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.
- 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.
- 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.
- Insert with several placeholders:
await pool.query(
"INSERT INTO books (title, author) VALUES ($1, $2)",
[title, author]
);
How to check it worked
- Call your endpoint with a normal author and see the expected books.
- Call it with an author value containing a quote, such as
O'Brien. With placeholders it simply finds books by that author, or none. If you had built the SQL with string joining, a quote like that would cause an error, which is a warning sign of an injection risk.
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 vary | Placeholder? | What to do instead |
|---|---|---|
| A value (author, id, date) | Yes | $1, $2 |
| A column to sort by | No | Check against a list such as ["title", "year"] in code |
| A table name | No | Choose it in code, never from input |
| A list of values | Yes, as an array | WHERE 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.