EthicsComputerCourses
Join training +91 90532 10052

Querying PostgreSQL with node-postgres

PERN Stack · Lesson 6 of 20 Intermediate 12 min read Updated

By the end of this lesson the KharchaBook API will read and write real PostgreSQL rows instead of an in-memory array. You will create one connection pool, write every query with parameters, fix the date problem we found in the last lesson, turn constraint errors into friendly API errors, and save several rows in one transaction. The routes from the Express lesson will not change at all.

What you should know first: Build a REST API with Express 5, whose data layer we replace, and PostgreSQL Setup & Schema Design, which created the tables, the kharcha_app role and DATABASE_URL. For general background, see Connect from Python, Node.js & PHP and Callbacks, Promises & async/await. Versions used: pg 8.23.1 (the npm package for node-postgres) and PostgreSQL 18.6. Every output below comes from running this code.

Client, pool and query

node-postgres is the most widely used PostgreSQL driver for Node.js. A driver is the library that speaks the database's network protocol for you. You install it as the npm package pg. It gives you two main tools:

ToolWhat it isWhen to use it
ClientOne connection to PostgreSQLShort scripts that connect, run a few queries and exit
PoolA set of connections that are reusedServers, where many requests run at the same time

Opening a connection is slow, because of the network setup and password check. Think of the autorickshaw stand outside Pune station. Passengers do not wait for a new rickshaw to be built. They take the next free one from the stand, and the rickshaw comes back for the next passenger. A pool is that stand. Each query borrows a connection, runs, and returns it. By default a pg pool keeps up to 10 connections and closes one that has been idle for 10 seconds.

Step 1: install pg and read DATABASE_URL

From the kharchabook folder:

Terminal
npm install pg -w server
Output
added 14 packages, changed 1 package, and audited 130 packages in 28s

42 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Then add the database setting to server/src/config.js, the only file that reads process.env. If DATABASE_URL is missing, the server now refuses to start, which is what the project-structure lesson promised:

JavaScript
export const config = {
  port: Number(process.env.PORT ?? 4000),
  clientOrigin: required("CLIENT_ORIGIN"),
  databaseUrl: required("DATABASE_URL"),
};

Step 2: one pool for the whole server

Create server/src/db.js. Every other file imports from here, so the server has exactly one pool:

JavaScript
// The one PostgreSQL connection pool for the whole server.
import pg from "pg";
import { config } from "./config.js";

// 1082 is the type id (OID) of PostgreSQL's `date` type.
// Keep dates as "YYYY-MM-DD" text instead of turning them into JavaScript Dates.
pg.types.setTypeParser(1082, (value) => value);

export const pool = new pg.Pool({
  connectionString: config.databaseUrl,
  max: 10,
  connectionTimeoutMillis: 5000,
});

// An idle connection can break (database restart, network drop).
// Without this listener the error would crash the whole server.
pool.on("error", (err) => {
  console.error("PostgreSQL pool error:", err.message);
});

export function query(text, params) {
  return pool.query(text, params);
}

max: 10 is the default, written out so readers see it. connectionTimeoutMillis: 5000 makes a request fail after 5 seconds if no connection is free; the default, 0, waits forever, and a stuck request is harder to debug than an error. The error listener matters because the pool is an event emitter: an error event with no listener stops the Node.js process.

The setTypeParser line is the fix for dates. The next step shows why we need it.

Step 3: see what types come back

PostgreSQL sends every value as text. node-postgres then converts some types into JavaScript values. This small script asks for one expense without our type parser, using the same DATABASE_URL:

JavaScript
// server/scripts/types-before.js
import pg from "pg";

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const { rows } = await pool.query(
  "SELECT id, amount, spent_on, created_at, count(*) OVER () AS total FROM expenses WHERE id = $1",
  [2],
);
console.log(rows[0]);
console.log(JSON.stringify(rows[0]));
await pool.end();

Run it with node --env-file=.env scripts/types-before.js from the server folder. On our laptop, set to India time:

Output
{
  id: 2,
  amount: '2340.50',
  spent_on: 2026-11-01T18:30:00.000Z,
  created_at: 2026-11-16T05:50:37.501Z,
  total: '1'
}
{"id":2,"amount":"2340.50","spent_on":"2026-11-01T18:30:00.000Z","created_at":"2026-11-16T05:50:37.501Z","total":"1"}

