Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

20.2 KB
Raw Blame
---
title: Hyperdrive
description: Cloudflare Hyperdrive pools connections to your external Postgres or MySQL database at the edge — provision a database (Neon or PlanetScale), front it with Hyperdrive, and bind the connection into your Worker.
---

import { Code, Tabs, TabItem } from "@astrojs/starlight/components";

export const pgDeps = `pg`;
export const pgDevDeps = `@types/pg`;
export const mysqlDeps = `mysql2`;

Hyperdrive is a Cloudflare-managed connection pooler that sits
between Workers and an external Postgres or MySQL database. The
Worker sees a familiar connection string, but the connection itself
is already pooled at the edge — no per-request TCP handshakes, no
cold-start connection storms.

Reach for Hyperdrive whenever your app needs a real relational
database: managed Postgres/MySQL providers like Neon and
PlanetScale, or a database you already run. (For serverless SQLite
inside Cloudflare, use [D1](/cloudflare/data/d1) instead.) This page
provisions a serverless database, fronts it with Hyperdrive, and
binds the connection into your Worker.

Three providers are wired up out of the box. Pick whichever you
prefer; the rest of the page follows your selection:

- **Neon** — serverless Postgres with copy-on-write branching.
- **PlanetScale (Postgres)** — managed Postgres with branch-per-PR
  workflows.
- **PlanetScale (MySQL)** — Vitess-backed MySQL, same branching model.

## Add the provider

Each database provider is its own `providers()` layer. Register it
alongside `Cloudflare.providers()` in your stack:

<Tabs syncKey="db-provider">
  <TabItem label="Neon">

```diff lang="typescript"
// alchemy.run.ts
import * as Alchemy from "alchemy";
import * as Cloudflare from "alchemy/Cloudflare";
+import * as Neon from "alchemy/Neon";
+import * as Layer from "effect/Layer";

export default Alchemy.Stack(
  "MyStack",
  {
-    providers: Cloudflare.providers(),
+    providers: Layer.mergeAll(Cloudflare.providers(), Neon.providers()),
    state: Alchemy.localState(),
  },
  // ...
);
```

Neon's auth is API-key-based. The first `bun alchemy login` after
this change adds a `Neon` step that either reads `NEON_API_KEY`
from the environment (good for CI) or stores a key under
`~/.alchemy/credentials/<profile>/neon-stored.json`.

  </TabItem>
  <TabItem label="PlanetScale (Postgres)">

```diff lang="typescript"
// alchemy.run.ts
import * as Alchemy from "alchemy";
import * as Cloudflare from "alchemy/Cloudflare";
+import * as Planetscale from "alchemy/Planetscale";
+import * as Layer from "effect/Layer";

export default Alchemy.Stack(
  "MyStack",
  {
-    providers: Cloudflare.providers(),
+    providers: Layer.mergeAll(Cloudflare.providers(), Planetscale.providers()),
    state: Alchemy.localState(),
  },
  // ...
);
```

PlanetScale's auth uses an API token id + secret. `bun alchemy login`
adds a `Planetscale` step that either reads `PLANETSCALE_API_TOKEN_ID`,
`PLANETSCALE_API_TOKEN`, and `PLANETSCALE_ORGANIZATION` from the
environment (good for CI) or stores the credentials under
`~/.alchemy/credentials/<profile>/planetscale-stored.json`.

  </TabItem>
  <TabItem label="PlanetScale (MySQL)">

```diff lang="typescript"
// alchemy.run.ts
import * as Alchemy from "alchemy";
import * as Cloudflare from "alchemy/Cloudflare";
+import * as Planetscale from "alchemy/Planetscale";
+import * as Layer from "effect/Layer";

export default Alchemy.Stack(
  "MyStack",
  {
-    providers: Cloudflare.providers(),
+    providers: Layer.mergeAll(Cloudflare.providers(), Planetscale.providers()),
    state: Alchemy.localState(),
  },
  // ...
);
```

PlanetScale's auth uses an API token id + secret. `bun alchemy login`
adds a `Planetscale` step that either reads `PLANETSCALE_API_TOKEN_ID`,
`PLANETSCALE_API_TOKEN`, and `PLANETSCALE_ORGANIZATION` from the
environment (good for CI) or stores the credentials under
`~/.alchemy/credentials/<profile>/planetscale-stored.json`.

  </TabItem>
</Tabs>

## Provision the database

Create `src/Db.ts`. The shape is the same across providers — a
top-level database resource, a branch, and (for PlanetScale) a
credentials resource that owns the password.

