Connect and query

Create and bind a Hyperdrive configuration

Connect Cloudflare to a database, expose the binding to one Worker, and keep origin credentials out of source.

A Hyperdrive configuration is the object that sits between your Worker and your database. You create it once, from the database connection details. Cloudflare checks it can reach the origin and hands you back an ID. That ID is what your Worker binds to.

The database password never has to appear in your project. Keep the connection string in an environment variable on your machine:

export DATABASE_URL="postgres://app_worker:[email protected]:5432/appdb?sslmode=require"

Create the configuration without putting the database password in source:

npx wrangler hyperdrive create app-db --connection-string "$DATABASE_URL"
npx wrangler hyperdrive get app-db

Copy only the returned binding ID into project configuration. Store the origin credential through the supported secret path. Connect from a local or preview environment first, then verify which database, role, and network path the binding actually reaches.

The create command prints the new configuration, including its id. That’s the value that goes in wrangler.jsonc:

{
  "compatibility_flags": ["nodejs_compat"],
  "hyperdrive": [
    { "binding": "HYPERDRIVE", "id": "57b7076f58be42419276f058a8968187" }
  ]
}

nodejs_compat is required because database drivers use Node.js APIs. Then run npx wrangler types so env.HYPERDRIVE shows up typed in your editor.

What the Worker sees

Inside the Worker, env.HYPERDRIVE.connectionString is a connection string Cloudflare generates for the pool. It is not your origin password. Your code hands it to the driver and never learns the real credential. That’s the point: the secret lives in the Hyperdrive configuration, not in source and not in a Worker secret.

The role matters as much as the string

Hyperdrive connects as whatever user is in the connection string. If that’s your admin login, every Worker request runs with admin power. Create a dedicated role with only the privileges the app needs. A later lesson covers how narrow that role should be.

When create fails

The common failure: wrangler hyperdrive create reports it can’t connect to the origin. Cloudflare has to reach your database from its own network, so a database that only accepts connections from your office IP will reject it. Fix the allow-list, or use a Cloudflare Tunnel if the database has no public address. The other common cause is a password with @ or # in it that wasn’t percent-encoded.

Try this before you run any write query: create a practice configuration, connect from wrangler dev, and run select current_user, current_database(). The answer tells you which role and which database the binding reaches. If it says postgres, stop and fix the role.

Lesson completed