Aller au contenu principal

PostgreSQL with Node.js

Prerequisites: an active PostgreSQL database, an application user, Node.js with npm, and the public connection settings from setup. This example only reads a constant and works with a read user.

Install and configure​

In a new example directory:

npm init -y
npm install pg

Set DATABASE_URL securely in your process environment using your application user and the database’s public connection settings. Use a real password, not ****. Preserve the appropriate TLS options; confirm certificate validation requirements with your deployment. See configuration.

Run a first query​

Create connect.mjs:

import pg from 'pg';

if (!process.env.DATABASE_URL) throw new Error('Set DATABASE_URL');
const pool = new pg.Pool({
connectionString: process.env.DATABASE_URL,
max: 2,
connectionTimeoutMillis: 5000,
idleTimeoutMillis: 10000,
});

try {
const result = await pool.query('SELECT 1 AS value');
console.log(result.rows[0].value); // Expected: 1
} catch (error) {
console.error('PostgreSQL connection/query failed:', error.code ?? error.name);
process.exitCode = 1;
} finally {
await pool.end();
}
node connect.mjs

Printing 1 confirms a native PostgreSQL connection and query. An HTTP developer token is not involved.

Integrate into your server​

Create one bounded pool per application process and reuse it. Close it during shutdown, not after every web request. Include all replicas when budgeting connections. Use parameterized queries for application input, for example pool.query('SELECT $1::text AS value', [userInput]).

Run application migrations separately with an appropriately privileged user. A successful connection does not create your schema. If your application relies on session state or prepared statements, verify compatibility with the available pooling mode.

Driver details: node-postgres connection configuration. If the first query fails, use connection troubleshooting.