Registry / database / pg
library0.1jsnpmunverified

pg (node-postgres) is a robust and non-blocking PostgreSQL client for Node.js, providing both a pure JavaScript implementation and optional native `libpq` bindings, both exposing the exact same API. Currently at version 8.20.0, the library maintains an active development pace with regular updates and bug fixes, indicated by its consistent major version releases and community support. Key features include efficient connection pooling, extensible data-type coercion between JavaScript and PostgreSQL types, support for parameterized queries to prevent SQL injection, named statements with query plan caching, and asynchronous notifications via `LISTEN/NOTIFY`. It also facilitates bulk data operations using `COPY TO/COPY FROM`. Its design prioritizes being a light abstraction layer, encouraging users to leverage companion modules for higher-level ORM or query building needs.

npm install pg
INSTALL
IMPORT
SIG · PG
P
pg
databasejavascriptv0.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Pool
import { Pool } from 'pg';
const { Pool } = require('pg'); // or in older ESM setups: import pg from 'pg'; const { Pool } = pg;
Since `pg@8.15.x`, named ESM imports like `import { Pool } from 'pg'` are fully supported. Prior to that, or in some mixed CommonJS/ESM setups, `import pg from 'pg'; const { Pool } = pg;` or the CommonJS `require` syntax might have been used. Pool is the recommended way to manage database connections in most applications.
Client
import { Client } from 'pg';
const { Client } = require('pg'); // or in older ESM setups: import pg from 'pg'; const { Client } = pg;
Use a single Client instance for short-lived, single-query operations or when you need a dedicated connection, such as for transactions where all queries must run on the same client. For general application use, `Pool` is preferred.
types
import { types } from 'pg';
const types = require('pg').types;
The `types` object allows for customizing how PostgreSQL data types are parsed into JavaScript. This is crucial for handling large integers (e.g., `int8`) or custom types to prevent precision loss or to integrate with specific JavaScript objects like `moment` for dates.

This quickstart demonstrates how to use `pg` with connection pooling, parameterized queries for safety, and basic database setup/teardown. It utilizes environment variables for configuration and handles connection acquisition and release from the pool.

