PostgreSQL with node-postgres

Topic 2 of 4 in Databases8 min readIntermediateFree course

Overview

pg (also called node-postgres) is the standard PostgreSQL driver for Node.js. It’s mature, fast and close to the metal: you write SQL, it sends it to Postgres and gives you back rows as JavaScript objects.

Terminal
npm install pg

Connecting with a pool

JavaScript
// src/db.js
import pg from 'pg';
import { config } from './config.js';

export const pool = new pg.Pool({
  connectionString: config.databaseUrl,
  max: 10,                       // at most 10 connections from this process
  idleTimeoutMillis: 30_000,     // close connections idle for 30 s
  connectionTimeoutMillis: 5_000, // fail if no connection within 5 s
});

pool.on('error', (err) => {
  console.error('Unexpected error on idle database client', err);
});

Six requests share a pg.Pool with a maximum of 10 connections; three connections are busy and one is idle. Each connection to PostgreSQL costs memory. Requests borrow a connection, run their query and give it back; when all are busy, the next request waits its turn.

Opening a database connection takes time and uses memory on the database server — Postgres typically allows only a hundred or so at once. A pool keeps a few connections open and lends them to queries as needed:

  • Create one pool per process, at start-up, and share it (modules are cached, so exporting it is enough).
  • Each pool.query() borrows a connection, runs, and returns it automatically.
  • If all connections are busy, new queries wait in line.

Several app processes each have their own pool, so max × processes must stay below the database’s limit.

Running queries

JavaScript
const { rows } = await pool.query('SELECT id, title FROM courses ORDER BY id');
console.log(rows); // [{ id: '1', title: 'Node.js' }, …]

const { rows: [course] } = await pool.query(
  'SELECT * FROM courses WHERE id = $1',
  [42],
);
if (!course) { /* not found */ }

const { rowCount } = await pool.query('DELETE FROM courses WHERE id = $1', [42]);
// rowCount tells you how many rows were affected

RETURNING gives you the inserted or updated row in the same round trip:

JavaScript
const { rows: [created] } = await pool.query(
  `INSERT INTO courses (title, level) VALUES ($1, $2) RETURNING *`,
  [title, level],
);

Parameters, always

Building SQL with a template string like SELECT * FROM users WHERE email = ‘${email}’ lets an input such as x’ OR ‘1’=’1 change the query so every user is returned. Using pool.query(‘SELECT * FROM users WHERE email = $1’, [email]) sends the SQL and the values separately, so the database never treats a value as code.

SQL injection happens when user input is pasted into a SQL string and changes its meaning. It has caused some of the largest data breaches in history, and it’s completely preventable:

JavaScript
// ✗ NEVER
pool.query(`SELECT * FROM users WHERE email = '${req.body.email}'`);

// ✓ ALWAYS
pool.query('SELECT * FROM users WHERE email = $1', [req.body.email]);

With placeholders ($1, $2…), the SQL text and the values are sent to Postgres separately. The database never interprets a value as SQL, whatever characters it contains.

Placeholders work for values only — not table names, column names or ASC/DESC. When those vary (for example, a sort query parameter), choose from a fixed list you control:

JavaScript
const SORTABLE = { title: 'title', newest: 'created_at DESC', oldest: 'created_at ASC' };
const orderBy = SORTABLE[req.validated.query.sort] ?? 'created_at DESC';
const sql = `SELECT * FROM courses ORDER BY ${orderBy} LIMIT $1`;

Rows to objects

Postgres conventionally uses snake_case column names, while JavaScript uses camelCase. Translate in the repository, so the rest of the app never sees database naming:

JavaScript
const toCourse = (row) => row && {
  id: Number(row.id),
  title: row.title,
  level: row.level,
  status: row.status,
  createdAt: row.created_at.toISOString(),
};

Type surprises

pg converts most Postgres types sensibly — integer to number, boolean to boolean, timestamptz to Date, jsonb to objects. Two exceptions catch people out:

  • bigint (including COUNT(*) results and bigint IDs) arrives as a string, because it can exceed JavaScript’s safe integer range.
  • numeric (exact decimals, e.g. money) arrives as a string, to avoid floating-point errors.

Convert deliberately: Number(row.count) is fine for counts; keep money as integers in the smallest unit.

Handling database errors

Postgres errors carry a five-character code. The ones you’ll handle most:

Code Meaning Typical response
23505 unique violation (duplicate email, title…) 409 Conflict
23503 foreign key violation (referenced row missing) 400 or 409
23502 not-null violation 400 (your validation missed something)
57014 query cancelled (e.g. statement timeout) 503
JavaScript
try {
  return await pool.query('INSERT INTO users (email) VALUES ($1) RETURNING *', [email]);
} catch (err) {
  if (err.code === '23505') throw new HttpError(409, 'That email is already registered');
  throw err;
}

Letting a unique constraint in the database catch duplicates is more reliable than checking first in code: two requests at the same moment can both pass a “does it exist?” check, but only one can win the constraint.

The CRUD project on Postgres

Remember the in-memory repository from Project: a CRUD API? Here is the same interface backed by Postgres:

JavaScript
// src/courses/courses.repository.pg.js
import { HttpError } from '../errors.js';

export function makePgCoursesRepo(pool) {
  const toCourse = (r) => r && {
    id: Number(r.id), title: r.title, description: r.description,
    level: r.level, status: r.status,
    createdAt: r.created_at, updatedAt: r.updated_at,
  };

  return {
    async list({ level, search, page, limit }) {
      const where = [];
      const values = [];
      if (level) { values.push(level); where.push(`level = $${values.length}`); }
      if (search) { values.push(`%${search}%`); where.push(`title ILIKE $${values.length}`); }
      const filter = where.length ? `WHERE ${where.join(' AND ')}` : '';

      const total = await pool.query(`SELECT count(*) FROM courses ${filter}`, values);
      const { rows } = await pool.query(
        `SELECT * FROM courses ${filter} ORDER BY id DESC
         LIMIT $${values.length + 1} OFFSET $${values.length + 2}`,
        [...values, limit, (page - 1) * limit],
      );
      return { items: rows.map(toCourse), total: Number(total.rows[0].count) };
    },
    async findById(id) {
      const { rows } = await pool.query('SELECT * FROM courses WHERE id = $1', [id]);
      return toCourse(rows[0]) ?? null;
    },
    async findByTitle(title) {
      const { rows } = await pool.query('SELECT * FROM courses WHERE lower(title) = lower($1)', [title]);
      return toCourse(rows[0]) ?? null;
    },
    async insert({ title, description, level }) {
      try {
        const { rows } = await pool.query(
          `INSERT INTO courses (title, description, level) VALUES ($1, $2, $3) RETURNING *`,
          [title, description, level],
        );
        return toCourse(rows[0]);
      } catch (err) {
        if (err.code === '23505') throw new HttpError(409, 'A course with this title already exists');
        throw err;
      }
    },
    async update(id, changes) {
      const columns = { title: 'title', description: 'description', level: 'level', status: 'status' };
      const sets = [];
      const values = [];
      for (const [key, column] of Object.entries(columns)) {
        if (changes[key] !== undefined) {
          values.push(changes[key]);
          sets.push(`${column} = $${values.length}`);
        }
      }
      values.push(id);
      const { rows } = await pool.query(
        `UPDATE courses SET ${sets.join(', ')}, updated_at = now() WHERE id = $${values.length} RETURNING *`,
        values,
      );
      return toCourse(rows[0]);
    },
    async remove(id) {
      const { rowCount } = await pool.query('DELETE FROM courses WHERE id = $1', [id]);
      return rowCount > 0;
    },
  };
}

Then change one line in server.js:

JavaScript
createApp({ coursesRepo: makePgCoursesRepo(pool) }).listen(port);

The service, routes, validation and error handling are untouched. That’s the layered structure paying off.

Closing the pool

When the app shuts down, close the pool so connections are released cleanly: await pool.end(). You’ll wire this into graceful shutdown in the Production chapter.

Keep queries in repositories, keep them parameterised, and keep the pool shared. Those three habits prevent most database problems in Node apps.

Exercise

A Postgres repository

Write findCourses({ level, search, limit, offset }) with pg that builds a safe, parameterised query: filter by level if given, search titles case-insensitively if search is given, order newest first, and apply limit and offset. Never put a user value into the SQL string itself.

JavaScript
import { pool } from './db.js';

export async function findCourses({ level, search, limit = 20, offset = 0 }) {
  // your code here
}

Summary

  • Create one pg.Pool for the whole app and reuse it; the pool hands out and recycles connections.
  • pool.query(sql, values) returns { rows, rowCount }; values go in $1, $2… placeholders.
  • Never interpolate user input into SQL — parameters make SQL injection impossible.
  • Map snake_case columns to camelCase fields in the repository; watch out for bigint and numeric arriving as strings.
  • Handle constraint errors by code — 23505 is a unique violation, which usually becomes a 409.