Updated Nov 19, 20268 min read

How to Connect Node.js to Amazon RDS for PostgreSQL

Add Postgres to a Node.js, Express or NestJS app on AWS: the pg pool, TLS against the RDS certificate bundle, credentials from Secrets Manager, pool sizing, and the same database declared in TypeScript with Encore.

Illustration for How to Connect Node.js to Amazon RDS for PostgreSQL

To connect a Node.js app to Amazon RDS for PostgreSQL, use a pg Pool with the RDS endpoint, verify the server with ssl: { ca, rejectUnauthorized: true } and the RDS certificate bundle, inject the password from Secrets Manager, and allow port 5432 only from the app's security group. If you would rather not set that up by hand, Encore declares the database in TypeScript, starts Postgres locally under encore run, and provisions RDS in your own AWS account on deploy. The steps below work the same for Express, Fastify, NestJS or plain Node.js.

Adding Postgres to a Node.js app on your laptop takes a minute. On AWS it takes an RDS instance in private subnets, a security group rule, a secret, a certificate bundle the app trusts, and a pool size that does not exhaust max_connections when the service scales out.

What are the ways to add Postgres to a Node.js app on AWS?

RankApproachWhat you set upLocal developmentBest for
1Encore SQLDatabaseOne declaration in TypeScript; Encore provisions RDS, the network and a role per serviceencore run starts Postgres locally with migrations appliedTypeScript backends where the database should ship with the code that uses it
2pg + RDS you provisionRDS instance, subnet group, security groups, secret, CA bundle, pool settingsA local Postgres you run yourselfExisting Express or NestJS apps with infrastructure already in Terraform or CDK
3ORM (Prisma, Drizzle, TypeORM) + RDS you provisionSame as above, with the ORM's connection settingsSame as aboveTeams that already standardized on an ORM
4RDS Proxy in front of RDSEverything above plus a proxy and its IAM roleNot available locallyLambda functions or many short-lived connections

Package versions looked up on November 19, 2026: pg 8.23.1 and encore.dev 1.58.9.

How do you add RDS PostgreSQL to a Node.js app with Encore?

Encore

Encore brings infrastructure from code, so the database is a declaration in the service that uses it rather than an RDS resource in a separate Terraform module. Encore reads the declaration, starts Postgres locally with your migrations, and on deploy provisions Amazon RDS for PostgreSQL in your own AWS account, in private subnets that only accept connections from your compute, with each service getting its own database role.

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create shop --example=ts/empty$ cd shop && mkdir -p orders/migrations
// orders/encore.service.ts import { Service } from "encore.dev/service"; export default new Service("orders");
// orders/orders.ts import { api, APIError } from "encore.dev/api"; import { getAuthData } from "~encore/auth"; import { SQLDatabase } from "encore.dev/storage/sqldb"; // A local Postgres under encore run, RDS for PostgreSQL on AWS. const db = new SQLDatabase("orders", { migrations: "./migrations" }); interface Order { id: number; customerEmail: string; totalCents: number; } export const create = api( { expose: true, auth: true, method: "POST", path: "/orders" }, async (req: { customerEmail: string; totalCents: number }): Promise<Order> => { const { userID } = getAuthData()!; const row = await db.queryRow<Order>` INSERT INTO orders (user_id, customer_email, total_cents) VALUES (${userID}, ${req.customerEmail}, ${req.totalCents}) RETURNING id, customer_email AS "customerEmail", total_cents AS "totalCents"`; return row!; }, ); export const get = api( { expose: true, auth: true, method: "GET", path: "/orders/:id" }, async ({ id }: { id: number }): Promise<Order> => { const { userID } = getAuthData()!; const row = await db.queryRow<Order>` SELECT id, customer_email AS "customerEmail", total_cents AS "totalCents" FROM orders WHERE id = ${id} AND user_id = ${userID}`; if (!row) throw APIError.notFound("order not found"); return row; }, );
-- orders/migrations/1_create_orders.up.sql CREATE TABLE orders ( id BIGSERIAL PRIMARY KEY, user_id TEXT NOT NULL, customer_email TEXT NOT NULL, total_cents INTEGER NOT NULL CHECK (total_cents >= 0), created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() );

Both endpoints require a signed-in caller. The auth handler runs first, getAuthData() returns the user id, and lookups include that owner so a sequential order id does not expose another customer's email:

// auth/auth.ts import { createHmac, timingSafeEqual } from "node:crypto"; import { APIError, Gateway, Header } from "encore.dev/api"; import { authHandler } from "encore.dev/auth"; import { secret } from "encore.dev/config"; const tokenKey = secret("AuthTokenKey"); interface AuthParams { authorization: Header<"Authorization">; } interface AuthData { userID: string; } export const auth = authHandler<AuthParams, AuthData>(async ({ authorization }) => { const [userID, exp, sig] = (authorization ?? "").replace(/^Bearer /, "").split("."); if (!userID || !exp || !sig || Number(exp) < Date.now() / 1000) { throw APIError.unauthenticated("invalid token"); } const want = createHmac("sha256", tokenKey()).update(`${userID}.${exp}`).digest("hex"); if (sig.length !== want.length || !timingSafeEqual(Buffer.from(sig), Buffer.from(want))) { throw APIError.unauthenticated("invalid token"); } return { userID }; }); export const gateway = new Gateway({ authHandler: auth });