<Tabs syncKey="db-provider">
  <TabItem label="Neon">

A `Neon.Project` is the top-level container. It owns a default
branch, a default role, and the WAL history that copy-on-write
branches fork from:

```typescript
// src/Db.ts
import * as Neon from "alchemy/Neon";
import * as Effect from "effect/Effect";

export const Db = Effect.gen(function* () {
  const project = yield* Neon.Project("app-db", {
    region: "aws-us-east-1",
  });

  const branch = yield* Neon.Branch("app-branch", {
    project,
  });

  return { project, branch };
});
```

`Neon.Branch` is a copy-on-write fork — cheap to create, fast to
destroy, and ideal for preview environments. Each branch has its
own connection string (`branch.connectionUri`) and a pooled variant
(`branch.pooledConnectionUri`).

  </TabItem>
  <TabItem label="PlanetScale (Postgres)">

A `Planetscale.PostgresDatabase` owns the long-lived cluster.
`PostgresBranch` is a branch off of it (cheap to fork for previews),
and `PostgresRole` materializes a user + password we can feed to
Hyperdrive:

```typescript
// src/Db.ts
import * as Planetscale from "alchemy/Planetscale";
import * as Effect from "effect/Effect";

export const Db = Effect.gen(function* () {
  const database = yield* Planetscale.PostgresDatabase("app-db", {
    region: { slug: "us-east" },
    clusterSize: "PS_10",
  });

  const branch = yield* Planetscale.PostgresBranch("app-branch", {
    database,
    isProduction: false,
  });

  const role = yield* Planetscale.PostgresRole("app-role", {
    database,
    branch,
    inheritedRoles: ["postgres"],
  });

  return { database, branch, role };
});
```

The role's `origin` (host / port / database / user / password) is
what Hyperdrive consumes — it's materialized lazily so the actual
password never lands in plan output.

  </TabItem>
  <TabItem label="PlanetScale (MySQL)">

A `Planetscale.MySQLDatabase` is the long-lived cluster.
`MySQLBranch` is a branch off of it (cheap to fork for previews),
and `MySQLPassword` materializes a user + password we can feed to
Hyperdrive:

```typescript
// src/Db.ts
import * as Planetscale from "alchemy/Planetscale";
import * as Effect from "effect/Effect";

export const Db = Effect.gen(function* () {
  const database = yield* Planetscale.MySQLDatabase("app-db", {
    region: { slug: "us-east" },
    clusterSize: "PS_10",
    allowForeignKeyConstraints: true,
  });

  const branch = yield* Planetscale.MySQLBranch("app-branch", {
    database,
    isProduction: false,
  });

  const password = yield* Planetscale.MySQLPassword("app-password", {
    database,
    branch,
    role: "readwriter",
  });

  return { database, branch, password };
});
```

The password's `origin` (host / port / database / user / password)
is what Hyperdrive consumes — it's materialized lazily so the
actual secret never lands in plan output.

  </TabItem>
</Tabs>

## Put Hyperdrive in front

Hyperdrive needs an `origin` describing where your database lives.
Each provider exposes a pre-parsed `origin` output (`{ scheme, host,
port, database, user, password }`) ready to feed straight in:

<Tabs syncKey="db-provider">
  <TabItem label="Neon">

```diff lang="typescript"
// src/Db.ts
+import * as Cloudflare from "alchemy/Cloudflare";
import * as Neon from "alchemy/Neon";
import * as Effect from "effect/Effect";

export const Db = Effect.gen(function* () {
  const project = yield* Neon.Project("app-db", { region: "aws-us-east-1" });
  const branch = yield* Neon.Branch("app-branch", { project });
  return { project, branch };
});

+export const Hyperdrive = Effect.gen(function* () {
+  const { branch } = yield* Db;
+  return yield* Cloudflare.Hyperdrive.Connection("app-hyperdrive", {
+    origin: branch.origin,
+  });
+});
```

`branch.origin` points at the **direct** (non-pooled) Neon endpoint —
the recommended target when sitting behind Hyperdrive, since
Hyperdrive already does its own connection pooling.

  </TabItem>
  <TabItem label="PlanetScale (Postgres)">

