Skip to content

Workers for Platforms

Workers for Platforms lets you run your customers’ code on Cloudflare’s edge inside your own account. Customer (“user”) Workers live in a dispatch namespace and get no routes or URLs of their own. Instead, a platform Worker you control receives every request and forwards it to the right user Worker by script name.

Declare the namespace as a shared constant so both the Stack and the platform Worker can reference the same resource:

src/namespace.ts
import * as Cloudflare from "@alchemy.run/cloudflare";
export const Customers = Cloudflare.WorkersForPlatforms.DispatchNamespace(
"Customers",
{ name: "my-platform-customers" },
);

The name is the namespace’s identity. There is no rename API, so changing it triggers a replacement (omit it to get a generated name). Deleting a namespace also deletes every script uploaded into it.

Setting a Worker’s namespace prop deploys it into the namespace as a user Worker instead of as a routable account-level script:

alchemy.run.ts
import * as Alchemy from "alchemy";
import * as Cloudflare from "@alchemy.run/cloudflare";
import * as Effect from "effect/Effect";
import { Customers } from "./src/namespace.ts";
import PlatformWorker from "./src/platform.ts";
export default Alchemy.Stack(
"Platform",
{ providers: Cloudflare.providers(), state: Cloudflare.state() },
Effect.gen(function* () {
const namespace = yield* Customers;
yield* Cloudflare.Worker("CustomerA", {
namespace: namespace.name,
script: `export default {
async fetch(request) {
return Response.json({ handledBy: "customer-a" });
},
};`,
});
const platform = yield* PlatformWorker; // defined next
return { url: platform.url.as<string>() };
}),
);

Referencing the namespace’s name output establishes the dependency edge, so the namespace is created before the user Worker is uploaded into it (and the script is deleted first on destroy). The script form takes raw ESM source, typically whatever code your customer uploaded. main with a local entrypoint works too.

Cloudflare.WorkersForPlatforms.Get(namespace) binds the namespace to the Worker and returns a dynamic-dispatch client; dispatch.get(name) looks up a user Worker by script name and returns a Fetcher:

src/platform.ts
import * as Cloudflare from "@alchemy.run/cloudflare";
import * as Effect from "effect/Effect";
import { HttpServerRequest } from "effect/http/HttpServerRequest";
import * as HttpServerResponse from "effect/http/HttpServerResponse";
import { Customers } from "./namespace.ts";
export default class PlatformWorker extends Cloudflare.Worker<PlatformWorker>()(
"PlatformWorker",
{ main: import.meta.filename, workersDev: true },
Effect.gen(function* () {
const dispatch = yield* Cloudflare.WorkersForPlatforms.Get(Customers);
return {
fetch: Effect.gen(function* () {
const request = yield* HttpServerRequest;
// Route however your platform maps requests to customers —
// here the first path segment is the script name.
const url = new URL(request.url, "http://platform");
const match = url.pathname.match(/^\/dispatch\/([^/]+)(\/.*)?$/);
if (!match) {
return HttpServerResponse.text("platform ok");
}
const [, scriptName, rest] = match;
const userWorker = yield* dispatch.get(scriptName).pipe(Effect.orDie);
const response = yield* Effect.promise(() =>
userWorker.fetch(new Request(`https://user-worker${rest ?? "/"}`)),
);
return HttpServerResponse.fromWeb(response);
}),
};
}).pipe(Effect.provide(Cloudflare.WorkersForPlatforms.GetBinding)),
) {}
Platform · WorkerrequestGET /dispatch/customer-a/hellodispatchdispatch.get("customer-a")customer-auser Workerdispatchdispatch.get("customer-b")no matchcustomer-buser WorkerPlatform · WorkerrequestGET /dispatch/customer-a/hellodispatchdispatch.get("customer-a")customer-auser Workerdispatchdispatch.get("customer-b")no matchcustomer-buser Worker
User Workers in the Customers namespace have no URL. Every request reaches the platform Worker, which picks one by script name and forwards the rest of the path.

Provide GetBinding as a layer so the client resolves the native dispatch_namespace runtime binding. A request to /dispatch/customer-a/hello is forwarded to the customer-a user Worker with the trailing path intact; dispatching to a script name that doesn’t exist in the namespace surfaces as an error from the edge, never a user-Worker response.

For a plain async handler, pass the namespace on the Worker’s env instead. InferEnv types it as the native runtime binding:

const platform = Cloudflare.Worker("Platform", {
main: "./src/handler.ts",
workersDev: true,
env: { DISPATCH: Customers },
});
type Env = Cloudflare.InferEnv<typeof platform>;
// src/handler.ts
export default {
async fetch(request: Request, env: Env) {
return env.DISPATCH.get("customer-a").fetch(request);
},
};

env.DISPATCH.get(name) returns the same Fetcher the Effect-native client wraps. Pick whichever style matches the rest of the Worker.

Route user Workers’ requests through an outbound Worker

Section titled “Route user Workers’ requests through an outbound Worker”

