DispatchNamespace
Source:
src/Cloudflare/WorkersForPlatforms/DispatchNamespace.ts
A Workers for Platforms dispatch namespace — a container for customer (“user”) Workers that a platform Worker dispatches to at runtime via a dynamic-dispatch binding.
The namespace has no mutable properties: its name is its identity, so
changing the name triggers a replacement. Deleting a namespace also
deletes every script uploaded into it.
Note: Workers for Platforms is a paid add-on. On accounts without the subscription, namespace creation fails with an entitlement error.
Creating a Dispatch Namespace
Section titled “Creating a Dispatch Namespace”Namespace with a generated name
const namespace = yield* Cloudflare.WorkersForPlatforms.DispatchNamespace("Customers", {});Namespace with an explicit name
const namespace = yield* Cloudflare.WorkersForPlatforms.DispatchNamespace("Customers", { name: "my-platform-customers",});Uploading user Workers
Section titled “Uploading user Workers”A Cloudflare.Worker deploys into the namespace as a “user worker”
(rather than as a routable account-level script) when its namespace prop is
set. Reference the namespace by its name output so it deploys first.
const namespace = yield* Cloudflare.WorkersForPlatforms.DispatchNamespace("Customers", {});
const customerA = yield* Cloudflare.Worker("CustomerA", { namespace: namespace.name, script: `export default { fetch() { return new Response("hi"); } }`,});Dispatching from a platform Worker
Section titled “Dispatching from a platform Worker”Effect-native binding via Get
Cloudflare.WorkersForPlatforms.Get(namespace) binds the namespace and
returns an Effect-native client; get(name) resolves a user Worker by script
name. Provide GetBinding on the Worker’s runtime layer.
const dispatch = yield* Cloudflare.WorkersForPlatforms.Get(namespace);
return { fetch: Effect.gen(function* () { const request = yield* HttpServerRequest; const userWorker = yield* dispatch.get("CustomerA"); return yield* Effect.promise(() => userWorker.fetch(request)); }),};Async binding via env + InferEnv
Passing the namespace on a Worker’s env binds it as a native
dispatch_namespace binding; Cloudflare.InferEnv types env.DISPATCH as
the runtime DispatchNamespace, so the async handler calls .get(name)
directly.
const platform = Cloudflare.Worker("Platform", { main: "./handler.ts", env: { DISPATCH: namespace },});type Env = Cloudflare.InferEnv<typeof platform>;
// handler.tsexport default { async fetch(request: Request, env: Env) { return env.DISPATCH.get("CustomerA").fetch(request); },};