```diff lang="typescript"
// src/Db.ts
+import * as Cloudflare from "alchemy/Cloudflare";
import * as Planetscale from "alchemy/Planetscale";
import * as Effect from "effect/Effect";

export const Db = Effect.gen(function* () {
  // ...
  return { database, branch, role };
});

+export const Hyperdrive = Effect.gen(function* () {
+  const { role } = yield* Db;
+  return yield* Cloudflare.Hyperdrive.Connection("app-hyperdrive", {
+    origin: role.origin,
+  });
+});
```

`role.origin` is the connection target Hyperdrive will pool. The
`origin` is an `Output`, so alchemy orders PostgresDatabase →
PostgresBranch → PostgresRole → Hyperdrive on the deploy graph.

  </TabItem>
  <TabItem label="PlanetScale (MySQL)">

```diff lang="typescript"
// src/Db.ts
+import * as Cloudflare from "alchemy/Cloudflare";
import * as Planetscale from "alchemy/Planetscale";
import * as Effect from "effect/Effect";

export const Db = Effect.gen(function* () {
  // ...
  return { database, branch, password };
});

+export const Hyperdrive = Effect.gen(function* () {
+  const { password } = yield* Db;
+  return yield* Cloudflare.Hyperdrive.Connection("app-hyperdrive", {
+    origin: password.origin,
+  });
+});
```

`password.origin` is the connection target Hyperdrive will pool —
its `scheme` is `"mysql"`, so Hyperdrive provisions a MySQL pooler.
The `origin` is an `Output`, so alchemy orders MySQLDatabase →
MySQLBranch → MySQLPassword → Hyperdrive on the deploy graph.

  </TabItem>
</Tabs>

## Dev mode and the pooled origin

In `bun alchemy dev`, alchemy doesn't create a Hyperdrive config at
all — the local Worker gets a connection string that points straight
at the database. With Hyperdrive out of the path, nothing pools
those local connections, so point the `dev` override at the
provider's **own** pooled endpoint instead:

<Tabs syncKey="db-provider">
  <TabItem label="Neon">

```diff lang="typescript"
// src/Db.ts
export const Hyperdrive = Effect.gen(function* () {
  const { branch } = yield* Db;
  return yield* Cloudflare.Hyperdrive.Connection("app-hyperdrive", {
    origin: branch.origin,
+    dev: branch.pooledOrigin,
  });
});
```

`branch.pooledOrigin` is the same connection parsed against Neon's
pgbouncer endpoint (the raw URI is `branch.pooledConnectionUri`).
Deployed Workers still go through Hyperdrive at the direct endpoint;
local dev goes through Neon's pooler.

  </TabItem>
  <TabItem label="PlanetScale (Postgres)">

```diff lang="typescript"
// src/Db.ts
export const Hyperdrive = Effect.gen(function* () {
  const { role } = yield* Db;
  return yield* Cloudflare.Hyperdrive.Connection("app-hyperdrive", {
    origin: role.origin,
+    dev: role.pooledOrigin,
  });
});
```

`role.pooledOrigin` targets PSBouncer on port 6432 — the direct
`role.origin` uses 5432 — and the raw pooled URL is available as
`role.connectionUrlPooled`. Deployed Workers still go through
Hyperdrive at the direct endpoint; local dev goes through
PlanetScale's pooler.

  </TabItem>
  <TabItem label="PlanetScale (MySQL)">

`MySQLPassword` has no pooled variant — when `dev` is omitted the
binding falls back to `password.origin` automatically, so there is
nothing to add. Set `dev` only when local dev should hit a
*different* database, e.g. a MySQL running on `localhost`.

  </TabItem>
</Tabs>

The pooled endpoint is also the right target when Hyperdrive isn't
in the picture at all. A Hyperdrive connection string only exists
inside a deployed Worker — the binding resolves it at runtime — so
anything else that talks to the database (CI jobs, a container,
`psql` on your laptop) should connect to the pooled URI directly:
`branch.pooledConnectionUri` on Neon, `role.connectionUrlPooled` on
PlanetScale. Just don't do the reverse — `origin` deliberately
points Hyperdrive at the *direct* endpoint, because Hyperdrive
already pools, and stacking it on top of the provider's pooler
means two poolers fighting over the same connections.

## Install the client library

The Worker uses a Node-compatible driver to talk to Hyperdrive over
the binding. Pick the one that matches your engine:

<Tabs syncKey="db-provider">
  <TabItem label="Neon">