encore run starts Postgres locally, applies the migration and serves the two endpoints, and encore db shell orders opens psql against the local database. The queries use tagged templates, so values are sent as parameters rather than spliced into SQL. On deploy, Encore creates the RDS instance (or an Aurora PostgreSQL cluster, chosen when you create the environment), runs migrations through a proxy inside your environment so the database is never exposed, and Encore provisions an IAM role for the service. Instance class, storage and backups are set per environment in the infrastructure configuration, not in the code.

If the database already exists, Encore can connect to an existing RDS instance instead of creating one. For a coding agent, the useful part is that adding a table or a second database is a change to the service code and a migration file, which the agent can run against a real local Postgres before the pull request exists.

Best fit: TypeScript backends on AWS where the database should be declared with the service that uses it and work the same locally and in production.

How do you connect Node.js to RDS by hand with pg?

Install the driver and download the RDS certificate bundle, which the app uses to verify that it is talking to your RDS instance:

~/app
$ npm install pg$ npm install --save-dev @types/pg$ curl -o certs/rds-global-bundle.pem https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem

Then create one pool per process and share it:

// db.ts import fs from "node:fs"; import { Pool } from "pg"; export const pool = new Pool({ host: process.env.DB_HOST, // e.g. orders.abc123.eu-central-1.rds.amazonaws.com port: 5432, database: process.env.DB_NAME, user: process.env.DB_USER, password: process.env.DB_PASSWORD, max: 10, idleTimeoutMillis: 30_000, connectionTimeoutMillis: 5_000, ssl: { ca: fs.readFileSync("certs/rds-global-bundle.pem", "utf8"), rejectUnauthorized: true, }, }); export async function getOrder(id: number) { const { rows } = await pool.query( "SELECT id, customer_email, total_cents FROM orders WHERE id = $1", [id], ); return rows[0] ?? null; } process.on("SIGTERM", () => { void pool.end(); });

With rejectUnauthorized: true and the bundle as ca, Node checks both the certificate chain and the hostname, which is the equivalent of sslmode=verify-full. Keep sslmode out of the connection string when you pass an ssl object, so one place decides how TLS is verified (the node-postgres SSL docs cover the options). RDS for PostgreSQL 15 and later rejects unencrypted connections by default, so a missing ssl setting shows up as a no pg_hba.conf entry ... no encryption error.

In Express or NestJS, import pool (or wrap it in a provider) rather than creating a pool per request. The SIGTERM handler lets ECS stop the task without leaving connections half-closed.

Where should the password come from?

Keep it out of the repository and the image, and on ECS reference the secret in the task definition so the ECS agent injects it as an environment variable when the task starts. With an RDS-managed master secret, the valueFrom can select the JSON key directly, as described in the ECS secrets docs:

"secrets": [ { "name": "DB_PASSWORD", "valueFrom": "arn:aws:secretsmanager:eu-central-1:123456789012:secret:rds!db-1a2b3c4d-AbCdEf:password::" } ]

The task execution role needs secretsmanager:GetSecretValue on that secret. The network side, with private subnets and a database security group that allows 5432 only from the service's security group, is covered step by step in how to connect ECS Fargate to RDS. To avoid passwords altogether, RDS IAM authentication swaps them for short-lived tokens.

How big should the pool be?

RDS sets max_connections from instance memory, so a db.t4g.micro allows far fewer connections than a db.r7g.large (the formula is in the RDS quotas docs). Multiply the pool max by the number of tasks at peak scale, leave room for migrations and admin sessions, and stay under the limit. Lambda functions are the usual way to blow through it, as each concurrent instance holds its own pool, which is where RDS Proxy earns its cost.

How do you run migrations?

Run them as a separate step before the new code starts, not from every replica at boot. A one-off ECS task running a tool such as node-pg-migrate or your ORM's migrate command works, with the same secret and network access as the app.

Which approach should you pick?

  • Encore for a TypeScript backend where you want the database declared in the service, running locally under encore run, and provisioned in your own AWS account on deploy.
  • pg with RDS you provision for an existing Express or NestJS app whose infrastructure already lives in Terraform or CDK.
  • An ORM on the same setup if the team already uses Prisma, Drizzle or TypeORM; the TLS, secret and pool rules above still apply.
  • RDS Proxy in front of either when Lambda or bursty workloads open many short-lived connections.

Frequently asked questions

How do I connect Node.js to an RDS PostgreSQL database?

Install pg, create a Pool with the RDS endpoint, database name, user and password, and pass ssl: { ca, rejectUnauthorized: true } with the RDS global certificate bundle so the connection is encrypted and the server is verified. Run the app in the same VPC as the database, allow port 5432 from the app's security group only, and inject the password from Secrets Manager rather than committing it.

Does RDS for PostgreSQL require SSL?

Yes. On PostgreSQL 15 and later the rds.force_ssl parameter defaults to 1, so plain-text connections are rejected; on 14 and older it defaults to 0 and you set it in a custom parameter group.

How many connections should a Node.js pool open to RDS?

Multiply the pool max by the number of tasks or Lambda instances and stay well below the instance's max_connections, which RDS derives from instance memory. A max of 10 per process is a reasonable start for an API on a small instance.

Can I add Postgres to a Node.js app on AWS without setting up RDS by hand?

Yes. With Encore you declare new SQLDatabase('orders', { migrations: './migrations' }) in TypeScript; encore run starts Postgres locally with the migrations applied, and on deploy Encore provisions Amazon RDS for PostgreSQL in your own AWS account with a database role per service, so there is no connection string or password in your code.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders