Connect with Node.js
Connect a Node.js application to a Managed PostgreSQL service with the pg package (node-postgres), with TLS certificate verification and credentials read from the environment.
Prerequisites
You need:
- A running Managed PostgreSQL service.
- The Exoscale CLI, configured with your API credentials, and
jq. - Node.js 18 or later.
- Your client IP address in the service IP filter. See Restrict Connections to a Service.
The service accepts TLS connections only: a client with TLS turned off (ssl: false) is
rejected with no pg_hba.conf entry ... no encryption.
Install the driver:
npm install pgRetrieve the Credentials and the CA Certificate
eval "$(exo dbaas show SERVICE_NAME -z ZONE -O json | jq -r '.pg.uri_params | "export PGHOST=\(.host) PGPORT=\(.port) PGDATABASE=\(.dbname) PGUSER=\(.user)"')"
export PGPASSWORD="$(exo dbaas user reveal-secrets SERVICE_NAME avnadmin -z ZONE -O json | jq -r .password)"
exo dbaas ca-certificate -z ZONE > ca.pem
export PGSSLROOTCERT="$PWD/ca.pem"Parameters:
SERVICE_NAME: name of your Managed PostgreSQL service, for examplemy-postgresql.ZONE: Exoscale zone the service runs in, for examplech-gva-2.
The JSON output of exo dbaas show does not include the password, which is why the second
command reads it with exo dbaas user reveal-secrets.
How TLS Works in node-postgres
pg does not use libpq. It takes a Node.js tls options object in its ssl setting. The
equivalents of the libpq SSL modes are:
libpq sslmode | ssl option in pg |
|---|---|
require | { rejectUnauthorized: false } |
verify-ca | { rejectUnauthorized: true, ca, checkServerIdentity: () => undefined } |
verify-full | { rejectUnauthorized: true, ca } |
With rejectUnauthorized: true and the CA certificate, Node.js also checks the hostname, which
is verify-full. Use it in production.
Connect
Save the following as index.js:
const fs = require("node:fs");
const { Client } = require("pg");
function requiredEnv(name) {
const value = process.env[name];
if (!value) {
throw new Error(`Environment variable ${name} is not set`);
}
return value;
}
const config = {
host: requiredEnv("PGHOST"),
port: Number(requiredEnv("PGPORT")),
database: requiredEnv("PGDATABASE"),
user: requiredEnv("PGUSER"),
password: requiredEnv("PGPASSWORD"),
application_name: "exoscale-nodejs-sample",
connectionTimeoutMillis: 10000,
ssl: {
rejectUnauthorized: true,
ca: fs.readFileSync(requiredEnv("PGSSLROOTCERT"), "utf8"),
},
};
async function main() {
const client = new Client(config);
await client.connect();
try {
const info = await client.query(
"SELECT version(), current_database(), current_user"
);
const row = info.rows[0];
console.log(`server: ${row.version}`);
console.log(`database: ${row.current_database}`);
console.log(`user: ${row.current_user}`);
const tls = await client.query(
"SELECT version, cipher FROM pg_stat_ssl WHERE pid = pg_backend_pid()"
);
console.log(`tls: ${tls.rows[0].version} ${tls.rows[0].cipher}`);
} finally {
await client.end();
}
}
main().catch((err) => {
console.error(err);
process.exit(1);
});Run it:
node index.jsIf PGSSLROOTCERT points to the wrong certificate, the connection fails with
self-signed certificate in certificate chain.
For an ES module project, replace the two require lines with import fs from "node:fs"; and
import pg from "pg";, followed by const { Client } = pg;.
Warning
Do not pass the service URI as connectionString. The sslmode in a connection string
replaces the ssl object passed next to it, so the ca setting is ignored. With the
?sslmode=require of the service URI, current pg 8 releases verify the certificate against
the system CAs and the connection fails with self-signed certificate in certificate chain.
With uselibpqcompat=true added to the URI, the certificate is not verified at all. Pass the
connection fields individually, as the sample does.
Use a Connection Pool
A web application should use Pool rather than Client, so that connections are reused across
requests. In index.js, keep the config object and replace the rest with:
const { Pool } = require("pg");
const pool = new Pool({ ...config, max: 10, idleTimeoutMillis: 30000 });
async function main() {
const { rows } = await pool.query("SELECT now()");
console.log(rows[0].now);
await pool.end();
}
main().catch((err) => {
console.error(err);
process.exit(1);
});Read the server limit with SHOW max_connections; and keep the sum of max across all your
application instances below it. In a serverless runtime, where each invocation can create its
own pool, use a server-side pool instead: see
Manage Connection Pools.