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

main
mdx 763 lines 23.8 KB
Raw
1 ---
2 title: Workers
3 description: Cloudflare Workers are the compute Runtime of every Alchemy app — declare the Worker and its handler in one file, bind resources with full type safety, and call other Workers over schemaless RPC.
4 ---
5
6 In Alchemy, a Cloudflare Worker is a
7 [Runtime](/infrastructure-as-effects/runtime): a
8 [Resource](/infrastructure-as-code/resource) that carries the code it
9 runs. The name and props describe the Worker to deploy. The Effect is
10 what it does:
11
12 ```typescript
13 // src/worker.ts
14 import * as Cloudflare from "@alchemy.run/cloudflare";
15 import * as Effect from "effect/Effect";
16 import * as HttpServerResponse from "effect/http/HttpServerResponse";
17
18 export default Cloudflare.Worker(
19 "Worker",
20 { main: import.meta.url },
21 Effect.gen(function* () {
22 return {
23 fetch: Effect.gen(function* () {
24 return HttpServerResponse.text("Hello, world!");
25 }),
26 };
27 }),
28 );
29 ```
30
31 `main: import.meta.url` tells Alchemy to bundle this file's default
32 export, the Worker itself, as the script. Yield the Worker from a
33 Stack and expose its URL:
34
35 ```typescript
36 // alchemy.run.ts
37 import * as Alchemy from "alchemy";
38 import * as Cloudflare from "@alchemy.run/cloudflare";
39 import * as Effect from "effect/Effect";
40 import Worker from "./src/worker.ts";
41
42 export default Alchemy.Stack(
43 "MyApp",
44 { providers: Cloudflare.providers(), state: Cloudflare.state() },
45 Effect.gen(function* () {
46 const worker = yield* Worker;
47 return { url: worker.url };
48 }),
49 );
50 ```
51
52 ```sh
53 bun alchemy deploy
54 ```
55
56 Alchemy bundles the file, uploads it, enables the `workers.dev`
57 subdomain, and prints the URL as a stack output.
58
59 Reach for a Worker whenever you need compute: HTTP APIs, frontends,
60 queue consumers, cron jobs, RPC services. Every other building block,
61 [Durable Objects](/cloudflare/compute/durable-objects),
62 [D1](/cloudflare/data/d1), [R2](/cloudflare/data/r2),
63 [Queues](/cloudflare/messaging/queues), is reached through a Worker
64 by binding it.
65
66 ## Bind a resource
67
68 Declare a Bucket next to the Worker and bind it. The
69 [Binding](/infrastructure-as-effects/binding) hands back a typed
70 client, and the Layer you provide decides how the binding is
71 implemented, here as a native `r2_bucket` binding on the Worker:
72
73 ```typescript
74 // src/worker.ts
75 import * as Cloudflare from "@alchemy.run/cloudflare";
76 import * as Effect from "effect/Effect";
77 import * as HttpServerResponse from "effect/http/HttpServerResponse";
78
79 export const Uploads = Cloudflare.R2.Bucket("Uploads");
80
81 export default Cloudflare.Worker(
82 "Worker",
83 { main: import.meta.url },
84 Effect.gen(function* () {
85 const bucket = yield* Cloudflare.R2.ReadWriteBucket(Uploads);
86
87 return {
88 fetch: Effect.gen(function* () {
89 const obj = yield* bucket.get("hello.txt");
90 return obj
91 ? HttpServerResponse.text(yield* obj.text())
92 : HttpServerResponse.text("Not found", { status: 404 });
93 }).pipe(
94 Effect.catchTag("R2Error", (error) =>
95 Effect.succeed(HttpServerResponse.text(error.message, { status: 500 })),
96 ),
97 ),
98 };
99 }).pipe(Effect.provide(Cloudflare.R2.ReadWriteBucketBinding)),
100 );
101 ```
102
103 The binding is declared where it's used, so deploying the Worker
104 deploys the wiring. The client's errors, like `R2Error`, live in the
105 Effect type system, so you can't forget to handle them. And the access
106 level is in the name: `ReadBucket`, `WriteBucket`, or
107 `ReadWriteBucket`, depending on what the Worker actually needs.
108
109 Every building block binds the same way. See
110 [KV](/cloudflare/data/kv), [D1](/cloudflare/data/d1),
111 [Queues](/cloudflare/messaging/queues),
112 [Hyperdrive](/cloudflare/data/hyperdrive), and
113 [Durable Objects](/cloudflare/compute/durable-objects), or walk
114 through it step by step in [tutorial part 2](/cloudflare/tutorial/part-2).
115
116 :::note
117 [Bindings](/infrastructure-as-effects/binding) explains what a binding
118 generates at deploy time and how the Layer you provide implements it.
119 :::
120
121 ## Call another Worker
122
123 Workers call each other's methods directly. No HTTP routes, no schema,
124 no public URL. Declare the callee as a class whose type carries its
125 RPC shape, and attach its implementation with `.make()`:
126
127 ```typescript
128 // src/Greeter.ts
129 import * as Cloudflare from "@alchemy.run/cloudflare";
130 import * as Effect from "effect/Effect";
131
132 export class Greeter extends Cloudflare.Worker<
133 Greeter,
134 { greet: (name: string) => Effect.Effect<string> }
135 >()("Greeter") {}
136
137 export default Greeter.make(
138 { main: import.meta.url },
139 Effect.gen(function* () {
140 return {
141 greet: (name: string) => Effect.succeed(`Hello ${name}`),
142 };
143 }),
144 );
145 ```
146
147 Bind it from another Worker with `bindWorker` and call `greet` through
148 the typed stub:
149
150 ```typescript
151 // src/Api.ts
152 import * as Cloudflare from "@alchemy.run/cloudflare";
153 import * as Effect from "effect/Effect";
154 import * as HttpServerResponse from "effect/http/HttpServerResponse";
155 import { Greeter } from "./Greeter.ts";
156
157 export default Cloudflare.Worker(
158 "Api",
159 { main: import.meta.url },
160 Effect.gen(function* () {
161 const greeter = yield* Cloudflare.Workers.bindWorker(Greeter);
162
163 return {
164 fetch: Effect.gen(function* () {
165 return HttpServerResponse.text(yield* greeter.greet("world"));
166 }),
167 };
168 }),
169 );
170 ```
171
172 `bindWorker(Greeter)` registers a service binding on `Api`, so each
173 call travels over Cloudflare's in-account service-binding fabric and
174 never the public internet. `greeter.greet("world")` is type-checked
175 against `Greeter`'s declared shape end to end.
176
177 Importing the `Greeter` class pulls in no runtime code. Alchemy marks
178 `.make()` as pure, so the bundler drops the implementation from every
179 Worker that only binds it. For external clients across a trust
180 boundary, where payloads need schema validation before they touch your
181 code, reach for [Effect RPC](/cloudflare/apis/effect-rpc) instead.
182
183 :::note
184 [Runtime](/infrastructure-as-effects/runtime#three-ways-to-declare-a-runtime)
185 covers the three declaration forms, and
186 [Schemaless RPC](/apis/schemaless) the calling convention.
187 :::
188
189 ## Call a Worker in another stack
190
191 When `Greeter` is deployed by another stack, reference it with
192 `Worker.ref`. Pass the `Greeter` class rather than its logical id so the
193 reference keeps its RPC shape:
194
195 ```typescript
196 // src/Api.ts
197 import * as Cloudflare from "@alchemy.run/cloudflare";
198 import * as Effect from "effect/Effect";
199 import * as HttpServerResponse from "effect/http/HttpServerResponse";
200 import { Greeter } from "./Greeter.ts";
201
202 export default Cloudflare.Worker(
203 "Api",
204 { main: import.meta.url },
205 Effect.gen(function* () {
206 const greeter = yield* Cloudflare.Workers.bindWorker(
207 Cloudflare.Worker.ref(Greeter, { stack: "Greeter" }),
208 );
209
210 return {
211 fetch: Effect.gen(function* () {
212 return HttpServerResponse.text(yield* greeter.greet("world"));
213 }),
214 };
215 }),
216 );
217 ```
218
219 `Worker.ref(Greeter, ...)` only reads `Greeter`'s logical id. This stack
220 does not deploy `Greeter`; it binds to the one the `Greeter` stack owns.
221
222 ## Call the Worker's own RPC methods
223
224 A Worker can bind itself. Declare the class first so its implementation
225 can reference it:
226
227 ```typescript
228 export class Greeter extends Cloudflare.Worker<
229 Greeter,
230 { greet: (name: string) => Effect.Effect<string> }
231 >()("Greeter") {}
232
233 export default Greeter.make(
234 { main: import.meta.url },
235 Effect.gen(function* () {
236 const self = yield* Cloudflare.Workers.bindWorker(Greeter);
237
238 return {
239 greet: (name: string) => Effect.succeed(`Hello ${name}`),
240 fetch: Effect.gen(function* () {
241 return HttpServerResponse.text(yield* self.greet("world"));
242 }),
243 };
244 }),
245 );
246 ```
247
248 A self binding uses workerd's `ctx.exports` loopback, so nothing is added
249 to the Worker's deployed bindings.
250
251 ## Serve static assets
252
253 Pass `assets` and Cloudflare serves matching requests from its asset
254 layer. Everything else invokes your handlers:
255
256 ```typescript
257 export default Cloudflare.Worker(
258 "Worker",
259 { main: import.meta.url, assets: "./public" },
260 // ...
261 );
262 ```
263
264 A path that matches no asset already falls through to the Worker. Set
265 `runWorkerFirst` when a path the Worker must own could be answered by
266 the asset layer instead, such as an asset file shadowing a route or a
267 single-page-application fallback that would serve the app shell to an
268 API call:
269
270 ```typescript
271 assets: {
272 directory: "./public",
273 // only these paths reach the Worker ahead of assets
274 runWorkerFirst: ["/api/*", "/admin/*"],
275 },
276 ```
277
278 `runWorkerFirst: true` routes every request through the Worker, which
279 then serves files itself via the `ASSETS` binding. The same routing
280 applies under `alchemy dev`.
281
282 Omit `main` entirely for an assets-only Worker. No script is uploaded,
283 and the asset layer applies `htmlHandling` and `notFoundHandling`
284 itself. Static asset requests are free and never invoke a Worker:
285
286 ```typescript
287 const site = yield* Cloudflare.Worker("Site", {
288 assets: {
289 directory: "./public",
290 htmlHandling: "drop-trailing-slash",
291 notFoundHandling: "404-page",
292 },
293 domain: "static.example.com",
294 });
295 ```
296
297 A `_headers` or `_redirects` file in the directory is applied
298 automatically, and a `.assetsignore` file excludes files from the
299 upload. If the directory comes from a build command, use
300 [StaticSite](/cloudflare/frontend/static-site). For Vite projects, use
301 the [Vite resource](/cloudflare/frontend/vite).
302
303 ## URLs and domains
304
305 `worker.urls` is every URL that serves the Worker, most significant
306 first, and `worker.url` is always `urls[0]`. Attach custom domains
307 with `domain`:
308
309 ```typescript
310 const worker = yield* Cloudflare.Worker("Api", {
311 main: "./src/api.ts",
312 domain: {
313 name: "example.com",
314 aliases: ["www.example.com"],
315 redirects: ["old.example.com"], // 301 → https://example.com
316 },
317 });
318 // worker.url === "https://example.com"
319 // worker.urls === ["https://example.com", "https://www.example.com",
320 // "https://<name>.<account>.workers.dev"]
321 ```
322
323 Every hostname becomes a Cloudflare custom domain. DNS records and
324 edge certificates are managed for you, and the zone must already exist
325 in the account. A bare string is shorthand for `{ name }`. Redirect
326 hostnames answer with a permanent redirect before the Worker runs, so
327 they never appear in `urls`.
328
329 Zone routes attach the Worker to a path pattern instead of a whole
330 hostname:
331
332 ```typescript
333 routes: [
334 { pattern: "example.com/api/*", zoneName: "example.com" },
335 ],
336 ```
337
338 `workersDev` controls the `workers.dev` surface:
339
340 ```typescript
341 workersDev: false, // no workers.dev URLs, url is the custom domain
342 workersDev: { enabled: false, previewsEnabled: true }, // preview URLs only
343 ```
344
345 Under `alchemy dev`, `urls` is the dev server's actual surface, the
346 `localhost` address first and then the LAN addresses. Pass `urls`
347 wholesale wherever a list of origins is needed:
348
349 ```typescript
350 const api = yield* Cloudflare.Worker("Api", {
351 main: "./src/api.ts",
352 env: { ALLOWED_ORIGINS: site.urls }, // CORS allow-list
353 });
354 ```
355
356 For zone setup, DNS records, and route patterns, see
357 [custom domains](/cloudflare/networking/custom-domains).
358
359 ## The Worker's own URL
360
361 A Worker often needs the URL it is served at, to build absolute links
362 or register a webhook. That URL only exists at deploy time, and a
363 Worker can't reference its own `url` Output, so `Worker.URL` injects
364 it as a binding on the Worker itself. Yield it in the Construction
365 phase, then yield the accessor it returns inside a handler:
366
367 ```typescript
368 export default Cloudflare.Worker(
369 "Api",
370 { main: import.meta.url },
371 Effect.gen(function* () {
372 const url = yield* Cloudflare.Worker.URL;
373
374 return {
375 fetch: Effect.gen(function* () {
376 const publicUrl = yield* url;
377 return yield* HttpServerResponse.json({ url: publicUrl });
378 }),
379 };
380 }),
381 );
382 ```
383
384 The value is the first custom `domain` if one is configured, otherwise
385 the `workers.dev` URL, and always equals the resource's `url`
386 attribute. Under `alchemy dev` it is the local dev server's URL.
387
388 Async Workers declare it on `env`, where `InferEnv` types the entry as
389 `string`. A `VITE_`-prefixed entry is also inlined into a Vite site's
390 client bundle, see [the site's own URL](/cloudflare/frontend/vite#the-sites-own-url):
391
392 ```typescript
393 export const Worker = Cloudflare.Worker("Worker", {
394 main: "./src/worker.ts",
395 env: { PUBLIC_URL: Cloudflare.Worker.URL },
396 });
397 ```
398
399 ## Async Workers
400
401 A Worker doesn't have to be an Effect program. Point `main` at a plain
402 module, a classic `async fetch` handler or a prebuilt bundle from
403 another tool, and declare bindings with the `env` prop. `InferEnv`
404 derives the handler's env type from them:
405
406 ```typescript
407 // alchemy.run.ts
408 import * as Cloudflare from "@alchemy.run/cloudflare";
409
410 export const Uploads = Cloudflare.R2.Bucket("Uploads");
411 export const DB = Cloudflare.D1.Database("DB");
412
413 export const Worker = Cloudflare.Worker("Worker", {
414 main: "./src/worker.ts",
415 env: { Uploads, DB },
416 });
417
418 export type WorkerEnv = Cloudflare.InferEnv<typeof Worker>;
419 ```
420
421 ```typescript
422 // src/worker.ts
423 import type { WorkerEnv } from "../alchemy.run.ts";
424
425 export default {
426 async fetch(request: Request, env: WorkerEnv) {
427 const obj = await env.Uploads.get("hello.txt");
428 return obj
429 ? new Response(await obj.text())
430 : new Response("Not found", { status: 404 });
431 },
432 };
433 ```
434
435 `InferEnv` maps each entry to its native `workers-types` client. An R2
436 bucket becomes `R2Bucket`, a D1 database `D1Database`, a Durable
437 Object or [Container](/cloudflare/compute/containers#bind-on-an-async-worker)
438 a typed `DurableObjectNamespace`, and `Config` or `Redacted` values
439 `string`. The handler stays plain JavaScript, but the env can never
440 drift from the infrastructure that produced it.
441 [Python Workers](/cloudflare/compute/python-workers) are async Workers
442 whose `main` is a `.py` file.
443
444 ### Bind another Worker or this one
445
446 A service binding reaches a Worker's default export or one of its named
447 [`WorkerEntrypoint`](https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/rpc/)
448 classes. The target can be another Worker or this Worker itself. The
449 examples below call this module:
450
451 ```typescript
452 // src/target.ts
453 import { WorkerEntrypoint } from "cloudflare:workers";
454
455 export class Api extends WorkerEntrypoint {
456 async greet(name: string): Promise<string> {
457 return `hello ${name}`;
458 }
459 }
460
461 export default {
462 async fetch() {
463 return new Response("ok");
464 },
465 };
466 ```
467
468 ### Another Worker's default export
469
470 Put the Worker itself on `env`:
471
472 ```typescript
473 const target = yield* Cloudflare.Worker("Target", { main: "./src/target.ts" });
474
475 const caller = yield* Cloudflare.Worker("Caller", {
476 main: "./src/caller.ts",
477 env: { TARGET: target },
478 });
479 ```
480
481 `env.TARGET` is a `Fetcher`, so `env.TARGET.fetch(request)` reaches the
482 target's `export default`.
483
484 ### Another Worker's named entrypoint
485
486 Name the class with `Cloudflare.WorkerEntrypoint`, and pass its instance
487 type (`Api`, not `typeof Api`) to type the RPC methods:
488
489 ```typescript
490 import type { Api } from "./src/target.ts";
491
492 const caller = yield* Cloudflare.Worker("Caller", {
493 main: "./src/caller.ts",
494 env: { API: Cloudflare.WorkerEntrypoint<Api>(target, "Api") },
495 });
496 ```
497
498 ```typescript
499 // src/caller.ts
500 export default {
501 async fetch(request: Request, env: CallerEnv) {
502 return new Response(await env.API.greet("alice"));
503 },
504 };
505 ```
506
507 `InferEnv` maps the binding to Cloudflare's `Service<Api>`, which checks
508 arguments and returns promises. Without the type argument `env.API` is a
509 plain `Fetcher` with only `fetch` and `connect`.
510
511 ### This Worker's default export
512
513 `Cloudflare.WorkerEntrypoint()` with no arguments binds the Worker to itself:
514
515 ```typescript
516 const api = yield* Cloudflare.Worker("Api", {
517 main: "./src/target.ts",
518 env: { SELF: Cloudflare.WorkerEntrypoint() },
519 });
520 ```
521
522 `env.SELF.fetch(request)` re-enters the Worker's own `export default`.
523 `Cloudflare.Workers.Self` is the same binding.
524
525 ### This Worker's named entrypoint
526
527 Pass just the name:
528
529 ```typescript
530 import type { Api } from "./src/target.ts";
531
532 const api = yield* Cloudflare.Worker("Api", {
533 main: "./src/target.ts",
534 env: { API: Cloudflare.WorkerEntrypoint<Api>("Api") },
535 });
536 ```
537
538 When the entrypoint class extends `WorkerEntrypoint<WorkerEnv>`, declare
539 `WorkerEnv` as an interface. A type alias is a circular type here:
540
541 ```typescript
542 export interface WorkerEnv extends Cloudflare.InferEnv<typeof api> {}
543 ```
544
545 Without the type argument `env.API` is a plain `Fetcher`, and either form
546 of `WorkerEnv` works.
547
548 ### Pass `ctx.props` to an entrypoint
549
550 The options form attaches properties the entrypoint reads from
551 `this.ctx.props`, on another Worker or on this one
552 (`Cloudflare.WorkerEntrypoint({ entrypoint, props })`). `Output` values
553 resolve at deploy time:
554
555 ```typescript
556 env: {
557 VENDOR: Cloudflare.WorkerEntrypoint(vendorWorker, {
558 entrypoint: "Vendor",
559 props: { baseUrl: site.url },
560 }),
561 },
562 ```
563
564 Leave out `entrypoint` to target the default export.
565
566 :::caution
567 `alchemy dev` delivers `props` to the local workerd today. On deployed
568 Workers the Cloudflare API's binding schema does not carry the field
569 yet, so `props` are dropped at upload. The binding itself deploys
570 correctly either way.
571 :::
572
573 ## Configure the Worker
574
575 Compatibility flags and the compatibility date go on `compatibility`.
576 `nodejs_compat` is the one you reach for most:
577
578 ```typescript
579 {
580 main: import.meta.url,
581 compatibility: { flags: ["nodejs_compat"], date: "2026-08-31" },
582 }
583 ```
584
585 Workers Observability is on by default, with logs and invocation logs
586 enabled. Pass `observability` to tune sampling, persist logs, or turn
587 on traces. Effect-native Workers should provide
588 [`Cloudflare.Telemetry()`](/infrastructure-as-effects/telemetry)
589 instead of setting `traces` by hand, since the Layer enables traces on
590 the Worker and mirrors `Effect.withSpan` into the Cloudflare waterfall:
591
592 ```typescript
593 observability: {
594 logs: { enabled: true, invocationLogs: true, persist: true },
595 traces: { enabled: true, headSamplingRate: 1 },
596 },
597 ```
598
599 A [Tail Worker](https://developers.cloudflare.com/workers/observability/logs/tail-workers/)
600 receives another Worker's execution traces after each invocation. List
601 it in `tailConsumers`, or in `streamingTailConsumers` to receive
602 events live while the producer is still running:
603
604 ```typescript
605 const tail = yield* Cloudflare.Worker("Tail", { main: "./src/tail.ts" });
606
607 const api = yield* Cloudflare.Worker("Api", {
608 main: "./src/api.ts",
609 tailConsumers: [tail],
610 });
611 ```
612
613 Put Cloudflare Access in front of the Worker with `access`.
614 Unauthenticated requests are redirected to your team's login page, and
615 handlers read the identity from `Cloudflare.Access.Context`:
616
617 ```typescript
618 {
619 main: import.meta.url,
620 access: {
621 policies: [{ decision: "allow", include: [{ emailDomain: "example.com" }] }],
622 },
623 }
624 ```
625
626 Pass an existing `Cloudflare.Access.Application` instead to share one
627 policy set across several Workers. See
628 [Protect a Worker with Access](/cloudflare/security/access).
629
630 `main` is bundled with rolldown at deploy time. Effect, Alchemy, and
631 the cloud SDKs are marked pure so unused code prunes aggressively.
632 Mark your own side-effect-free packages the same way with
633 `build.pure`, or set `bundle: false` to upload a bundle another tool
634 already produced, such as OpenNext, byte for byte:
635
636 ```typescript
637 {
638 main: "./.open-next/worker.js",
639 bundle: false,
640 assets: "./.open-next/assets",
641 }
642 ```
643
644 Every prop, including `limits`, `placement`, `logpush`, `crons`, and
645 `tags`, is documented on the
646 [Worker reference](/providers/cloudflare/workers/worker).
647
648 ## Background work and scopes
649
650 The Worker's constructor runs once per isolate. The first event builds
651 your Layers, and every later event reuses them. Each event then runs
652 with a fresh `Scope` that closes after the response via
653 `ctx.waitUntil`, so a finalizer added in a handler runs after the
654 response is sent without blocking it:
655
656 ```typescript
657 fetch: Effect.gen(function* () {
658 yield* Effect.addFinalizer(() => flushMetrics().pipe(Effect.ignore));
659 return HttpServerResponse.text("ok");
660 }),
661 ```
662
663 For ad-hoc background work, `Cloudflare.waitUntil` forks an Effect
664 with the caller's full context and keeps the invocation alive until it
665 settles:
666
667 ```typescript
668 Effect.gen(function* () {
669 return {
670 fetch: Effect.gen(function* () {
671 yield* Cloudflare.waitUntil(writeAuditLog(event));
672 return HttpServerResponse.text("accepted", { status: 202 });
673 }),
674 };
675 });
676 ```
677
678 Streaming responses and WebSocket upgrades transfer the request scope
679 to the stream, so its finalizers run when the stream completes. workerd
680 has no isolate-teardown hook, so a finalizer added in the constructor
681 never runs. Acquire anything that needs cleanup, connections and
682 pools, inside handlers. `Drizzle.Postgres` follows this pattern, one
683 pool per event, and the
684 [SQL connection lifecycle](/sql/effect-sql/lifecycle) spells out the
685 contract. [Instance scope vs request scope](/infrastructure-as-effects/runtime#instance-scope-vs-request-scope)
686 covers the model across all runtimes.
687
688 ## Versions
689
690 Every deploy uploads an immutable version, and by default it takes
691 100% of traffic. The `version` prop unlocks the other shapes. Split
692 traffic to roll a deploy out gradually:
693
694 ```typescript
695 yield* Cloudflare.Worker("Api", {
696 main: "./src/api.ts",
697 version: { traffic: 25 },
698 });
699 ```
700
701 Set `preview.of` to deploy this Worker as a
702 [Preview](/cloudflare/compute/previews) of another stage's Worker
703 (branch and pull-request testing, isolated Durable Objects). Set
704 `version.parent` to upload a canary version of another stage's
705 Worker. Ramping, rollback, smoke testing with version overrides, and
706 pinning users to a version are covered in
707 [Gradual deployments](/cloudflare/compute/gradual-deployments).
708
709 Durable Objects that are busy during a deploy keep running their
710 current code for up to 5 minutes. `codeUpdateStrategy` changes how
711 long they wait, or switches them right away. See
712 [Code updates](/cloudflare/compute/code-updates).
713
714 The `version_metadata` binding tells a running Worker which version
715 it is, so responses and logs can say exactly which deploy produced
716 them:
717
718 ```typescript
719 export default Cloudflare.Worker(
720 "Api",
721 { main: import.meta.url },
722 Effect.gen(function* () {
723 const versionMetadata = yield* Cloudflare.Workers.VersionMetadata();
724
725 return {
726 fetch: Effect.gen(function* () {
727 const { id, tag, timestamp } = yield* versionMetadata;
728 return yield* HttpServerResponse.json({ id, tag, timestamp });
729 }),
730 };
731 }).pipe(Effect.provide(Cloudflare.Workers.VersionMetadataBinding)),
732 );
733 ```
734
735 Async Workers declare it on `env` as
736 `CF_VERSION_METADATA: Cloudflare.Workers.VersionMetadata()`, and
737 `InferEnv` types the entry as the native `{ id, tag, timestamp }`
738 object.
739
740 ## Where next
741
742 Guides that build on Workers:
743
744 - [Gradual deployments](/cloudflare/compute/gradual-deployments) — previews, canaries, and ramped rollouts across versions.
745 - [Code updates](/cloudflare/compute/code-updates) — what a deploy does to running Workers and Durable Objects.
746 - [Python Workers](/cloudflare/compute/python-workers) — point `main` at a `.py` file.
747 - [Workers Cache](/cloudflare/compute/cache) — serve responses from the edge before the Worker runs.
748 - [Rate limiting](/cloudflare/compute/rate-limiting) — throttle requests with a binding.
749 - [Browser rendering](/cloudflare/compute/browser-rendering) — a headless browser as a binding.
750 - [Worker Loader](/cloudflare/compute/worker-loader) — run untrusted Workers at runtime.
751 - [Workers for Platforms](/cloudflare/compute/workers-for-platforms) — run customers' Workers in your account.
752 - [Custom domains](/cloudflare/networking/custom-domains) — serve Workers from your own hostnames and routes.
753 - [Effect HTTP API](/cloudflare/apis/effect-http-api) and [Effect RPC](/cloudflare/apis/effect-rpc) — schema-validated surfaces.
754 - [Frontend frameworks](/cloudflare/frontend/frontends) — ship a frontend from the same Stack.
755
756 Related:
757
758 - [Durable Objects](/cloudflare/compute/durable-objects), [Workflows](/cloudflare/compute/workflows), and [Containers](/cloudflare/compute/containers) — the other compute Runtimes, all reached through a Worker.
759 - [Secrets & env](/cloudflare/security/secrets-env) — bind `.env` values and secrets into the Worker.
760
761 Reference:
762
763 - [Worker API reference](/providers/cloudflare/workers/worker)