Back to Learning Hub
Databases and scalingbuild Last tested 2026-11-27

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.

How do I connect a Cloudflare Worker to PostgreSQL? architecture flow diagram

Packages

pg@cloudflare/workers-types

What 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.

Code Walkthrough

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

ApproachStrengthsTradeoffs
Direct pg from WorkerZero extra Cloudflare resource; works with any Postgres hostFull TCP + TLS + SCRAM handshake per request; easily exhausts max_connections
Cloudflare HyperdriveEdge TLS termination, warm regional connection pool, optional query cachingRequires wrangler hyperdrive create binding and transaction-mode pooling semantics
Checkpoint

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

Next Lesson
How many PostgreSQL connections does my API need?

Want this architecture built for your team?

Fixed-scope engineering sprints for databases, AI agents, and production retrieval.

Mugesh Rao
AI Engineer & Full Stack Engineer