import { Pool } from 'pg'; import dotenv from 'dotenv'; dotenv.config(); const pool = new Pool({ connectionString: process.env.DATABASE_URL ?? 'postgresql://user:password@localhost:5432/mydb', ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : undefined, // Adjust SSL for production }); async function queryDatabase() { let client; try { client = await pool.connect(); // Acquire a client from the pool const res = await client.query('SELECT $1::text as message, NOW() as currentTime;', ['Hello from pg!']); console.log('Query result:', res.rows[0].message); console.log('Current DB Time:', res.rows[0].currenttime); const insertRes = await client.query('INSERT INTO users(name, email) VALUES($1, $2) RETURNING id;', ['John Doe', 'john.doe@example.com']); console.log('Inserted user with ID:', insertRes.rows[0].id); const usersRes = await client.query('SELECT * FROM users WHERE email = $1;', ['john.doe@example.com']); console.log('Found user:', usersRes.rows[0]); } catch (err) { console.error('Database operation failed:', err); process.exit(1); } finally { if (client) { client.release(); // Release the client back to the pool console.log('Client released.'); } } } async function setupDatabase() { const setupClient = await pool.connect(); try { console.log('Setting up database...'); await setupClient.query(` CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP ); `); console.log('Table "users" ensured.'); } catch (err) { console.error('Database setup failed:', err); } finally { setupClient.release(); } } setupDatabase().then(() => queryDatabase().then(() => pool.end()));
Debug
Known issues
breakingThe default behavior for SSL connections changed in `pg@8.0`. Previously, `ssl: true` defaulted to `rejectUnauthorized: false` for self-signed certificates. Now, `rejectUnauthorized` defaults to `true`, which will cause connections to fail unless a valid certificate chain is provided or `ssl: { rejectUnauthorized: false }` is explicitly set.
fix
If connecting to a database with a self-signed certificate, explicitly set `ssl: { rejectUnauthorized: false }` in your Client or Pool configuration: `const pool = new Pool({ ssl: { rejectUnauthorized: false } });`
affects: >=8.0.0
breakingIn `pg@7.0`, the global singleton `pg.connect()`, `pg.end()`, and `pg.cancel()` methods were removed, having been deprecated since `pg@6.3`. Direct use of the `Pool` constructor is now required.
fix
Replace `pg.connect()` with `pool.connect()` after instantiating a `new Pool()` object. Similarly, replace `pg.end()` with `pool.end()`. See the official migration guide for more details.
affects: >=7.0.0
breakingThe `client.query()` method's return value changed significantly in `pg@7.0`. When a callback is provided, it now returns `undefined` (previously an event emitter). When no callback is provided, it returns a `Promise`. The query object itself is no longer an event emitter by default.
fix
Refactor code using `client.query().on('row', ...)` or other event emitter patterns. For streaming, use `pg-cursor` or `pg-query-stream`. For simple queries, use async/await with the promise returned by `client.query()` without a callback.
affects: >=7.0.0
gotchaFailure to release client connections back to the pool (`client.release()`) will lead to connection pool exhaustion, causing new database requests to hang or fail with 'too many clients' errors, eventually crashing the application.
fix
Always ensure `client.release()` is called in a `finally` block after acquiring a client with `pool.connect()`, regardless of whether the database operations succeeded or failed.
affects: >=1.0.0
gotchaNot using parameterized queries (`$1`, `$2`, etc.) when inserting or updating data based on user input exposes your application to SQL injection vulnerabilities. String concatenation for query parameters is highly discouraged.
fix
Always use parameterized queries. Pass an array of values as the second argument to `client.query(text, values)` to let `pg` handle safe parameter substitution. For dynamic identifiers (table/column names), use a library like `pg-format` for proper escaping.
affects: >=1.0.0
gotchaThe optional `pg-native` peer dependency can improve performance but requires PostgreSQL client libraries (libpq-dev) and a C/C++ compiler toolchain to be installed on the system where `pg-native` is built. Build failures are common if these prerequisites are missing.
fix
Ensure `libpq-dev` (or equivalent for your OS, e.g., `postgresql-devel` on RHEL, `libpq` on macOS via Homebrew) and a C++ compiler are installed before `npm install pg-native`. If `pg-native` is not strictly necessary for performance, `pg` will gracefully fall back to its pure JavaScript implementation.
affects: >=1.0.0
Errors
Common errors & fixes
Error: password authentication failed for user "your_user"
Incorrect username or password in the connection configuration (environment variables, connection string, or config object).
fix
Verify `PGUSER`, `PGPASSWORD`, `PGDATABASE`, `PGHOST`, `PGPORT` environment variables or the respective properties in the `Client`/`Pool` config object. Ensure the PostgreSQL user exists and has the correct password.
Error: Client was closed and is no longer queryable
Attempting to execute a query on a `Client` instance that has already been explicitly ended (`client.end()`) or implicitly closed (e.g., due to connection loss or idle timeout) without reconnecting or acquiring a new client. This can also happen if a client is returned to the pool and then reused before it's truly available, or if transactions are attempted across different clients from a pool.
fix
Ensure `client.end()` is not called prematurely for long-lived clients or that you are always acquiring a fresh client from the `Pool` for each logical unit of work, releasing it afterward. For transactions, ensure all queries are executed on the *same* `Client` instance acquired from the `Pool` until the transaction is committed or rolled back.
Error: no pg_hba.conf entry for host "X.X.X.X", user "your_user", database "your_db", no encryption
The PostgreSQL server's `pg_hba.conf` file does not contain an entry that permits the specified user, database, host, and authentication method to connect.
fix
Edit your PostgreSQL server's `pg_hba.conf` file to add an appropriate entry allowing connections from your application's host with the specified user, database, and authentication method (e.g., `host all all 0.0.0.0/0 md5` for broad access with password or `hostssl all all 0.0.0.0/0 scram-sha-256` for secure access).
SyntaxError: Named export 'Pool' not found. The requested module 'pg' is a CommonJS module, which may not support all module.exports as nam...
Attempting to use named ESM imports (e.g., `import { Pool } from 'pg';`) in an environment where `pg` is being loaded as a CommonJS module, or with an older version of `pg` that did not fully support named ESM exports.
fix
Ensure you are using `pg@8.15.x` or newer for full ESM support. If you must use an older version or are in a mixed CJS/ESM environment, use `import pg from 'pg'; const { Pool } = pg;` or the CommonJS `const { Pool } = require('pg');` pattern. Make sure your `package.json` has `"type": "module"` if you intend to use native ESM.
Upgrade
Version history
0.1latest on npm
Audit
Dependencies
pg-nativeoptionalOptional native libpq bindings for improved performance; falls back to pure JavaScript if not installed or fails to build. Requires PostgreSQL client libraries (libpq) installed on the system to compile.
Agent activity
6 hits · last 30 days
node
6
Resources