📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PostgreSQL Essentials PostgreSQL with Node.js

PostgreSQL with Node.js

6 min read
Use the pg library in Node.js with a connection Pool. Always use $1, $2 placeholders to prevent SQL injection. Release the client back to the pool in a finally block after transactions to prevent connection leaks.

PostgreSQL + Node.js (pg)

npm install pg

const { Pool } = require('pg');
const pool = new Pool({ connectionString: process.env.DATABASE_URL });

// Query
const { rows } = await pool.query(
  'SELECT * FROM users WHERE id = $1', [userId]
);

// Transaction
const client = await pool.connect();
try {
  await client.query('BEGIN');
  await client.query('UPDATE ...');
  await client.query('COMMIT');
} finally { client.release(); }