API Reference

node-postgres (pg)

PostgreSQL client for Node.js with connection pooling, parameterized queries, transactions, and typed results for production database access.

Official Documentation ↗
CompatibilityThis documentation covers version pg 8.x with Node.js 20+; pool defaults and timeouts are configuration, not guarantees. Check the official docs for the latest API surface.

Installation

npmnpm install pg
pnpmpnpm add pg
yarnyarn add pg

Methods

pg is the standard PostgreSQL client for Node.js. Use a pool, parameterized queries, and explicit transactions. The client does not validate SQL or protect against every injection pattern; it only separates values from the query text when placeholders are used.

Pool sizing

The pool’s max is per process. Sum it across replicas, workers, and migration tools, and keep the total below the database’s max_connections with headroom. A large pool can overload the database; a small pool can queue requests.

Errors and cleanup

Check query errors, roll back failed transactions, and release clients in finally. Do not hold a client while waiting on an HTTP API or user input. On shutdown, stop accepting work before calling pool.end().

FAQ

Why should I use a pool instead of a new Client per request?
Opening a connection requires a handshake and authentication. A pool reuses connections and bounds concurrency, which reduces latency and protects the database from too many sessions.
How do I prevent SQL injection with pg?
Use parameter placeholders such as $1 and pass values in the values array. Do not build SQL by concatenating strings, including identifiers; identifiers need a separate allowlist.
Why does pool.query work but my transaction fail?
Each pool.query may use a different connection. A transaction needs one checked-out client for BEGIN, all statements, and COMMIT or ROLLBACK, and the client must be released afterward.