[`pg`](https://node-postgres.com) — node-postgres:

<Tabs syncKey="pkgManager">
  <TabItem label="bun" icon="bun">
    <Code code={`bun add ${pgDeps}\nbun add -d ${pgDevDeps}`} lang="sh" />
  </TabItem>
  <TabItem label="npm" icon="npm">
    <Code code={`npm install ${pgDeps}\nnpm install -D ${pgDevDeps}`} lang="sh" />
  </TabItem>
  <TabItem label="pnpm" icon="pnpm">
    <Code code={`pnpm add ${pgDeps}\npnpm add -D ${pgDevDeps}`} lang="sh" />
  </TabItem>
  <TabItem label="yarn" icon="seti:yarn">
    <Code code={`yarn add ${pgDeps}\nyarn add -D ${pgDevDeps}`} lang="sh" />
  </TabItem>
</Tabs>

  </TabItem>
  <TabItem label="PlanetScale (Postgres)">

[`pg`](https://node-postgres.com) — node-postgres:

<Tabs syncKey="pkgManager">
  <TabItem label="bun" icon="bun">
    <Code code={`bun add ${pgDeps}\nbun add -d ${pgDevDeps}`} lang="sh" />
  </TabItem>
  <TabItem label="npm" icon="npm">
    <Code code={`npm install ${pgDeps}\nnpm install -D ${pgDevDeps}`} lang="sh" />
  </TabItem>
  <TabItem label="pnpm" icon="pnpm">
    <Code code={`pnpm add ${pgDeps}\npnpm add -D ${pgDevDeps}`} lang="sh" />
  </TabItem>
  <TabItem label="yarn" icon="seti:yarn">
    <Code code={`yarn add ${pgDeps}\nyarn add -D ${pgDevDeps}`} lang="sh" />
  </TabItem>
</Tabs>

  </TabItem>
  <TabItem label="PlanetScale (MySQL)">

[`mysql2`](https://github.com/sidorares/node-mysql2):

<Tabs syncKey="pkgManager">
  <TabItem label="bun" icon="bun">
    <Code code={`bun add ${mysqlDeps}`} lang="sh" />
  </TabItem>
  <TabItem label="npm" icon="npm">
    <Code code={`npm install ${mysqlDeps}`} lang="sh" />
  </TabItem>
  <TabItem label="pnpm" icon="pnpm">
    <Code code={`pnpm add ${mysqlDeps}`} lang="sh" />
  </TabItem>
  <TabItem label="yarn" icon="seti:yarn">
    <Code code={`yarn add ${mysqlDeps}`} lang="sh" />
  </TabItem>
</Tabs>

  </TabItem>
</Tabs>

## Bind Hyperdrive to your Worker

`Cloudflare.Hyperdrive.Connect(...)` returns a typed accessor for the
runtime binding — connection string, host, port, user, password,
database — plus a `raw` escape hatch for libraries that want the
underlying `Hyperdrive` object:

<Tabs syncKey="db-provider">
  <TabItem label="Neon">

```diff lang="typescript"
// src/Api.ts
import * as Cloudflare from "alchemy/Cloudflare";
import * as Effect from "effect/Effect";
+import * as Redacted from "effect/Redacted";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
+import { Client } from "pg";
+import { Hyperdrive } from "./Db.ts";

export default class Api extends Cloudflare.Worker<Api>()(
  "Api",
  {
    main: import.meta.url,
+    compatibility: {
+      // node-postgres needs Node.js APIs to run inside a Worker.
+      flags: ["nodejs_compat"],
+    },
  },
  Effect.gen(function* () {
+    const hd = yield* Cloudflare.Hyperdrive.Connect(Hyperdrive);
+
    return {
      fetch: Effect.gen(function* () {
+        const connectionString = Redacted.value(yield* hd.connectionString);
+        const rows = yield* Effect.promise(async () => {
+          // One client per request — Hyperdrive does the pooling.
+          const client = new Client({ connectionString });
+          await client.connect();
+          try {
+            const r = await client.query("SELECT now() as now");
+            return r.rows;
+          } finally {
+            await client.end().catch(() => {});
+          }
+        });
+        return yield* HttpServerResponse.json({ ok: true, rows });
      }),
    };
-  }),
+  }).pipe(Effect.provide(Cloudflare.Hyperdrive.ConnectBinding)),
) {}
```

  </TabItem>
  <TabItem label="PlanetScale (Postgres)">

```diff lang="typescript"
// src/Api.ts
import * as Cloudflare from "alchemy/Cloudflare";
import * as Effect from "effect/Effect";
+import * as Redacted from "effect/Redacted";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
+import { Client } from "pg";
+import { Hyperdrive } from "./Db.ts";

export default class Api extends Cloudflare.Worker<Api>()(
  "Api",
  {
    main: import.meta.url,
+    compatibility: {
+      // node-postgres needs Node.js APIs to run inside a Worker.
+      flags: ["nodejs_compat"],
+    },
  },
  Effect.gen(function* () {
+    const hd = yield* Cloudflare.Hyperdrive.Connect(Hyperdrive);
+
    return {
      fetch: Effect.gen(function* () {
+        const connectionString = Redacted.value(yield* hd.connectionString);
+        const rows = yield* Effect.promise(async () => {
+          // One client per request — Hyperdrive does the pooling.
+          const client = new Client({ connectionString });
+          await client.connect();
+          try {
+            const r = await client.query("SELECT now() as now");
+            return r.rows;
+          } finally {
+            await client.end().catch(() => {});
+          }
+        });
+        return yield* HttpServerResponse.json({ ok: true, rows });
      }),
    };
-  }),
+  }).pipe(Effect.provide(Cloudflare.Hyperdrive.ConnectBinding)),
) {}
```

  </TabItem>
  <TabItem label="PlanetScale (MySQL)">

```diff lang="typescript"
// src/Api.ts
import * as Cloudflare from "alchemy/Cloudflare";
import * as Effect from "effect/Effect";
+import * as Redacted from "effect/Redacted";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
+import { createConnection } from "mysql2/promise";
+import { Hyperdrive } from "./Db.ts";

export default class Api extends Cloudflare.Worker<Api>()(
  "Api",
  {
    main: import.meta.url,
+    compatibility: {
+      // mysql2 needs Node.js APIs to run inside a Worker.
+      flags: ["nodejs_compat"],
+    },
  },
  Effect.gen(function* () {
+    const hd = yield* Cloudflare.Hyperdrive.Connect(Hyperdrive);
+
    return {
      fetch: Effect.gen(function* () {
+        const connectionString = Redacted.value(yield* hd.connectionString);
+        const rows = yield* Effect.promise(async () => {
+          // One connection per request — Hyperdrive does the pooling.
+          const conn = await createConnection(connectionString);
+          try {
+            const [r] = await conn.query("SELECT NOW() as now");
+            return r;
+          } finally {
+            await conn.end().catch(() => {});
+          }
+        });
+        return yield* HttpServerResponse.json({ ok: true, rows });
      }),
    };
-  }),
+  }).pipe(Effect.provide(Cloudflare.Hyperdrive.ConnectBinding)),
) {}
```

  </TabItem>
</Tabs>

Two things to notice (regardless of engine):

- The `nodejs_compat` flag is required because the driver uses
  Node's `net` and `crypto` APIs.
- The fetch handler opens a fresh connection per request and ends
  it on the way out. This is intentional — Hyperdrive does the
  pooling on Cloudflare's side, so the Worker doesn't need its
  own. (The [Drizzle guide](/cloudflare/data/drizzle) revisits
  this when we want long-lived clients.)

## Wire the resources into the stack

Update `alchemy.run.ts` to yield `Db` and `Hyperdrive` so they
become part of the deploy graph:

```diff lang="typescript"
// alchemy.run.ts
import Api from "./src/Api.ts";
+import { Db, Hyperdrive } from "./src/Db.ts";

export default Alchemy.Stack(
  "MyStack",
  { /* ... */ },
  Effect.gen(function* () {
+    yield* Db;
+    yield* Hyperdrive;
    const api = yield* Api;
    return { url: api.url.as<string>() };
  }),
);
```

## Deploy

```sh
bun alchemy deploy
```

Watch the deploy plan: alchemy creates the database, then the
branch, then the credentials (for PlanetScale), then the Hyperdrive
that points at the connection origin, then the Worker with the
Hyperdrive binding attached. After it completes, hit your Worker
URL and you should see something like:

```json
{ "ok": true, "rows": [{ "now": "2026-05-04T07:53:48.123Z" }] }
```

You're now talking to your database from the edge through
Hyperdrive.

## Where next

Guides that build on Hyperdrive:

- [Add Drizzle ORM](/cloudflare/data/drizzle) — swap the raw
  driver for typed schemas and alchemy-managed migrations.
- [Shared database across stages](/cloudflare/data/shared-database)
  — point PR-preview stages at one long-lived database.
- [Branch from a shared database](/cloudflare/data/branch-from-shared-database)
  — copy-on-write branches per preview stage.

Database integrations:

- [PlanetScale](/planetscale)
- [Neon](/neon)