A user Worker runs your customer’s code, and by default its fetch() calls go straight to the internet. An outbound Worker is a Worker of yours that receives every one of those calls instead, so you can allow or block the destination, add credentials, or log who called what.

fetch()fetch(request)the internetcustomer-auser WorkerEgressoutbound Workerapi.example.comfetch()fetch(request)the internetcustomer-auser WorkerEgressoutbound Workerapi.example.com
A user Worker dispatched through a binding with an outbound Worker has no route to the internet of its own. Every fetch() it makes arrives at Egress, which decides what to send on.

The outbound Worker is set on the dispatch binding. Declare the binding once, next to the namespace, and pass the Worker as outbound:

src/dispatch.ts
import * as Cloudflare from "@alchemy.run/cloudflare";
import { Customers } from "./namespace.ts";
export const Egress = Cloudflare.Worker("Egress", { main: "./src/egress.ts" });
export const Dispatch = Cloudflare.WorkersForPlatforms.Get(Customers, {
outbound: Egress,
});
src/egress.ts
export default {
fetch(request: Request) {
console.log(`user Worker asked for ${request.url}`);
return fetch(request);
},
};

outbound also takes a Cloudflare.Worker.ref("Egress", { stack: "Shared" }) to an outbound Worker another stack deploys. Cloudflare calls the Worker’s default export.

One outbound Worker serves every customer, so a fetch() that reaches it doesn’t say whose it is. The platform Worker knows, because it just routed the request, and passes that along with the dispatch. Declare the values as the binding’s type and list their names in parameters:

src/dispatch.ts
import * as Cloudflare from "@alchemy.run/cloudflare";
import { Customers } from "./namespace.ts";
export type OutboundParams = { customer: string };
export const Egress = Cloudflare.Worker("Egress", { main: "./src/egress.ts" });
export const Dispatch = Cloudflare.WorkersForPlatforms.Get<OutboundParams>(Customers, {
outbound: Egress,
parameters: ["customer"],
});

The platform Worker yields the binding and gives every value on each dispatch:

src/platform.ts
import * as Cloudflare from "@alchemy.run/cloudflare";
import * as Effect from "effect/Effect";
import { HttpServerRequest } from "effect/http/HttpServerRequest";
import * as HttpServerResponse from "effect/http/HttpServerResponse";
import { Dispatch } from "./dispatch.ts";
export default class PlatformWorker extends Cloudflare.Worker<PlatformWorker>()(
"PlatformWorker",
{ main: import.meta.filename, workersDev: true },
Effect.gen(function* () {
const dispatch = yield* Dispatch;
return {
fetch: Effect.gen(function* () {
const request = yield* HttpServerRequest;
const scriptName = new URL(request.url, "http://platform").pathname.slice(1);
const userWorker = yield* dispatch
.get(scriptName, {}, { outbound: { customer: scriptName } })
.pipe(Effect.orDie);
const response = yield* Effect.promise(() => userWorker.fetch("https://user-worker/"));
return HttpServerResponse.fromWeb(response);
}),
};
}).pipe(Effect.provide(Cloudflare.WorkersForPlatforms.GetBinding)),
) {}

Cloudflare holds a dispatch to exactly the declared names. It refuses one that leaves a value out (Missing one or more required arguments to worker) and one that passes a name parameters doesn’t list (No such worker parameter), so both are compile errors here. Pass null for “no value”. A value can be a string, a number or a plain object.

The user Worker never sees these values. They come from your platform Worker, so the outbound Worker can trust them.

An async outbound Worker reads each value on its env, beside its own bindings:

src/egress.ts
import type { OutboundParams } from "./dispatch.ts";
export default {
fetch(request: Request, env: OutboundParams) {
console.log(`${env.customer} asked for ${request.url}`);
return fetch(request);
},
};

An Effect-native outbound Worker reads them with OutboundParameters, inside the handler:

src/egress.ts
import * as Cloudflare from "@alchemy.run/cloudflare";
import * as Effect from "effect/Effect";
import { HttpServerRequest } from "effect/http/HttpServerRequest";
import * as HttpServerResponse from "effect/http/HttpServerResponse";
import type { OutboundParams } from "./dispatch.ts";
export default class Egress extends Cloudflare.Worker<Egress>()(
"Egress",
{ main: import.meta.filename },
Effect.gen(function* () {
return {
fetch: Effect.gen(function* () {
const request = yield* HttpServerRequest;
const { customer } = yield* Cloudflare.WorkersForPlatforms.OutboundParameters<OutboundParams>();
return HttpServerResponse.text(`${customer} asked for ${request.url}`);
}),
};
}),
) {}

The values belong to one dispatch, and one instance of the outbound Worker serves many, so read them in the handler on every request. The env the Worker was built with (WorkerEnvironment) keeps the values of an earlier dispatch. src/dispatch.ts imports this class and passes it as outbound.

Cloudflare’s preview refuses a dispatch binding that has an outbound Worker, so alchemy dev binds the namespace without it. Dispatches work and take the same outbound values, and user Workers reach the internet directly. Test what the outbound Worker does against a deployed stage.