How do I connect a Cloudflare Worker to PostgreSQL?
Worked Answer
Use node-postgres (pg) with nodejs_compat enabled in wrangler.toml, then point Client({ connectionString: env.HYPERDRIVE.connectionString }) at a Cloudflare Hyperdrive binding so edge requests reuse warm pooled connections instead of opening a new TCP + TLS handshake per request.
Follow one request from a Cloudflare Worker to PostgreSQL. Run a parameterized query with pg, then switch from a direct TCP connection to Hyperdrive to eliminate cold-start connection overhead.
Packages
pg@cloudflare/workers-typesWhat happens on one request
A Worker executes in an isolate near the user, while your PostgreSQL instance lives in a single region. Opening a fresh TCP + TLS + Postgres auth handshake on every Worker invocation adds 80–250 ms and exhausts max_connections during traffic spikes. Hyperdrive terminates TLS at Cloudflare's edge and maintains a warm connection pool close to your database.
Direct pg connection vs. Cloudflare Hyperdrive
Toggle between a direct connection string and a Hyperdrive binding to see which setup steps change.
Requires nodejs_compat in wrangler.toml and a publicly reachable Postgres host. Opens a new TCP connection per request—use only for low-traffic prototypes.
import { Client } from 'pg';
export default {
async fetch(request, env) {
const client = new Client({ connectionString: env.DATABASE_URL });
await client.connect();
try {
const { rows } = await client.query(
'SELECT id, name, plan FROM accounts WHERE id = $1',
[new URL(request.url).searchParams.get('id')]
);
return Response.json(rows[0] ?? null);
} finally {
await client.end();
}
},
};Direct TCP vs. Hyperdrive Pooler
| Approach | Strengths | Tradeoffs |
|---|---|---|
| Direct pg from Worker | Zero extra Cloudflare resource; works with any Postgres host | Full TCP + TLS + SCRAM handshake per request; easily exhausts max_connections |
| Cloudflare Hyperdrive | Edge TLS termination, warm regional connection pool, optional query caching | Requires wrangler hyperdrive create binding and transaction-mode pooling semantics |
When switching a Cloudflare Worker from a direct pg connection to Hyperdrive, what changes in your parameterized SQL query?
Production Evidence & Architecture Guides
Official Sources
Want this architecture built for your team?
Fixed-scope engineering sprints for databases, AI agents, and production retrieval.