Square CloudSquare Cloud

How to connect PostgreSQL to Node.js (pg and Prisma)

Install pg, create a single Pool per process with the URL read from an environment variable, and use parameterized queries ($1, $2). For TLS, pass the server's CA in the ssl object; with Prisma, the same options go to the @prisma/adapter-pg adapter.

Updated 8 min read

Learning objectives

After reading this article you will be able to:

  • Connect with pg using one pool per process and the URL in an environment variable
  • Configure TLS with the server's CA and a client certificate, without turning verification off
  • Use Prisma with the pg driver adapter and close connections cleanly
On this page

Connecting Node.js to PostgreSQL takes a few lines, and most production problems start in them: a new pool on every request, the password hardcoded in the source, a rejectUnauthorized: false copied from an old answer. This guide builds the connection the way that survives real traffic, first with pg (node-postgres) and then with Prisma, which uses pg underneath.

The examples use ESM and async/await. If you are still choosing between a driver and an ORM, see which Node.js ORM to use.

What do you need before you start?#

  • Node.js installed and a project with "type": "module" in package.json.
  • A PostgreSQL server reachable over the network, with a username, password and database name.
  • If the server requires TLS with its own certificate authority (CA), the CA file and, when it asks for a client certificate, the client certificate and key.
bash
npm install pg

The connection URL follows the format postgresql://user:password@host:5432/database. Reserved characters in the password (@, :, /, #) need percent-encoding: encodeURIComponent("p@ss") returns p%40ss. Keep the URL in an environment variable, never in the code. In development, a .env file outside Git is enough, and Node loads it without an extra package:

bash
node --env-file=.env index.js

The reasoning behind keeping config out of code is in what environment variables are.

How do you connect with pg using a pool?#

A pool opens a few connections and lends them to your code. Create one per process, in its own module: Node caches modules, so every file that imports db.js gets the same pool.

javascript
// db.js
import { readFileSync } from "node:fs";
import { Pool } from "pg";

if (!process.env.DATABASE_URL) throw new Error("Set DATABASE_URL");

export const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 5, // connection ceiling for THIS process
  idleTimeoutMillis: 30_000,
  connectionTimeoutMillis: 5_000, // fail instead of waiting forever
  ssl: {
    ca: readFileSync("certs/ca.pem"), // server CA
    cert: readFileSync("certs/client-cert.pem"), // client certificate
    key: readFileSync("certs/client-key.pem"), // client key
  },
});

// An idle connection that drops emits an error on the pool; with no listener, the process exits.
pool.on("error", (err) => {
  console.error("Error on an idle PostgreSQL connection:", err);
});

If the server doesn't ask for a client certificate, remove cert and key and keep only ca.

Now the queries, always with parameters ($1, $2) instead of string concatenation:

javascript
// users.js
import { pool } from "./db.js";

export async function findByEmail(email) {
  const { rows } = await pool.query(
    "SELECT id, name FROM users WHERE email = $1",
    [email],
  );
  return rows[0] ?? null;
}

pg sends the value separately from the SQL, and the server never parses it as a command. That is what stops SQL injection. Parameters work for values, not for table or column names: for those, check against a fixed list of allowed names.

For a transaction, check out a client with pool.connect(), run BEGIN and COMMIT on it and give it back with client.release() in a finally block. Don't run a transaction through pool.query, because each call can land on a different connection.

How big should the pool be?#

Node runs your code on a single thread, and a connection is busy only while its query runs. A max of 5 to 10 per process is usually enough. The number that matters is the sum: every process (cluster worker, replica, another app on the same database) has its own pool. Four processes with max: 5 can open 20 connections. If the sum goes over the server's limit, you get the error explained in 'too many connections'.

How do you set up TLS with a CA and a client certificate?#

The ssl object in pg goes straight to Node's TLS socket. With it filled in, Node checks the server certificate chain against the ca you passed and also checks the host name. That is the equivalent of libpq's sslmode=verify-full, the mode the PostgreSQL documentation recommends.

Three habits prevent most errors:

  1. Keep TLS parameters out of the URL. The pg documentation warns that sslmode, sslrootcert, sslcert or sslkey in the connection string replace the whole ssl object, and your options are lost. A forgotten ?sslmode=require in the URL makes pg ignore your ca.
  2. Don't turn verification off. rejectUnauthorized: false makes the certificate error go away because it accepts any server, including an impostor in the middle. The fix is passing the right CA.
  3. One .pem with both parts works. If the client certificate and key come in the same file, read that file into both cert and key: Node finds each part inside it.

Certificate and key files are secrets, like the password: put the certs/ folder in .gitignore. If the error is self-signed certificate in certificate chain, the full diagnosis is in the self-signed certificate error when connecting to a database.

How do you use Prisma with PostgreSQL?#

The examples use the Prisma ORM 7 line, with schema.prisma, prisma generate and a driver adapter. Without a version, npm install prisma may install a different line with a different API. Pin the major in the commands and check the lines on Prisma's release status page:

bash
npm install @prisma/client@7 @prisma/adapter-pg@7 pg dotenv
npm install --save-dev prisma@7 tsx typescript @types/node @types/pg
npx prisma init --datasource-provider postgresql --output ../generated/prisma

The prisma CLI usually goes in devDependencies. If your server generates the client during install, it has to be in dependencies.

init creates prisma/schema.prisma, a .env and the config file: prisma7.config.ts in newer releases of the 7 line, prisma.config.ts in earlier ones. The 7 line's CLI accepts both names; edit the one your project already has. The URL lives in that file, no longer in the schema:

typescript
// prisma7.config.ts (or prisma.config.ts)
import "dotenv/config";
import { defineConfig } from "prisma/config";

export default defineConfig({
  schema: "prisma/schema.prisma",
  migrations: { path: "prisma/migrations" },
  datasource: { url: process.env["DATABASE_URL"] },
});

Add a model to the prisma/schema.prisma that init generated:

prisma
generator client {
  provider = "prisma-client"
  output   = "../generated/prisma"
}

datasource db {
  provider = "postgresql"
}

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
}
bash
npx prisma migrate dev --name init
npx prisma generate

The client takes the adapter, and the adapter accepts the same options as pg's Pool, including max and ssl:

typescript
// db.ts
import "dotenv/config";
import { readFileSync } from "node:fs";
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "./generated/prisma/client";

const adapter = new PrismaPg({
  connectionString: process.env.DATABASE_URL,
  max: 5,
  ssl: {
    ca: readFileSync("certs/ca.pem"),
    cert: readFileSync("certs/client-cert.pem"),
    key: readFileSync("certs/client-key.pem"),
  },
});

export const prisma = new PrismaClient({ adapter });
typescript
// script.ts
import { prisma } from "./db";

const ana = await prisma.user.upsert({
  where: { email: "ana@example.com" },
  update: {},
  create: { email: "ana@example.com", name: "Ana" },
});
console.log(ana);

const email = "ana@example.com";
const rows = await prisma.$queryRaw`SELECT id FROM "User" WHERE email = ${email}`;
console.log(rows);

await prisma.$disconnect();

Run it with npx tsx script.ts; the production options are in how to run TypeScript in production. $queryRaw as a tagged template sends ${email} as a parameter; $queryRawUnsafe builds the string and brings the injection risk back.

The CLI (prisma migrate, prisma db push) doesn't go through the adapter: it reads the URL from datasource.url in the config file, and the adapter's ssl options don't apply to it. The PostgreSQL page in the 7 line's docs only shows sslmode and sslcert in that URL and doesn't say how the CLI presents a client certificate. If your server requires one, check that page for the version you use and test migrate against a rehearsal database before relying on it. If you put TLS parameters in the CLI's URL, give it its own variable (MIGRATE_DATABASE_URL, for example) and keep the app's DATABASE_URL clean: pg would read those parameters and replace the ssl object.

How do you close connections without losing queries?#

Whatever stops the process (the OS, a service manager, your host) usually sends SIGTERM; Ctrl+C sends SIGINT. Stop taking new work, wait for the requests in flight, and only then close the pool:

javascript
// index.js
import http from "node:http";
import { pool } from "./db.js";

const server = http.createServer(async (_req, res) => {
  try {
    const { rows } = await pool.query("SELECT now() AS now");
    res.end(JSON.stringify(rows[0]));
  } catch (err) {
    console.error(err);
    res.statusCode = 500;
    res.end();
  }
});
server.listen(Number(process.env.PORT ?? 3000), "0.0.0.0");