Priya bought groceries on 2 November, but the JSON says 1 November. Here is what happened. For a date column, node-postgres builds a JavaScript Date at midnight in the server's local time zone. India is 5 hours 30 minutes ahead of UTC, so midnight on 2 November in Pune is 18:30 on 1 November in UTC. JSON.stringify always writes dates in UTC, and the day changes. Running the same script with TZ=UTC printed 2026-11-02T00:00:00.000Z: the right day, but still not the "YYYY-MM-DD" our contract promises. So the bug depends on where the server runs, which is the worst kind of bug.

A calendar day has no time and no time zone, so it should stay text. pg.types.setTypeParser(1082, (value) => value) tells node-postgres: "for type 1082 (date), give me the text unchanged". Type ids like 1082 are PostgreSQL's fixed OIDs (object identifiers). Here is what each column type becomes once our db.js is loaded:

PostgreSQL typeJavaScript valueWhy
integernumberFits safely in a JavaScript number
numeric(10,2)string, "2340.50"Exact; a number could lose precision
bigint, including count(*)string, "1"Can be larger than JavaScript numbers hold safely
datestring, "2026-11-02"Our type parser; the default is a local-midnight Date
timestamptzDateA real moment; JSON writes it as UTC ISO text

For counts, cast in SQL when you want a number: count(*)::int.

Step 4: SQL in the data layer

Now replace the bodies in server/src/data/. First categories.js:

JavaScript
import { query } from "../db.js";

export async function listCategories() {
  const { rows } = await query("SELECT id, name FROM categories ORDER BY id");
  return rows;
}

export async function findCategory(id) {
  const { rows } = await query("SELECT id, name FROM categories WHERE id = $1", [id]);
  return rows[0] ?? null;
}

query() returns a result object. rows is an array of plain objects, one per row, with column names as keys. $1 is a placeholder, and the array after the SQL holds the value for it. Then expenses.js, shown in part:

JavaScript
import { query } from "../db.js";

// Every expense query returns these columns: e = expenses, c = categories.
const FIELDS = `e.id, e.amount, e.category_id, c.name AS category,
  e.spent_on, e.note, e.created_at`;

function toExpense(row) {
  return {
    id: row.id,
    amount: row.amount,
    categoryId: row.category_id,
    category: row.category,
    spentOn: row.spent_on,
    note: row.note,
    createdAt: row.created_at,
  };
}

export async function listExpenses() {
  const { rows } = await query(
    `SELECT ${FIELDS}
     FROM expenses e JOIN categories c ON c.id = e.category_id
     ORDER BY e.spent_on DESC, e.id DESC`,
  );
  return rows.map(toExpense);
}

export async function createExpense(input) {
  const { rows } = await query(
    `WITH e AS (
       INSERT INTO expenses (amount, category_id, spent_on, note)
       VALUES ($1, $2, $3, $4)
       RETURNING *
     )
     SELECT ${FIELDS} FROM e JOIN categories c ON c.id = e.category_id`,
    [input.amount, input.categoryId, input.spentOn, input.note],
  );
  return toExpense(rows[0]);
}

export async function deleteExpense(id) {
  const { rowCount } = await query("DELETE FROM expenses WHERE id = $1", [id]);
  return rowCount === 1;
}

toExpense() is no longer async: the JOIN brings the category name in the same query, so there is no second lookup. createExpense uses a CTE (a WITH query) around INSERT ... RETURNING *, so the new row and its category name come back in one round trip. updateExpense follows the same pattern with UPDATE ... WHERE id = $5 RETURNING *, and returns null when no row matched. getExpense is listExpenses with WHERE e.id = $1. deleteExpense uses rowCount, the number of rows the statement touched. The ${FIELDS} text is our own constant, never user input, so building SQL from it is safe.

Parameters stop SQL injection

Why not just put the value into the SQL text? Here is a search written both ways. The first function is the mistake; never copy it:

JavaScript
async function searchUnsafe(text) {
  const sql = `SELECT id, note FROM expenses WHERE note ILIKE '%${text}%'`;
  return (await query(sql)).rows;
}

async function searchSafe(text) {
  const sql = "SELECT id, note FROM expenses WHERE note ILIKE '%' || $1 || '%'";
  return (await query(sql, [text])).rows;
}

const attack = "' OR '1'='1";
console.log("unsafe:", (await searchUnsafe(attack)).length, "rows");
console.log("safe:  ", (await searchSafe(attack)).length, "rows");
console.log("safe search for 'rent':", await searchSafe("rent"));
Output
unsafe: 5 rows
safe:   0 rows
safe search for 'rent': [ { id: 1, note: 'November rent, Kothrud flat' } ]

