skip to content

How does a Cloudflare Worker query an existing PostgreSQL database through Hyperdrive, from creating the config to running a query?

level: juniorimportance: should knowfreq 32%

answer

  1. a config, then a binding
  2. wrangler hyperdrive create
  3. connection string from env
  4. new client per request
  5. local dev needs its own string

basics

~10 s

Create a Hyperdrive config with wrangler hyperdrive create and the database's connection string, bind its ID under hyperdrive in the Wrangler file, then pass env.HYPERDRIVE.connectionString to node-postgres or Postgres.js inside the handler.

solid answer

~40 s

First `wrangler hyperdrive create <name> --connection-string="postgres://user:password@host:5432/db"` registers the origin; Hyperdrive test-connects and returns a config ID. The Wrangler file binds that ID: `"hyperdrive": [{ "binding": "HYPERDRIVE", "id": "<id>" }]`. In the `fetch` handler you create a driver client from `env.HYPERDRIVE.connectionString` (node-postgres `new Client({ connectionString })` or `postgres(...)`) and query as usual; MySQL drivers take `host`, `user`, `password`, `database` and `port` from the same binding. The drivers need Node.js APIs, which are on by default for compatibility dates from 2026-08-04 and need `nodejs_compat` before that. For `wrangler dev` you also give a `localConnectionString` (or the `CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE` variable), because local mode connects straight to a database you choose.

code

bash · 3 lines
bash
npx wrangler hyperdrive create products-db --connection-string="postgres://app_user:[email protected]:5432/catalog"
export CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE="postgres://app_user:PASSWORD@localhost:5432/catalog"
npx wrangler dev

go deeper

for a junior

Recall the three pieces in order: wrangler hyperdrive create, the hyperdrive binding with its ID, and a driver client built from env.HYPERDRIVE.connectionString inside the handler.

for a middle

Explain that the binding hands out generated credentials while the real password stays in the config, and why local development needs its own connection string.

for a senior

Show you know the config is tested at creation, that TLS to the origin is mandatory, and that wrangler dev --remote writes to the real database.

for a principal

Frame Hyperdrive as the way to keep an existing regional database while moving compute to Workers, and say who owns the configs and their credentials.

