Skip to content

Dynamic Workers

A Dynamic Worker is code that a Worker loads at runtime through a Worker Loader binding, such as code that a customer uploads or a model writes. workerd compiles the code into a separate V8 isolate in the same process. Cloudflare runs this feature in an open beta, so the API can change. Read the Cloudflare Dynamic Workers documentation and the API reference for the API.

workerd refuses worker_loaders in a wrangler.json, so the example uses a config.capnp, the native workerd configuration format. The Worker Loader binding is experimental and needs --experimental.

Example

The Dynamic Workers example loads a Worker from a string and sends its console logs to a Tail Worker.

config.capnptext
using Workerd = import "/workerd/workerd.capnp";

const config :Workerd.Config = (
  services = [(name = "main", worker = .worker)],
  sockets = [
    (name = "http", address = "localhost:8787", http = (), service = "main"),
  ],
);

const worker :Workerd.Worker = (
  modules = [(name = "index.js", esModule = embed "index.js")],
  compatibilityDate = "2026-01-01",
  bindings = [(name = "LOADER", workerLoader = ())],
);
index.jsjs
import { WorkerEntrypoint } from "cloudflare:workers";

const WORKER_ID = "hello-v1";
const WORKER_MAIN = "worker.js";
const WORKER_SOURCE = `
  export default {
    fetch() {
      console.log("hello from loaded code");
      return new Response("Hello from a Dynamic Worker!\\n");
    }
  };
`;

export class DynamicWorkerTail extends WorkerEntrypoint {
  tail(events) {
    for (const event of events) {
      for (const log of event.logs) {
        console.log(`dynamic-worker-tail: ${log.message.join(" ")}`, {
          workerId: this.ctx.props.workerId,
          level: log.level,
        });
      }
    }
  }
}

export default {
  fetch(request, env, ctx) {
    const worker = env.LOADER.get(WORKER_ID, () => ({
      compatibilityDate: "2025-01-01",
      mainModule: WORKER_MAIN,
      modules: { [WORKER_MAIN]: WORKER_SOURCE },
      tails: [
        ctx.exports.DynamicWorkerTail({
          props: { workerId: WORKER_ID },
        }),
      ],
    }));
    return worker.getEntrypoint().fetch(request);
  },
};
npx workerd serve --experimental ./dynamic-worker-tails/config.capnp
curl http://localhost:8787/

workerd prints the log line of the loaded Worker, then the copy that the Tail Worker receives.

Dynamic Workers work in a cluster. To join one, a config.capnp also needs a writable disk service named do-storage. Each instance compiles the code that it loads, and a loaded Worker never moves to another instance. A loaded Worker’s modules can total 64 MiB, and its env 1 MiB.

Differences from Cloudflare

  • The loaded isolate runs in the workerd process, and workerd is not a hardened sandbox. Run untrusted code in a virtual machine.

See also Cloudflare compatibility.

Type to search…

↑↓ navigate↵ selectEsc close