function shutdown() {
  // stop accepting connections; the callback runs once open requests finish
  server.close(async () => {
    await pool.end(); // close the database connections
    process.exit(0);
  });
}
process.once("SIGTERM", shutdown);
process.once("SIGINT", shutdown);

With Prisma, swap pool.end() for await prisma.$disconnect(). In a bot, the counterpart of server.close() is disconnecting from the chat service before closing the database.

Which errors show up most often?#

text
Error: connect ECONNREFUSED 127.0.0.1:5432
error: password authentication failed for user "app"
Error: self-signed certificate in certificate chain
error: no pg_hba.conf entry for host "203.0.113.7", user "app", database "app", no encryption
error: sorry, too many clients already
Error: timeout exceeded when trying to connect
Message Likely cause Fix
ECONNREFUSED 127.0.0.1:5432 The client is trying localhost: the URL points there, or the variable never reached the process and pg used its default Check that the variable exists in the process and what host it holds
password authentication failed Wrong user or password, or a special character left unencoded Encode the password with encodeURIComponent
self-signed certificate in certificate chain Node doesn't know the server's CA, or an sslmode in the URL wiped your ssl Pass ca and remove TLS parameters from the URL
no pg_hba.conf entry ... no encryption The server requires TLS and the client connected without it Fill in the ssl object
too many clients already The sum of all pools went over the server's limit Lower max or the number of processes
timeout exceeded when trying to connect Pool exhausted by connections never released, or database unreachable release() in finally and check the network

If the connection is refused even with the right URL, follow the checklist in ECONNREFUSED on the database.

How to do this on Square Cloud#

PostgreSQL hosting on Square Cloud starts on the Standard plan, from R$44.99 per month. You create the database in the dashboard (name and memory, from 1024 MB), and it is ready in seconds in the same datacenter as your applications, with an average latency of about 1 ms. PostgreSQL ships with the pgvector and pg_cron extensions.

  1. Copy the full connection URL, shown once at creation (resetting the password shows it again), into the application's DATABASE_URL variable, in the dashboard, the API, the CLI or VS Code. The URL isn't added to your variables on its own, and the change applies on the next restart.
  2. Download the certificate in the dashboard. TLS is mandatory: the client trusts the downloaded CA and, on PostgreSQL, also presents the .pem. In the ssl object, the CA goes in ca and the .pem in cert and key, as in the TLS section. Don't swap this for rejectUnauthorized: false.
  3. Put the files in the application, in the ZIP or through the dashboard's file manager. The disk is persistent, and a new commit overwrites only the files it contains, so certificates kept out of Git are still there after a GitHub deploy.
  4. Size the pool: each database accepts up to 256 connections, with no pooler in front, so the sum of max across every process and application using the database has to fit under that ceiling.

At start, the platform runs npm install when there is no node_modules, with NODE_ENV=production: devDependencies are skipped and there is no build step, but postinstall runs and environment variables already exist during install. With Prisma, one option is keeping prisma (on major 7) in dependencies and generating the client in postinstall, with "postinstall": "prisma generate". The TypeScript runtime runs the .ts file directly, with tsx. Limits and plans on PostgreSQL hosting.

Database hosting

MongoDB, PostgreSQL, MySQL and Redis next to your app

PostgreSQL hosting

FAQs

Should I use Client or Pool in pg?

For APIs, bots and servers, use Pool: it reuses connections and hands each one back when the query ends. Client makes sense in short scripts that open one connection, do the work and exit.

Can I use rejectUnauthorized: false to fix the certificate error?

No. That option turns off server verification and leaves the connection open to a man-in-the-middle attack. Pass the server's CA in ssl.ca so verification works.

How many connections does the pg pool open by default?

Up to 10, set by the max option. The pool starts empty, opens connections on demand and closes the ones that sit idle for 10 seconds (idleTimeoutMillis).

Why does Prisma need an adapter to connect to PostgreSQL?

In the Prisma ORM 7 line, Prisma Client talks to relational databases through a driver adapter. @prisma/adapter-pg uses pg underneath, so pool size and TLS follow pg's options.

Next articleHow to connect PostgreSQL to Python (psycopg and SQLAlchemy)Connect Python to PostgreSQL with psycopg or SQLAlchemy: one pool per process, the URL in an environment variable, TLS with verify-full and %s query parameters.

More in Databases

See all 32 articles