## What Hyperdrive is in this picture **Hyperdrive** is a Cloudflare service that sits between a Worker and an existing **PostgreSQL** or **MySQL** database that lives somewhere else, for example in one cloud region. It pools connections near the database and can cache read results, but from the Worker's point of view it looks like an ordinary database server: your usual driver connects to it with a connection string. Wiring it up takes three pieces: 1. a **Hyperdrive config**, created once per origin database, which stores the real host, user and password; 2. a **binding** in the Wrangler file that gives the Worker access to that config as `env.HYPERDRIVE`; 3. a **driver client** created inside the handler from the binding's connection details. ## Step 1: create the config ```bash npx wrangler hyperdrive create products-db \ --connection-string="postgres://app_user:[email protected]:5432/catalog" ``` When you create or update a config, Hyperdrive makes a test connection and sends an empty test query. If that fails you get a numbered configuration error instead of a config, such as `2008` (bad hostname), `2009` (the host is not a public address), `2012` (the database does not offer TLS) or `2013` (invalid credentials). Hyperdrive always connects to the origin over TLS, so the database must accept TLS. On success Wrangler prints the new config's ID. The same command also accepts the parts separately (`--host`, `--port`, `--database`, `--user`, `--password`, `--scheme`), and `--binding` with `--update-config` can write the binding into your Wrangler file for you. ## Step 2: bind it ```json { "compatibility_date": "2026-10-10", "hyperdrive": [ { "binding": "HYPERDRIVE", "id": "<config id>" } ] } ``` The real database password is stored in the Hyperdrive config, not in the Worker. At run time the binding exposes: - `connectionString`, a ready-made string for drivers that accept one; - `host`, `port`, `user`, `password` and `database` for drivers that want the parts; the type definitions describe the `host` and `password` as generated values that are only valid inside the running Worker; - `connect()`, which returns a raw TCP socket to Hyperdrive for libraries that bring their own protocol code. ## Step 3: query from the handler ```javascript import { Client } from "pg"; export default { async fetch(request, env, ctx) { const client = new Client({ connectionString: env.HYPERDRIVE.connectionString }); await client.connect(); const { rows } = await client.query( "SELECT id, name, price FROM products WHERE category = $1 LIMIT 50", [new URL(request.url).searchParams.get("category")] ); return Response.json(rows); }, }; ``` Create the client **inside** the handler, never at module scope: Workers forbid I/O outside a handler, and Hyperdrive already makes a per-request client cheap. You do not need to call `client.end()`; the client is cleaned up when the invocation ends while Hyperdrive keeps its pooled connection to the database. With **Postgres.js** the call is `postgres(env.HYPERDRIVE.connectionString)`. For **MySQL**, the driver in Cloudflare's examples takes `host`, `user`, `password`, `database` and `port` from the binding and needs `disableEval: true`, because Workers do not allow the `eval()` code generation that driver uses by default. ## Node.js compatibility These drivers use Node.js APIs. For a **compatibility date of 2026-08-04 or later**, Node.js compatibility is on by default and nothing extra is needed. For an earlier date, add `"nodejs_compat"` to `compatibility_flags`; without it the import fails with an error like `No such module "node:<module>"`. The old `node_compat` setting was removed in Wrangler 4 and is not the fix. ## Local development | Mode | What the binding connects to | Pooling and caching | | --- | --- | --- | | `wrangler dev` (default) | the database in `localConnectionString` or `CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_<BINDING>` | not active | | `wrangler dev --remote` | the database in the deployed Hyperdrive config | active, against real data | Local `wrangler dev` refuses to start a Worker with a Hyperdrive binding until one of those local strings is set. The environment variable wins if both are present, and it keeps credentials out of the committed Wrangler file. The local string can point at a database on your machine or at a remote one over TLS (with `sslmode=require`). Because `--remote` runs against your production database, any write you make in that session is a real write. ## First-run problems and their causes - **`2009` or `2010` at create time**: the host is private or unreachable from the internet; a private database needs a tunnel. - **`2013` at create time**: wrong user or password in the connection string. - **`No such module "node:..."` at run time**: an older compatibility date without `nodejs_compat`. - **`Code generation from strings disallowed for this context`** with a MySQL driver: its `disableEval: true` option is missing. - **`Disallowed operation called within global scope`**: the client was connected outside the handler.

  • What does `wrangler dev` do when a Hyperdrive binding has no local connection string?
    It stops at startup with an error asking you to set `localConnectionString` on that binding or the `CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_<BINDING>` environment variable. Local mode does not reach the deployed Hyperdrive config at all; it connects your Worker directly to the database you name, so Hyperdrive's pooling and caching are absent locally. Use `wrangler dev --remote` to exercise them, knowing it runs against production data.
  • Why can a MySQL Worker not just use `env.HYPERDRIVE.connectionString` the same way?
    It can with drivers that parse one, but the MySQL driver in Cloudflare's examples takes `host`, `user`, `password`, `database` and `port` from the binding as separate options. It also needs `disableEval: true`, because by default that driver generates parsers with `eval()`, which Workers block with "Code generation from strings disallowed for this context".

  • A Hyperdrive binding exposes a query method, so no database driver is needed.
  • Store the origin database URL as a Worker secret and pass it to the driver; Hyperdrive changes nothing.
  • A Hyperdrive binding works under wrangler dev with no local connection string.
  • Setting node_compat = true is how a driver gets Node.js APIs in Wrangler 4.
  • Hyperdrive also speeds up D1, so every SQL store should sit behind it.

Assumes compatibility dates from 2026-08-04, where Node.js compatibility is on by default; earlier dates need the nodejs_compat flag for these drivers.