The attack text closed the quote and added OR '1'='1', which is true for every row, so the unsafe search returned all five expenses. With $1, node-postgres sends the SQL and the value separately. PostgreSQL treats the value only as data, so it searched for notes containing that odd text and found none. The OWASP API Security Top 10 lesson has more on injection. Note that placeholders work for values only. Table and column names cannot be parameters; if they ever come from the user, check them against a fixed allow-list.

Step 5: turn constraint errors into API errors

The database can still refuse a row that passed our validator, for example if a category is deleted between the check and the insert. A node-postgres error carries PostgreSQL's details, including code (such as 23503, foreign key violation) and constraint, the name PostgreSQL gave each rule in the schema lesson. Add a map to server/src/middleware/errors.js and check it in errorHandler, just before the general 500:

JavaScript
// PostgreSQL constraint name -> [JSON field, message for the user].
const CONSTRAINT_FIELDS = {
  expenses_category_id_fkey: ["categoryId", "Choose a category from the list."],
  expenses_amount_check: ["amount", "Enter an amount from 0.01 to 1000000, with at most 2 decimals."],
  expenses_note_check: ["note", "The note must be text of at most 200 characters."],
};

// inside errorHandler, after the BAD_JSON and TOO_LARGE checks:
const field = CONSTRAINT_FIELDS[err.constraint];
if (field) {
  return res.status(400).json({
    error: {
      code: "VALIDATION_FAILED",
      message: "Some fields need fixing.",
      details: { [field[0]]: field[1] },
    },
  });
}

To test it, we switched off the category check in checkBody for a moment and posted category 42. The database refused the row and the client still got the standard shape:

Output
400 {"error":{"code":"VALIDATION_FAILED","message":"Some fields need fixing.","details":{"categoryId":"Choose a category from the list."}}}

Any other database error, such as a wrong password, still becomes the general INTERNAL 500. The server log shows the real cause, here error: password authentication failed for user "kharcha_app" with code: '28P01', and the client never sees it.

Step 6: run the API on PostgreSQL

Start the server with npm run dev -w server and repeat the curl calls from the Express lesson. The seed data is already there:

Terminal
curl http://localhost:4000/api/expenses/2
Output
{"data":{"id":2,"amount":"2340.50","categoryId":1,"category":"Groceries","spentOn":"2026-11-02","note":"DMart monthly ration","createdAt":"2026-11-16T05:50:37.501Z"}}

The date is "2026-11-02", the amount is a two-decimal string, and the shape matches the contract. Restart the server and the data is still there.

Transactions need one client

pool.query() may use a different connection for each call. A transaction (BEGIN ... COMMIT) must run on one connection, so you borrow a client from the pool and give it back in finally. Add this helper to db.js:

JavaScript
// Runs work(client) inside BEGIN/COMMIT on one connection; rolls back on any error.
export async function transaction(work) {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    const result = await work(client);
    await client.query("COMMIT");
    return result;
  } catch (err) {
    await client.query("ROLLBACK");
    throw err;
  } finally {
    client.release();
  }
}

Kabir wants to import a list of expenses from his bank statement: all of them or none. An importExpenses(inputs) function in data/expenses.js calls transaction() and runs one INSERT per item with client.query(). We imported two rows, the second with category 42, and counted rows before and after:

Output
Import failed: 23503 expenses_category_id_fkey
{ before: 5, after: 5 }

The first INSERT succeeded inside the transaction, but ROLLBACK undid it, so the table still has 5 rows. Forgetting client.release() is a classic bug: after 10 leaks the pool is empty and every request waits until it times out.

Why the date fix matters in React

The client code from the project-structure lesson splits spentOn on -. Here is what it does with the old and the fixed API value:

React JSXOpen in editor
import { createRoot } from "react-dom/client";

// The same expense, as the API sent it before and after the type parser fix
const before = { id: 2, category: "Groceries", amount: "2340.50", spentOn: "2026-11-01T18:30:00.000Z" };
const after = { id: 2, category: "Groceries", amount: "2340.50", spentOn: "2026-11-02" };

const inr = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" });
function formatDate(isoDate) {
  const [y, m, d] = isoDate.split("-").map(Number);
  return new Date(y, m - 1, d).toLocaleDateString("en-IN", { day: "numeric", month: "short", year: "numeric" });
}

function Row({ label, expense }) {
  const shown = formatDate(expense.spentOn);
  console.log(label, JSON.stringify(expense.spentOn), "->", shown);
  return <li>{label}: {expense.category}, {inr.format(Number(expense.amount))} on {shown}</li>;
}

