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

main
mdx 633 lines 20.5 KB
Raw
1 ---
2 title: Effect HTTP API
3 description: Build a schema-validated HTTP API with Effect's HttpApi module and deploy it as a Cloudflare Worker.
4 sidebar:
5 order: 3
6 ---
7
8 Effect HTTP is the trust-boundary modality: schema-validated REST
9 endpoints — real URLs, path params, query strings, payloads — that
10 any HTTP client can call, no Effect or TypeScript required on the
11 consumer's side. This page deploys one to a Cloudflare Worker; the
12 concept home is [Effect HTTP](/apis/effect-http), and
13 [RPC](/apis) covers choosing between the modalities.
14
15 In the [tutorial](/cloudflare/tutorial/part-2), you built a Worker with manual
16 `if/else` routing and raw request parsing. That works, but as your
17 API grows you lose type safety at the boundary — request payloads
18 aren't validated, response shapes aren't enforced, and errors slip
19 through untyped.
20
21 Effect's `HttpApi` module solves this. You declare endpoints with
22 schemas for payloads, responses, and errors, then implement handlers
23 against those schemas. The result is an `HttpEffect` — the same type
24 a Worker's `fetch` expects — so it plugs in directly.
25
26 The mental model we'll follow is:
27
28 1. **Define the schema and API outside the Worker.** Both are pure
29 descriptions and can be imported by clients.
30 2. **Construct the service inside the Worker's Construction phase.**
31 The Construction phase runs at plan time *and* runtime, so we only do
32 pure construction here — we never `yield*` something that needs
33 a request to exist.
34 3. **Return `{ fetch }`** where `fetch` is an `HttpEffect` produced
35 by `HttpRouter.toHttpEffect`. That's the value Workers invoke on
36 every request.
37 4. **Bonus:** deploy, grab the URL, and call the API from a fully
38 typed client.
39
40 ## 1. Define the schema
41
42 Start with a domain model. The schema lives outside the Worker so
43 the same file can be imported by clients without pulling in any
44 runtime code.
45
46 ```typescript
47 // src/task.ts
48 import * as Schema from "effect/Schema";
49
50 export class Task extends Schema.Class<Task>("Task")({
51 id: Schema.String,
52 title: Schema.String,
53 completed: Schema.Boolean,
54 }) {}
55
56 export class TaskNotFound extends Schema.TaggedError<TaskNotFound>()(
57 "TaskNotFound",
58 { id: Schema.String },
59 { httpApiStatus: 404 },
60 ) {}
61 ```
62
63 `Schema.Class` gives you a runtime-validated class with an inferred
64 TypeScript type. `Schema.TaggedError` gives you a typed error you
65 can return from handlers and discriminate against on the client —
66 `httpApiStatus: 404` maps it to a 404 response instead of a generic 500.
67
68 ## 2. Declare the API
69
70 Endpoints are declarations — they describe `(method, path,
71 params, payload, success, error)` without implementing anything yet. Putting
72 them in their own file keeps the spec importable from both the
73 server *and* a typed client.
74
75 ```typescript
76 // src/api.ts
77 import * as Schema from "effect/Schema";
78 import * as HttpApi from "effect/http-api/HttpApi";
79 import * as HttpApiEndpoint from "effect/http-api/HttpApiEndpoint";
80 import * as HttpApiGroup from "effect/http-api/HttpApiGroup";
81 import { Task, TaskNotFound } from "./task.ts";
82
83 export const decodeTask = Schema.decodeUnknownEffect(Task);
84 export const encodeTask = Schema.encodeUnknownSync(Task);
85
86 const TaskParams = Schema.Struct({
87 id: Schema.String,
88 });
89
90 const getTask = HttpApiEndpoint.get("getTask", "/:id", {
91 params: TaskParams,
92 success: Task,
93 error: TaskNotFound,
94 });
95
96 const createTask = HttpApiEndpoint.post("createTask", "/", {
97 success: Task,
98 payload: Schema.Struct({
99 title: Schema.String,
100 }),
101 });
102
103 export class TasksGroup extends HttpApiGroup.make("Tasks")
104 .add(getTask)
105 .add(createTask) {}
106
107 export class TaskApi extends HttpApi.make("TaskApi").add(TasksGroup) {}
108 ```
109
110 Nothing executes yet — `TaskApi` is purely a value-level description.
111 The same `TaskApi` constant is what we'll hand to the client at the
112 end of this guide.
113
114 ## 3. Build the Worker
115
116 Now we wire it up. Create `src/worker.ts` with an empty Construction phase:
117
118 ```typescript
119 // src/worker.ts
120 import * as Cloudflare from "@alchemy.run/cloudflare";
121 import * as Effect from "effect/Effect";
122
123 export default Cloudflare.Worker(
124 "Worker",
125 { main: import.meta.url },
126 Effect.gen(function* () {
127 return {};
128 }),
129 );
130 ```
131
132 The generator inside `Cloudflare.Worker` is the **Construction phase**. It
133 runs both at *plan time* (when Alchemy builds the deployment graph)
134 and at *runtime* (when the Worker boots a fresh isolate). Anything
135 you `yield*` here must be safe in both contexts — typically resource
136 binding factories like `R2.ReadWriteBucket(...)`, never per-request work.
137
138 ### 3a. Bind an R2 bucket for storage
139
140 Tasks need to live somewhere durable. Declare a `Bucket` resource
141 and bind it inside the constructor — `Cloudflare.R2.ReadWriteBucket(Tasks)`
142 returns a typed handle whose `get` / `put` / `delete` / `list` methods
143 we'll call from the handlers below.
144
145 ```typescript
146 // src/bucket.ts
147 import * as Cloudflare from "@alchemy.run/cloudflare";
148
149 export const Tasks = Cloudflare.R2.Bucket("Tasks");
150 ```
151
152 ```diff lang="typescript"
153 +import { Tasks } from "./bucket.ts";
154
155 export default Cloudflare.Worker(
156 "Worker",
157 { main: import.meta.url },
158 Effect.gen(function* () {
159 + const tasks = yield* Cloudflare.R2.ReadWriteBucket(Tasks);
160
161 return {};
162 }),
163 );
164 ```
165
166 We'll provide the runtime side of this binding
167 (`Cloudflare.R2.ReadWriteBucketBinding`) in step 3c when we wire up the
168 `fetch` handler.
169
170 ### 3b. Construct the handler group inside the constructor
171
172 `HttpApiBuilder.group` *constructs* a `Layer` that wires handlers
173 into the API spec. It's pure — it doesn't run them. That makes it
174 safe to call inside the constructor.
175
176 > Don't `yield*` `HttpApiBuilder.layer(TaskApi)` here — building the
177 > layer is fine, but actually executing the server requires an
178 > incoming request. The constructor only does construction; the work happens
179 > later, on each `fetch` call.
180
181 ```diff lang="typescript"
182 Effect.gen(function* () {
183 const tasks = yield* Cloudflare.R2.ReadWriteBucket(Tasks);
184
185 + const tasksGroup = HttpApiBuilder.group(TaskApi, "Tasks", (handlers) =>
186 + handlers
187 + .handle("getTask", ({ params }) =>
188 + Effect.gen(function* () {
189 + const object = yield* tasks.get(params.id).pipe(Effect.orDie);
190 + if (!object) {
191 + return yield* Effect.fail(new TaskNotFound({ id: params.id }));
192 + }
193 + return Schema.decodeUnknownSync(Task)(
194 + JSON.parse(yield* object.text().pipe(Effect.orDie)),
195 + );
196 + }),
197 + )
198 + .handle("createTask", ({ payload }) =>
199 + Effect.gen(function* () {
200 + const task = new Task({
201 + id: crypto.randomUUID(),
202 + title: payload.title,
203 + completed: false,
204 + });
205 + yield* tasks.put(task.id, JSON.stringify(task));
206 + return task;
207 + }).pipe(Effect.orDie),
208 + ),
209 + );
210
211 return {};
212 }),
213 ```
214
215 Each handler receives a typed request. `params.id` is a `string`
216 because that's what the endpoint declared, and the return type must
217 satisfy `Task` (or fail with `TaskNotFound`). Mismatches are caught
218 at compile time.
219
220 `tasks.get` and `tasks.put` can fail with `R2Error`, which isn't in
221 either endpoint's declared error set. `Effect.orDie` converts those
222 into defects so the HttpApi runtime turns them into 500 responses —
223 keeping the typed error channel reserved for `TaskNotFound`.
224
225 ### 3c. Return `{ fetch }`
226
227 The return value of the constructor is the *Worker's surface* — for a
228 fetch-style Worker that means an object with a `fetch` field. The
229 value of `fetch` must be an `HttpEffect`: an `Effect` that, given an
230 `HttpServerRequest`, produces an `HttpServerResponse`.
231
232 We assemble it in three layers, then convert:
233
234 - `HttpApiBuilder.layer(TaskApi)` — the top-level API layer.
235 - `Layer.provide(tasksGroup)` — plug in the handlers we just built.
236 - `Layer.provide([Etag.layer, HttpPlatformStub, Path.layer])` —
237 platform services the builder needs (content negotiation, ETag
238 generation, path handling).
239 - `yield* HttpRouter.toHttpEffect(...)` — build the assembled Layer
240 and yield the `HttpEffect`.
241
242 `HttpPlatformStub` stands in for `HttpPlatform.layer`, which requires
243 a `FileSystem` and therefore can't run on Workers — there is no
244 filesystem in the isolate. Define it once at module scope:
245
246 ```typescript
247 const HttpPlatformStub = Layer.succeed(HttpPlatform.HttpPlatform, {
248 fileResponse: () => Effect.die("HttpPlatform.fileResponse not supported"),
249 fileWebResponse: () =>
250 Effect.die("HttpPlatform.fileWebResponse not supported"),
251 });
252 ```
253
254 ```diff lang="typescript"
255 return {
256 + fetch: yield* HttpRouter.toHttpEffect(
257 + HttpApiBuilder.layer(TaskApi).pipe(
258 + Layer.provide(tasksGroup),
259 + Layer.provide([Etag.layer, HttpPlatformStub, Path.layer]),
260 + ),
261 + ),
262 };
263 ```
264
265 `HttpRouter.toHttpEffect` returns an `Effect` that builds the Layer
266 and hands back the request handler — yielding it once in the constructor means
267 route construction happens at boot, not per request.
268
269 ### 3d. Enable CORS
270
271 `HttpRouter.cors(...)` returns a `Layer` that registers a global
272 router middleware. Plug it in alongside the platform services with
273 another `Layer.provide`.
274
275 ```diff lang="typescript"
276 return {
277 fetch: yield* HttpRouter.toHttpEffect(
278 HttpApiBuilder.layer(TaskApi).pipe(
279 Layer.provide(tasksGroup),
280 Layer.provide([Etag.layer, HttpPlatformStub, Path.layer]),
281 + Layer.provide(HttpRouter.cors({
282 + allowedOrigins: ["*"],
283 + allowedMethods: ["GET", "POST", "OPTIONS"],
284 + allowedHeaders: ["Content-Type"],
285 + })),
286 ),
287 ),
288 };
289 ```
290
291 The middleware wraps every response — including the automatic
292 `OPTIONS` preflight — with the configured `Access-Control-*` headers.
293 Because it's a `Layer<never, never, HttpRouter>`, it composes the same
294 way as the rest of the API stack: order doesn't matter, and there's
295 no per-handler plumbing.
296
297 ### Putting it together
298
299 Here's the complete `src/worker.ts`:
300
301 ```typescript
302 // src/worker.ts
303 import * as Cloudflare from "@alchemy.run/cloudflare";
304 import * as Effect from "effect/Effect";
305 import * as Layer from "effect/Layer";
306 import * as Path from "effect/Path";
307 import * as Schema from "effect/Schema";
308 import * as Etag from "effect/http/Etag";
309 import * as HttpPlatform from "effect/http/HttpPlatform";
310 import * as HttpRouter from "effect/http/HttpRouter";
311 import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
312 import { TaskApi } from "./api.ts";
313 import { Tasks } from "./bucket.ts";
314 import { Task, TaskNotFound } from "./task.ts";
315
316 const HttpPlatformStub = Layer.succeed(HttpPlatform.HttpPlatform, {
317 fileResponse: () => Effect.die("HttpPlatform.fileResponse not supported"),
318 fileWebResponse: () =>
319 Effect.die("HttpPlatform.fileWebResponse not supported"),
320 });
321
322 export default Cloudflare.Worker(
323 "Worker",
324 { main: import.meta.url },
325 Effect.gen(function* () {
326 const tasks = yield* Cloudflare.R2.ReadWriteBucket(Tasks);
327
328 const tasksGroup = HttpApiBuilder.group(TaskApi, "Tasks", (handlers) =>
329 handlers
330 .handle("getTask", ({ params }) =>
331 Effect.gen(function* () {
332 const object = yield* tasks.get(params.id).pipe(Effect.orDie);
333 if (!object) {
334 return yield* Effect.fail(new TaskNotFound({ id: params.id }));
335 }
336 return Schema.decodeUnknownSync(Task)(
337 JSON.parse(yield* object.text().pipe(Effect.orDie)),
338 );
339 }),
340 )
341 .handle("createTask", ({ payload }) =>
342 Effect.gen(function* () {
343 const task = new Task({
344 id: crypto.randomUUID(),
345 title: payload.title,
346 completed: false,
347 });
348 yield* tasks.put(task.id, JSON.stringify(task));
349 return task;
350 }).pipe(Effect.orDie),
351 ),
352 );
353
354 return {
355 fetch: yield* HttpRouter.toHttpEffect(
356 HttpApiBuilder.layer(TaskApi).pipe(
357 Layer.provide(tasksGroup),
358 Layer.provide([Etag.layer, HttpPlatformStub, Path.layer]),
359 Layer.provide(
360 HttpRouter.cors({
361 allowedOrigins: ["*"],
362 allowedMethods: ["GET", "POST", "OPTIONS"],
363 allowedHeaders: ["Content-Type"],
364 }),
365 ),
366 ),
367 ),
368 };
369 }).pipe(Effect.provide(Cloudflare.R2.ReadWriteBucketBinding)),
370 );
371 ```
372
373 ## 4. Add to the Stack
374
375 ```typescript
376 // alchemy.run.ts
377 import * as Alchemy from "alchemy";
378 import * as Cloudflare from "@alchemy.run/cloudflare";
379 import * as Effect from "effect/Effect";
380 import Worker from "./src/worker.ts";
381
382 export default Alchemy.Stack(
383 "TaskApi",
384 { providers: Cloudflare.providers(), state: Cloudflare.state() },
385 Effect.gen(function* () {
386 const worker = yield* Worker;
387 return { url: worker.url };
388 }),
389 );
390 ```
391
392 ## 5. Deploy
393
394 ```sh
395 alchemy deploy
396 ```
397
398 You can hit it directly with `curl`:
399
400 ```sh
401 curl -X POST https://your-worker.workers.dev/ \
402 -H "Content-Type: application/json" \
403 -d '{"title": "Write docs"}'
404 # → {"id":"...","title":"Write docs","completed":false}
405
406 curl https://your-worker.workers.dev/<id>
407 # → {"id":"...","title":"Write docs","completed":false}
408 ```
409
410 Invalid payloads get automatic 400 responses with structured
411 validation errors — no manual checking needed.
412
413 ## Bonus: call it from a typed client
414
415 Because `TaskApi` is just a value, the same spec drives a fully
416 typed client. There's no codegen step — `HttpApiClient.make`
417 produces methods whose argument and return types come straight from
418 the endpoint schemas.
419
420 ```typescript
421 // scripts/client.ts
422 import * as Effect from "effect/Effect";
423 import * as HttpApiClient from "effect/http-api/HttpApiClient";
424 import { TaskApi } from "../src/api.ts";
425
426 const program = Effect.gen(function* () {
427 const client = yield* HttpApiClient.make(TaskApi, {
428 baseUrl: process.env.TASK_API_URL!,
429 });
430
431 const created = yield* client.Tasks.createTask({
432 payload: { title: "Write docs" },
433 });
434 console.log("Created:", created.id);
435
436 const fetched = yield* client.Tasks.getTask({
437 params: { id: created.id },
438 });
439 console.log("Fetched:", fetched.title);
440 });
441
442 Effect.runPromise(program);
443 ```
444
445 Get the URL from the deploy output and run it:
446
447 ```sh
448 TASK_API_URL=https://your-worker.workers.dev bun scripts/client.ts
449 ```
450
451 `client.Tasks.getTask` returns `Effect<Task, TaskNotFound | HttpClientError>`.
452 The `TaskNotFound` branch is a real typed value you can pattern-match
453 on, not an HTTP status code you have to interpret.
454
455 ## Bonus: route some endpoints to a Durable Object
456
457 The same `HttpApi` machinery can run *inside* a Durable Object. The
458 DO becomes a typed sub-API that the Worker delegates to, while the
459 public `TaskApi` shape remains a single value clients can import.
460
461 ### Define a DO-side group
462
463 The DO exposes its own group built from the same endpoint
464 declarations. Add two more endpoints to the public spec — one for
465 `get` and one for `create` — that the Worker will proxy to the DO,
466 then make a private group for the DO with just the two original
467 endpoints:
468
469 ```typescript
470 // src/api.ts
471 const getTaskDO = HttpApiEndpoint.get("getTaskDO", "/do/:id", {
472 params: TaskParams,
473 success: Task,
474 error: TaskNotFound,
475 });
476
477 const createTaskDO = HttpApiEndpoint.post("createTaskDO", "/do", {
478 success: Task,
479 payload: Schema.Struct({ title: Schema.String }),
480 });
481
482 export class TasksGroup extends HttpApiGroup.make("Tasks")
483 .add(getTask)
484 .add(createTask)
485 .add(getTaskDO)
486 .add(createTaskDO) {}
487
488 export class TasksDOGroup extends HttpApiGroup.make("TasksDO")
489 .add(getTask)
490 .add(createTask) {}
491
492 export class TaskDOApi extends HttpApi.make("TaskDOApi").add(TasksDOGroup) {}
493 ```
494
495 ### Implement the DO
496
497 The DO's constructor returns `{ fetch }` — an `HttpEffect` produced exactly
498 the same way the Worker produces one, just scoped to its own
499 `TaskDOApi`. Storage is the DO's transactional `state.storage`
500 instead of R2.
501
502 ```typescript
503 // src/object.ts
504 import * as Cloudflare from "@alchemy.run/cloudflare";
505 import * as Effect from "effect/Effect";
506 import * as Layer from "effect/Layer";
507 import * as Path from "effect/Path";
508 import * as Etag from "effect/http/Etag";
509 import * as HttpPlatform from "effect/http/HttpPlatform";
510 import * as HttpRouter from "effect/http/HttpRouter";
511 import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
512 import { TaskDOApi, decodeTask, encodeTask } from "./api.ts";
513 import { Task, TaskNotFound } from "./task.ts";
514
515 const HttpPlatformStub = Layer.succeed(HttpPlatform.HttpPlatform, {
516 fileResponse: () => Effect.die("HttpPlatform.fileResponse not supported"),
517 fileWebResponse: () =>
518 Effect.die("HttpPlatform.fileWebResponse not supported"),
519 });
520
521 export default class TasksObject extends Cloudflare.DurableObject<TasksObject>()(
522 "TasksObject",
523 Effect.gen(function* () {
524 const state = yield* Cloudflare.DurableObjectState;
525 return Effect.gen(function* () {
526 const tasksGroup = HttpApiBuilder.group(TaskDOApi, "TasksDO", (handlers) =>
527 handlers
528 .handle("getTask", ({ params }) =>
529 state.storage.get<Task>(params.id).pipe(
530 Effect.flatMap((task) =>
531 task
532 ? decodeTask(task).pipe(Effect.orDie)
533 : Effect.fail(new TaskNotFound({ id: params.id })),
534 ),
535 ),
536 )
537 .handle("createTask", ({ payload }) => {
538 const task = new Task({
539 id: crypto.randomUUID(),
540 title: payload.title,
541 completed: false,
542 });
543 return state.storage.put(task.id, encodeTask(task)).pipe(Effect.as(task));
544 }),
545 );
546
547 return {
548 fetch: yield* HttpRouter.toHttpEffect(
549 HttpApiBuilder.layer(TaskDOApi).pipe(
550 Layer.provide(tasksGroup),
551 Layer.provide([Etag.layer, HttpPlatformStub, Path.layer]),
552 ),
553 ),
554 };
555 });
556 }),
557 ) {}
558 ```
559
560 ### Bridge the DO into a typed client
561
562 Inside the Worker's constructor, `Cloudflare.toHttpClient(stub)` wraps a DO
563 stub as an `HttpClient`. Hand that client to `HttpApiClient.makeWith`
564 and you get a fully typed client whose every call is a DO `fetch`
565 under the hood:
566
567 ```diff lang="typescript"
568 +import * as HttpApiClient from "effect/http-api/HttpApiClient";
569 +import TasksObject, { TaskDOApi } from "./object.ts";
570
571 Effect.gen(function* () {
572 const tasks = yield* Cloudflare.R2.ReadWriteBucket(Tasks);
573 + const tasksDO = yield* TasksObject;
574 +
575 + const getTaskDOClient = (id: string = "default") =>
576 + HttpApiClient.makeWith(TaskDOApi, {
577 + baseUrl: "http://localhost",
578 + httpClient: Cloudflare.toHttpClient(tasksDO.getByName(id)),
579 + });
580 ```
581
582 The `baseUrl` is irrelevant — requests never leave the isolate; the
583 `httpClient` short-circuits straight to `tasksDO.getByName(id).fetch`.
584
585 ### Wire the proxy handlers
586
587 The Worker's two new handlers just construct a per-request DO client
588 and forward the typed call. Errors from the DO already match the
589 public endpoint's error schema, so there's no remapping:
590
591 ```diff lang="typescript"
592 const tasksGroup = HttpApiBuilder.group(TaskApi, "Tasks", (handlers) =>
593 handlers
594 .handle("getTask", /* ... R2 implementation ... */)
595 .handle("createTask", /* ... R2 implementation ... */)
596 + .handle("getTaskDO", ({ params }) =>
597 + getTaskDOClient().pipe(
598 + Effect.flatMap((client) => client.TasksDO.getTask({ params })),
599 + ),
600 + )
601 + .handle("createTaskDO", ({ payload }) =>
602 + getTaskDOClient().pipe(
603 + Effect.flatMap((client) => client.TasksDO.createTask({ payload })),
604 + ),
605 + ),
606 );
607 ```
608
609 `GET /do/:id` and `POST /do` now hit the DO; `GET /:id` and `POST /`
610 still hit R2. Same `TaskApi`, same client, two different storage
611 backends behind the scenes.
612
613 ## Recap
614
615 - The **schema** (`Task`, `TaskNotFound`) and the **API spec**
616 (`TaskApi`) live outside the Worker — they're pure descriptions.
617 - The **handlers** are constructed inside the Worker's Construction phase
618 closure. We build a `Layer` with `HttpApiBuilder.group` but never
619 `yield*` the running server — that only makes sense per-request.
620 - The Worker's surface is `{ fetch }`, where `fetch` is an
621 `HttpEffect` yielded once from `HttpRouter.toHttpEffect`.
622 - The same `TaskApi` value drives a fully typed client via
623 `HttpApiClient.make` — no codegen, no string URLs.
624
625 ## Where next
626
627 - [Effect HTTP](/apis/effect-http) — the concept home for this modality.
628 - [RPC](/apis) — how to choose between Schemaless RPC, Effect RPC, and
629 Effect HTTP.
630 - [Effect RPC on Workers](/cloudflare/apis/effect-rpc) — the
631 schema-first RPC shape for Effect/TypeScript consumers.
632 - [Schemaless RPC](/cloudflare/compute/workers#call-another-worker) — the
633 default for internal Worker-to-Worker calls.