@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
mdx 628 lines 19.1 KB
Raw
1 ---
2 title: Hyperdrive
3 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.
4 ---
5
6 import { Tabs, TabItem } from "@astrojs/starlight/components";
7 import PackageManagers from "../../../../components/PackageManagers.astro";
8
9 export const pgDeps = `@alchemy.run/sql @effect/sql-pg`;
10 export const mysqlDeps = `@alchemy.run/sql @effect/sql-mysql2`;
11
12 Hyperdrive is a Cloudflare-managed connection pooler that sits
13 between Workers and an external Postgres or MySQL database. The
14 Worker sees a familiar connection string, but the connection itself
15 is already pooled at the edge — no per-request TCP handshakes, no
16 cold-start connection storms.
17
18 Reach for Hyperdrive whenever your app needs a real relational
19 database: managed Postgres/MySQL providers like Neon and
20 PlanetScale, or a database you already run — including one in a
21 [private network](/cloudflare/data/hyperdrive-private-database). (For serverless SQLite
22 inside Cloudflare, use [D1](/cloudflare/data/d1) instead.) This page
23 provisions a serverless database, fronts it with Hyperdrive, and
24 binds the connection into your Worker.
25
26 Three providers are wired up out of the box. Pick whichever you
27 prefer; the rest of the page follows your selection:
28
29 - **Neon** — serverless Postgres with copy-on-write branching.
30 - **PlanetScale (Postgres)** — managed Postgres with branch-per-PR
31 workflows.
32 - **PlanetScale (MySQL)** — Vitess-backed MySQL, same branching model.
33
34 ## Add the provider
35
36 Each database provider is its own `providers()` layer. Register it
37 alongside `Cloudflare.providers()` in your stack:
38
39 <Tabs syncKey="db-provider">
40 <TabItem label="Neon">
41
42 ```diff lang="typescript"
43 // alchemy.run.ts
44 import * as Alchemy from "alchemy";
45 import * as Cloudflare from "@alchemy.run/cloudflare";
46 +import * as Neon from "@alchemy.run/neon";
47 +import * as Layer from "effect/Layer";
48
49 export default Alchemy.Stack(
50 "MyStack",
51 {
52 - providers: Cloudflare.providers(),
53 + providers: Layer.mergeAll(Cloudflare.providers(), Neon.providers()),
54 state: Alchemy.localState(),
55 },
56 // ...
57 );
58 ```
59
60 Neon's auth is API-key-based. After this change,
61 `bun alchemy profile edit --add Neon` either reads `NEON_API_KEY`
62 from the environment (good for CI) or stores a key under
63 `~/.alchemy/credentials/<profile>/neon-stored.json`.
64
65 </TabItem>
66 <TabItem label="PlanetScale (Postgres)">
67
68 ```diff lang="typescript"
69 // alchemy.run.ts
70 import * as Alchemy from "alchemy";
71 import * as Cloudflare from "@alchemy.run/cloudflare";
72 +import * as Planetscale from "@alchemy.run/planetscale";
73 +import * as Layer from "effect/Layer";
74
75 export default Alchemy.Stack(
76 "MyStack",
77 {
78 - providers: Cloudflare.providers(),
79 + providers: Layer.mergeAll(Cloudflare.providers(), Planetscale.providers()),
80 state: Alchemy.localState(),
81 },
82 // ...
83 );
84 ```
85
86 PlanetScale's auth uses an API token id + secret.
87 `bun alchemy profile edit --add Planetscale` either reads `PLANETSCALE_API_TOKEN_ID`,
88 `PLANETSCALE_API_TOKEN`, and `PLANETSCALE_ORGANIZATION` from the
89 environment (good for CI) or stores the credentials under
90 `~/.alchemy/credentials/<profile>/planetscale-stored.json`.
91
92 </TabItem>
93 <TabItem label="PlanetScale (MySQL)">
94
95 ```diff lang="typescript"
96 // alchemy.run.ts
97 import * as Alchemy from "alchemy";
98 import * as Cloudflare from "@alchemy.run/cloudflare";
99 +import * as Planetscale from "@alchemy.run/planetscale";
100 +import * as Layer from "effect/Layer";
101
102 export default Alchemy.Stack(
103 "MyStack",
104 {
105 - providers: Cloudflare.providers(),
106 + providers: Layer.mergeAll(Cloudflare.providers(), Planetscale.providers()),
107 state: Alchemy.localState(),
108 },
109 // ...
110 );
111 ```
112
113 PlanetScale's auth uses an API token id + secret.
114 `bun alchemy profile edit --add Planetscale` either reads `PLANETSCALE_API_TOKEN_ID`,
115 `PLANETSCALE_API_TOKEN`, and `PLANETSCALE_ORGANIZATION` from the
116 environment (good for CI) or stores the credentials under
117 `~/.alchemy/credentials/<profile>/planetscale-stored.json`.
118
119 </TabItem>
120 </Tabs>
121
122 ## Provision the database
123
124 Create `src/Db.ts`. The shape is the same across providers — a
125 top-level database resource, a branch, and (for PlanetScale) a
126 credentials resource that owns the password.
127
128 <Tabs syncKey="db-provider">
129 <TabItem label="Neon">
130
131 A `Neon.Project` is the top-level container. It owns a default
132 branch, a default role, and the WAL history that copy-on-write
133 branches fork from:
134
135 ```typescript
136 // src/Db.ts
137 import * as Neon from "@alchemy.run/neon";
138 import * as Effect from "effect/Effect";
139
140 export const Db = Effect.gen(function* () {
141 const project = yield* Neon.Project("app-db", {
142 region: "aws-us-east-1",
143 });
144
145 const branch = yield* Neon.Branch("app-branch", {
146 project,
147 });
148
149 return { project, branch };
150 });
151 ```
152
153 `Neon.Branch` is a copy-on-write fork — cheap to create, fast to
154 destroy, and ideal for preview environments. Each branch has its
155 own connection string (`branch.connectionUri`) and a pooled variant
156 (`branch.pooledConnectionUri`).
157
158 </TabItem>
159 <TabItem label="PlanetScale (Postgres)">
160
161 A `Planetscale.PostgresDatabase` owns the long-lived cluster.
162 `PostgresBranch` is a branch off of it (cheap to fork for previews),
163 and `PostgresRole` materializes a user + password we can feed to
164 Hyperdrive:
165
166 ```typescript
167 // src/Db.ts
168 import * as Planetscale from "@alchemy.run/planetscale";
169 import * as Effect from "effect/Effect";
170
171 export const Db = Effect.gen(function* () {
172 const database = yield* Planetscale.PostgresDatabase("app-db", {
173 region: { slug: "us-east" },
174 clusterSize: "PS_10",
175 });
176
177 const branch = yield* Planetscale.PostgresBranch("app-branch", {
178 database,
179 isProduction: false,
180 });
181
182 const role = yield* Planetscale.PostgresRole("app-role", {
183 database,
184 branch,
185 inheritedRoles: ["postgres"],
186 });
187
188 return { database, branch, role };
189 });
190 ```
191
192 The role's `origin` (host / port / database / user / password) is
193 what Hyperdrive consumes — it's materialized lazily so the actual
194 password never lands in plan output.
195
196 </TabItem>
197 <TabItem label="PlanetScale (MySQL)">
198
199 A `Planetscale.MySQLDatabase` is the long-lived cluster.
200 `MySQLBranch` is a branch off of it (cheap to fork for previews),
201 and `MySQLPassword` materializes a user + password we can feed to
202 Hyperdrive:
203
204 ```typescript
205 // src/Db.ts
206 import * as Planetscale from "@alchemy.run/planetscale";
207 import * as Effect from "effect/Effect";
208
209 export const Db = Effect.gen(function* () {
210 const database = yield* Planetscale.MySQLDatabase("app-db", {
211 region: { slug: "us-east" },
212 clusterSize: "PS_10",
213 allowForeignKeyConstraints: true,
214 });
215
216 const branch = yield* Planetscale.MySQLBranch("app-branch", {
217 database,
218 isProduction: false,
219 });
220
221 const password = yield* Planetscale.MySQLPassword("app-password", {
222 database,
223 branch,
224 role: "readwriter",
225 });
226
227 return { database, branch, password };
228 });
229 ```
230
231 The password's `origin` (host / port / database / user / password)
232 is what Hyperdrive consumes — it's materialized lazily so the
233 actual secret never lands in plan output.
234
235 </TabItem>
236 </Tabs>
237
238 ## Put Hyperdrive in front
239
240 Hyperdrive needs an `origin` describing where your database lives.
241 Each provider exposes a pre-parsed `origin` output (`{ scheme, host,
242 port, database, user, password }`) ready to feed straight in:
243
244 <Tabs syncKey="db-provider">
245 <TabItem label="Neon">
246
247 ```diff lang="typescript"
248 // src/Db.ts
249 +import * as Cloudflare from "@alchemy.run/cloudflare";
250 import * as Neon from "@alchemy.run/neon";
251 import * as Effect from "effect/Effect";
252
253 export const Db = Effect.gen(function* () {
254 const project = yield* Neon.Project("app-db", { region: "aws-us-east-1" });
255 const branch = yield* Neon.Branch("app-branch", { project });
256 return { project, branch };
257 });
258
259 +export const Hyperdrive = Effect.gen(function* () {
260 + const { branch } = yield* Db;
261 + return yield* Cloudflare.Hyperdrive.Connection("app-hyperdrive", {
262 + origin: branch.origin,
263 + });
264 +});
265 ```
266
267 `branch.origin` points at the **direct** (non-pooled) Neon endpoint —
268 the recommended target when sitting behind Hyperdrive, since
269 Hyperdrive already does its own connection pooling.
270
271 </TabItem>
272 <TabItem label="PlanetScale (Postgres)">
273
274 ```diff lang="typescript"
275 // src/Db.ts
276 +import * as Cloudflare from "@alchemy.run/cloudflare";
277 import * as Planetscale from "@alchemy.run/planetscale";
278 import * as Effect from "effect/Effect";
279
280 export const Db = Effect.gen(function* () {
281 // ...
282 return { database, branch, role };
283 });
284
285 +export const Hyperdrive = Effect.gen(function* () {
286 + const { role } = yield* Db;
287 + return yield* Cloudflare.Hyperdrive.Connection("app-hyperdrive", {
288 + origin: role.origin,
289 + });
290 +});
291 ```
292
293 `role.origin` is the connection target Hyperdrive will pool. The
294 `origin` is an `Output`, so alchemy orders PostgresDatabase →
295 PostgresBranch → PostgresRole → Hyperdrive on the deploy graph.
296
297 </TabItem>
298 <TabItem label="PlanetScale (MySQL)">
299
300 ```diff lang="typescript"
301 // src/Db.ts
302 +import * as Cloudflare from "@alchemy.run/cloudflare";
303 import * as Planetscale from "@alchemy.run/planetscale";
304 import * as Effect from "effect/Effect";
305
306 export const Db = Effect.gen(function* () {
307 // ...
308 return { database, branch, password };
309 });
310
311 +export const Hyperdrive = Effect.gen(function* () {
312 + const { password } = yield* Db;
313 + return yield* Cloudflare.Hyperdrive.Connection("app-hyperdrive", {
314 + origin: password.origin,
315 + });
316 +});
317 ```
318
319 `password.origin` is the connection target Hyperdrive will pool —
320 its `scheme` is `"mysql"`, so Hyperdrive provisions a MySQL pooler.
321 The `origin` is an `Output`, so alchemy orders MySQLDatabase →
322 MySQLBranch → MySQLPassword → Hyperdrive on the deploy graph.
323
324 </TabItem>
325 </Tabs>
326
327 ## Dev mode and the pooled origin
328
329 In `bun alchemy dev`, alchemy doesn't create a Hyperdrive config at
330 all — the local Worker gets a connection string that points straight
331 at the database. With Hyperdrive out of the path, nothing pools
332 those local connections, so point the `dev` override at the
333 provider's **own** pooled endpoint instead:
334
335 <Tabs syncKey="db-provider">
336 <TabItem label="Neon">
337
338 ```diff lang="typescript"
339 // src/Db.ts
340 export const Hyperdrive = Effect.gen(function* () {
341 const { branch } = yield* Db;
342 return yield* Cloudflare.Hyperdrive.Connection("app-hyperdrive", {
343 origin: branch.origin,
344 + dev: branch.pooledOrigin,
345 });
346 });
347 ```
348
349 `branch.pooledOrigin` is the same connection parsed against Neon's
350 pgbouncer endpoint (the raw URI is `branch.pooledConnectionUri`).
351 Deployed Workers still go through Hyperdrive at the direct endpoint;
352 local dev goes through Neon's pooler.
353
354 </TabItem>
355 <TabItem label="PlanetScale (Postgres)">
356
357 ```diff lang="typescript"
358 // src/Db.ts
359 export const Hyperdrive = Effect.gen(function* () {
360 const { role } = yield* Db;
361 return yield* Cloudflare.Hyperdrive.Connection("app-hyperdrive", {
362 origin: role.origin,
363 + dev: role.pooledOrigin,
364 });
365 });
366 ```
367
368 `role.pooledOrigin` targets PSBouncer on port 6432 — the direct
369 `role.origin` uses 5432 — and the raw pooled URL is available as
370 `role.connectionUrlPooled`. Deployed Workers still go through
371 Hyperdrive at the direct endpoint; local dev goes through
372 PlanetScale's pooler.
373
374 </TabItem>
375 <TabItem label="PlanetScale (MySQL)">
376
377 `MySQLPassword` has no pooled variant — when `dev` is omitted the
378 binding falls back to `password.origin` automatically, so there is
379 nothing to add. Set `dev` only when local dev should hit a
380 *different* database, e.g. a MySQL running on `localhost`.
381
382 </TabItem>
383 </Tabs>
384
385 The pooled endpoint is also the right target when Hyperdrive isn't
386 in the picture at all. A Hyperdrive connection string only exists
387 inside a deployed Worker — the binding resolves it at runtime — so
388 anything else that talks to the database (CI jobs, a container,
389 `psql` on your laptop) should connect to the pooled URI directly:
390 `branch.pooledConnectionUri` on Neon, `role.connectionUrlPooled` on
391 PlanetScale. For a container that means passing the pooled URI in as
392 an environment variable — see
393 [Connect to a SQL database](/cloudflare/compute/containers#connect-to-a-sql-database).
394 Just don't do the reverse — `origin` deliberately
395 points Hyperdrive at the *direct* endpoint, because Hyperdrive
396 already pools, and stacking it on top of the provider's pooler
397 means two poolers fighting over the same connections.
398
399 ## Install the client library
400
401 The Worker queries Hyperdrive with Effect SQL. Install the driver that
402 matches your engine:
403
404 <Tabs syncKey="db-provider">
405 <TabItem label="Neon">
406
407 [`@effect/sql-pg`](https://github.com/Effect-TS/effect-smol/tree/main/packages/sql/pg) — Effect's native Postgres driver:
408
409 <PackageManagers add={pgDeps} />
410
411 </TabItem>
412 <TabItem label="PlanetScale (Postgres)">
413
414 [`@effect/sql-pg`](https://github.com/Effect-TS/effect-smol/tree/main/packages/sql/pg) — Effect's native Postgres driver:
415
416 <PackageManagers add={pgDeps} />
417
418 </TabItem>
419 <TabItem label="PlanetScale (MySQL)">
420
421 [`@effect/sql-mysql2`](https://github.com/Effect-TS/effect-smol/tree/main/packages/sql/mysql2) — Effect's MySQL client:
422
423 <PackageManagers add={mysqlDeps} />
424
425 </TabItem>
426 </Tabs>
427
428 ## Bind Hyperdrive to your Worker
429
430 `Cloudflare.Hyperdrive.Connect(...)` returns a typed accessor for the
431 runtime binding — connection string, host, port, user, password,
432 database — plus a `raw` escape hatch for libraries that want the
433 underlying `Hyperdrive` object. Pass its `connectionString` to Effect SQL:
434
435 <Tabs syncKey="db-provider">
436 <TabItem label="Neon">
437
438 ```diff lang="typescript"
439 // src/Api.ts
440 import * as Cloudflare from "@alchemy.run/cloudflare";
441 +import * as SQL from "@alchemy.run/sql/Postgres";
442 import * as Effect from "effect/Effect";
443 import * as HttpServerResponse from "effect/http/HttpServerResponse";
444 +import { Hyperdrive } from "./Db.ts";
445
446 export default class Api extends Cloudflare.Worker<Api>()(
447 "Api",
448 {
449 main: import.meta.url,
450 + compatibility: {
451 + // The driver opens its socket through Node's `net` and `tls` APIs.
452 + flags: ["nodejs_compat"],
453 + },
454 },
455 Effect.gen(function* () {
456 + const hd = yield* Cloudflare.Hyperdrive.Connect(Hyperdrive);
457 + const sql = yield* SQL.Postgres({ url: hd.connectionString });
458 +
459 return {
460 fetch: Effect.gen(function* () {
461 + const rows = yield* sql`SELECT now() AS now`;
462 + return yield* HttpServerResponse.json({ ok: true, rows });
463 }),
464 };
465 - }),
466 + }).pipe(Effect.provide(Cloudflare.Hyperdrive.ConnectBinding)),
467 ) {}
468 ```
469
470 </TabItem>
471 <TabItem label="PlanetScale (Postgres)">
472
473 ```diff lang="typescript"
474 // src/Api.ts
475 import * as Cloudflare from "@alchemy.run/cloudflare";
476 +import * as SQL from "@alchemy.run/sql/Postgres";
477 import * as Effect from "effect/Effect";
478 import * as HttpServerResponse from "effect/http/HttpServerResponse";
479 +import { Hyperdrive } from "./Db.ts";
480
481 export default class Api extends Cloudflare.Worker<Api>()(
482 "Api",
483 {
484 main: import.meta.url,
485 + compatibility: {
486 + // The driver opens its socket through Node's `net` and `tls` APIs.
487 + flags: ["nodejs_compat"],
488 + },
489 },
490 Effect.gen(function* () {
491 + const hd = yield* Cloudflare.Hyperdrive.Connect(Hyperdrive);
492 + const sql = yield* SQL.Postgres({ url: hd.connectionString });
493 +
494 return {
495 fetch: Effect.gen(function* () {
496 + const rows = yield* sql`SELECT now() AS now`;
497 + return yield* HttpServerResponse.json({ ok: true, rows });
498 }),
499 };
500 - }),
501 + }).pipe(Effect.provide(Cloudflare.Hyperdrive.ConnectBinding)),
502 ) {}
503 ```
504
505 </TabItem>
506 <TabItem label="PlanetScale (MySQL)">
507
508 ```diff lang="typescript"
509 // src/Api.ts
510 import * as Cloudflare from "@alchemy.run/cloudflare";
511 +import * as SQL from "@alchemy.run/sql/MySQL";
512 import * as Effect from "effect/Effect";
513 import * as HttpServerResponse from "effect/http/HttpServerResponse";
514 +import { Hyperdrive } from "./Db.ts";
515
516 export default class Api extends Cloudflare.Worker<Api>()(
517 "Api",
518 {
519 main: import.meta.url,
520 + compatibility: {
521 + // The driver opens its socket through Node's `net` and `tls` APIs.
522 + flags: ["nodejs_compat"],
523 + },
524 },
525 Effect.gen(function* () {
526 + const hd = yield* Cloudflare.Hyperdrive.Connect(Hyperdrive);
527 + const sql = yield* SQL.MySQL({ url: hd.connectionString });
528 +
529 return {
530 fetch: Effect.gen(function* () {
531 + const rows = yield* sql`SELECT NOW() AS now`;
532 + return yield* HttpServerResponse.json({ ok: true, rows });
533 }),
534 };
535 - }),
536 + }).pipe(Effect.provide(Cloudflare.Hyperdrive.ConnectBinding)),
537 ) {}
538 ```
539
540 </TabItem>
541 </Tabs>
542
543 `SQL.Postgres` and `SQL.MySQL` open a pool lazily inside each request's
544 [scope](/sql/effect-sql/lifecycle) and close it when the request ends.
545 Hyperdrive does the pooling on Cloudflare's side, so the Worker never
546 retains sockets across requests. The [Postgres](/sql/effect-sql/postgres)
547 and [MySQL](/sql/effect-sql/mysql) client guides cover queries, typed
548 errors, and transactions; [Drizzle](/cloudflare/data/drizzle) adds typed
549 schemas on the same connection.
550
551 ## Wire the resources into the stack
552
553 Update `alchemy.run.ts` to yield `Db` and `Hyperdrive` so they
554 become part of the deploy graph:
555
556 ```diff lang="typescript"
557 // alchemy.run.ts
558 import Api from "./src/Api.ts";
559 +import { Db, Hyperdrive } from "./src/Db.ts";
560
561 export default Alchemy.Stack(
562 "MyStack",
563 { /* ... */ },
564 Effect.gen(function* () {
565 + yield* Db;
566 + yield* Hyperdrive;
567 const api = yield* Api;
568 return { url: api.url.as<string>() };
569 }),
570 );
571 ```
572
573 ## Deploy
574
575 ```sh
576 bun alchemy deploy
577 ```
578
579 Watch the deploy plan: alchemy creates the database, then the
580 branch, then the credentials (for PlanetScale), then the Hyperdrive
581 that points at the connection origin, then the Worker with the
582 Hyperdrive binding attached. After it completes, hit your Worker
583 URL and you should see something like:
584
585 ```json
586 { "ok": true, "rows": [{ "now": "2026-05-04T07:53:48.123Z" }] }
587 ```
588
589 You're now talking to your database from the edge through
590 Hyperdrive.
591
592 ## Workers defaults
593
594 `SQL.MySQL` and `Drizzle.MySQL` disable prepared statements and mysql2's eval-based
595 row parsers when running in workerd. Hyperdrive's MySQL proxy uses the text
596 protocol, and Workers prohibit runtime JavaScript compilation.
597
598 ```typescript
599 const sql = yield* SQL.MySQL({
600 url: connection.connectionString,
601 disablePreparedStatements: true,
602 poolConfig: { disableEval: true },
603 });
604 ```
605
606 These are detected defaults, not required boilerplate. Explicit configuration
607 wins; direct connections outside workerd retain prepared statements and normal
608 parsers by default. The adapter parses URL fields and query parameters into the
609 driver configuration so `poolConfig` options reach mysql2.
610
611 ## Where next
612
613 Guides that build on Hyperdrive:
614
615 - [Private database (Workers VPC)](/cloudflare/data/hyperdrive-private-database)
616 — reach a database with no public endpoint, such as Aurora in an
617 AWS VPC, through a Cloudflare Tunnel.
618 - [Add Drizzle ORM](/cloudflare/data/drizzle) — add typed
619 schemas and alchemy-managed migrations.
620 - [Shared database across stages](/cloudflare/data/shared-database)
621 — point PR-preview stages at one long-lived database.
622 - [Branch from a shared database](/cloudflare/data/branch-from-shared-database)
623 — copy-on-write branches per preview stage.
624
625 Database integrations:
626
627 - [PlanetScale](/planetscale)
628 - [Neon](/neon)