createRoot(document.getElementById("root")).render(
  <ul>
    <Row label="Before" expense={before} />
    <Row label="After" expense={after} />
  </ul>
);
Output
Before "2026-11-01T18:30:00.000Z" -> Invalid Date
After "2026-11-02" -> 2 Nov 2026

With the old value, the third part was "01T18:30:00.000Z", which is not a number, so the page shows "Invalid Date". Code using new Date(spentOn) would show the wrong day in India instead. One server line fixes both.

Common mistakes

  • Creating a new Pool per request. Each one opens fresh connections and soon hits PostgreSQL's connection limit. Create one pool in db.js.
  • Building SQL with template strings from user input. Use $1, $2 placeholders for every value.
  • Leaving date as a JavaScript Date. The day can shift with the server's time zone. Keep it as text with setTypeParser(1082, ...).
  • Adding counts that came back as strings. "1" + "2" is "12". Cast with ::int in SQL or use Number().
  • Running BEGIN with pool.query(). The next query may use another connection. Use pool.connect() and release the client in finally.

Interview questions

1. What is the difference between a Client and a Pool in node-postgres?

A Client is one connection that you open and close yourself, which suits short scripts. A Pool keeps several connections open and lends them to queries, so a server does not pay the connection cost on every request. The pool also limits how many connections the app opens at once.

2. Why does node-postgres return numeric and bigint values as strings?

JavaScript numbers are 64-bit floating point. They cannot hold every bigint exactly, and decimals such as money would lose precision. Returning strings keeps the exact value, and the application decides how to convert it.

3. How do parameterised queries prevent SQL injection?

The SQL text and the values are sent to PostgreSQL separately. The values are never parsed as SQL, so input such as ' OR '1'='1 is just text to compare. Only values can be parameters, so table and column names must come from an allow-list.

4. How do you run a transaction with a pool?

Borrow one client with pool.connect(), run BEGIN, your queries and COMMIT on that client, and run ROLLBACK if anything throws. Always call client.release() in a finally block, or the pool slowly runs out of connections.

Key points

  • Install pg, create one Pool in src/db.js, and listen for its error event.
  • Write every value as a $1 placeholder; never build SQL from user input.
  • numeric and bigint arrive as strings; setTypeParser(1082, v => v) keeps date as "YYYY-MM-DD".
  • Only the bodies of the data functions changed; routes, validation and the contract stayed the same.
  • Map constraint names to field errors, and keep the general 500 for everything else.
  • Transactions need one client from pool.connect(), with ROLLBACK on error and release() in finally.

Exercise

Add a monthly report endpoint, GET /api/reports/monthly?month=2026-11. It should return { "data": [ { "category": "Rent", "total": "18000.00", "entries": 1 }, ... ] }, biggest total first. Put the SQL in a new server/src/data/reports.js, use placeholders for the month range, make entries a real number, and answer a missing or badly formed month with the standard VALIDATION_FAILED error.

Show solution
JavaScript
// server/src/data/reports.js
import { query } from "../db.js";

export async function monthlyTotals(firstDay, nextFirstDay) {
  const { rows } = await query(
    `SELECT c.name AS category, sum(e.amount) AS total, count(*)::int AS entries
     FROM expenses e JOIN categories c ON c.id = e.category_id
     WHERE e.spent_on >= $1 AND e.spent_on < $2
     GROUP BY c.name
     ORDER BY total DESC`,
    [firstDay, nextFirstDay],
  );
  return rows;
}

// server/src/routes/reports.js
import { Router } from "express";
import { monthlyTotals } from "../data/reports.js";
import { HttpError } from "../middleware/errors.js";

const router = Router();

router.get("/monthly", async (req, res) => {
  const month = String(req.query.month ?? "");
  if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(month)) {
    throw new HttpError(400, "VALIDATION_FAILED", "Some fields need fixing.", {
      month: "Use a month in the form YYYY-MM.",
    });
  }
  const [y, m] = month.split("-").map(Number);
  const next = m === 12 ? `${y + 1}-01` : `${y}-${String(m + 1).padStart(2, "0")}`;
  res.json({ data: await monthlyTotals(`${month}-01`, `${next}-01`) });
});

export default router;

Mount it in app.js with app.use("/api/reports", reportsRouter) before notFound. count(*)::int makes entries a number, while total stays an exact string. The month is checked with a pattern before it reaches SQL, and it still travels as a parameter.

Quick Quiz

1. Why does a server use a Pool rather than one Client per request?

2. Without a type parser, what does node-postgres return for a date column?

3. Which query is safe from SQL injection?

4. In a transaction helper, where must client.release() go?

Learn PERN Stack with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call