Dynamic Worker Loader: Runtime Sandboxing, Bindings and Limits
How Cloudflare Dynamic Workers and the Worker Loader API run untrusted code at runtime with load(), get(), bindings, and network isolation.
This page summarises Cloudflare documentation on Dynamic Workers: Workers your host Worker creates at runtime to run code you do not fully trust—model-generated scripts, per-tenant logic, or user uploads—in an isolated sandbox with explicit capabilities instead of inherited secrets.
Spin up Workers at runtime to execute code on-demand in a secure, sandboxed environment.
— Cloudflare, Dynamic Workers
Dynamic Workers are available to paid Workers accounts as an open beta product; they start in milliseconds and suit agents, code interpreters, and multi-tenant platforms. The lowest-level control surface is the Worker Loader binding (env.LOADER), exposed after you add a worker_loaders entry in Wrangler.
Worker Loader API: load() vs get() for on-demand code
Section titled “Worker Loader API: load() vs get() for on-demand code”The Worker Loader API reference assumes a binding configured as env.LOADER. Two methods cover the usual “run once” vs “run again” choices described in Getting started.
| Method | When to use | Caching |
|---|---|---|
env.LOADER.load(WorkerCode) |
One-off execution (e.g. each AI-generated snippet) | Every call creates a new Worker |
env.LOADER.get(id, getCodeCallback) |
Same logical code across requests | Runtime may reuse a warm isolate for that id |
Unlike
get(),load()does not cache by ID. Each call creates a new Worker. Useload()when the code is always new, such as for one-time AI-generated tool calls.— Cloudflare, API reference — load
For get(), the callback must return the same WorkerCode for a given id; if content changes, use a new id (version suffix or hash). The stub returns synchronously, but requests wait until load completes. Cloudflare does not guarantee that two requests hit the same isolate, even with the same stub—design for idempotent callbacks and no hidden in-sandbox durable state unless you add bindings or Workflows.
WorkerCode: modules, mainModule, and language limits
Section titled “WorkerCode: modules, mainModule, and language limits”A WorkerCode object names mainModule (must appear in modules) and a modules map of filenames to source strings or typed module objects ({js: string}, {py: string}, {wasm: ArrayBuffer}, etc.). See API reference — WorkerCode.
Python is supported with the python_workers compatibility flag, but:
While Dynamic Workers support Python, Python Workers are currently much slower to start than JavaScript Workers. For one-off AI-generated code, we strongly recommend using JavaScript.
— Cloudflare, API reference — modules
There is no TypeScript compile step inside the loader—bundle first with @cloudflare/worker-bundler or the Dynamic Workers Playground pattern, then pass mainModule and modules to load() or get().
How to point a Dynamic Worker at an entrypoint
Section titled “How to point a Dynamic Worker at an entrypoint”After loading, call worker.getEntrypoint() for the default export or worker.getEntrypoint("ClassName") for a named WorkerEntrypoint class. The Dynamic Workers Starter loads user POSTed code, sets globalOutbound: null, and forwards a request to the sandbox entrypoint.
Network sandbox: globalOutbound and what code cannot inherit
Section titled “Network sandbox: globalOutbound and what code cannot inherit”From Choose a sandbox environment: code in a Dynamic Worker uses Workers runtime APIs plus what you pass in; it does not inherit the loader Worker’s bindings, credentials, or data. It can reach the Internet unless you block egress.
Setting globalOutbound: null blocks fetch() and connect() from the Dynamic Worker. That is the default posture for Build an AI code interpreter and for DynamicWorkerExecutor in Code Mode:
Network isolation —
fetch()andconnect()blocked by default (globalOutbound: null) when usingDynamicWorkerExecutor— Cloudflare, @cloudflare/codemode v0.1.0 changelog
You can also pass a Fetcher to intercept or allow outbound traffic (egress control is listed under Usage). For authenticated APIs, expose methods on a custom binding in the loader Worker (token stays there); see Call an authenticated API from a sandbox.
Pair network lockdown with resource limits where needed—for example limits: { cpuMs: 50 } in the interpreter tutorial—and an outer wall-clock timeout in the host Worker, since waiting without CPU can outlive CPU limits.
Bindings: capability-based access and custom WorkerEntrypoint stubs
Section titled “Bindings: capability-based access and custom WorkerEntrypoint stubs”Bindings with Dynamic Workers let you decide exactly what each sandbox can do: partition KV/R2 via wrapper classes, expose RPC methods, or reject calls before they hit real resources.
Bindings let you control what a Dynamic Worker can access. When you create a Dynamic Worker, you decide exactly what resources and operations it can use.
— Cloudflare, Bindings
The pattern: define a class extending WorkerEntrypoint in the loader Worker, create a stub with ctx.exports.YourClass({ props: { ... } }), and pass it in WorkerCode.env. Props (API keys, tenant prefixes) are visible only in the loader; the Dynamic Worker calls this.env.CHAT_ROOM.post(...) without seeing secrets.
Custom bindings follow a capability-based security model: a Dynamic Worker can only access what you explicitly give it.
— Cloudflare, Bindings — Capability-based sandboxing
The env object in WorkerCode may include structured-cloneable data and Service Bindings, including loopback stubs from ctx.exports—the extension point for per-user APIs (API reference — env).
For agents, Cloudflare recommends TypeScript declarations with doc comments so models know the binding surface (Bindings — chat room example).
Code Mode and DynamicWorkerExecutor for agent tool orchestration
Section titled “Code Mode and DynamicWorkerExecutor for agent tool orchestration”How Code Mode works treats an executor as one shot of model-written code: result, error, and captured logs—no durable history inside the sandbox.
DynamicWorkerExecutor (@cloudflare/codemode) loads an isolated Dynamic Worker per execution, routes codemode.* calls back to real tools over Workers RPC, captures console output, and defaults to a 30s timeout. Optional modules inject helper ES modules (v0.2.1 changelog).
For MCP hosts, Build a Code Mode MCP server states that code execution does not replace authorization—enforce permissions in tool handlers before side effects, and do not leak credentials through tool results.
Wrangler needs:
{ "worker_loaders": [{ "binding": "LOADER" }]}as shown in the Code Mode API reference and codemode changelogs.
Persistence patterns: Durable Object Facets and Dynamic Workflows
Section titled “Persistence patterns: Durable Object Facets and Dynamic Workflows”Ephemeral sandboxes: each load() is a new isolate; variables do not carry across runs (Replace the code interpreter).
Facet storage: Durable Object Facets load a DurableObject class from dynamic code under a supervisor; the facet gets its own SQLite-backed storage, isolated from the parent’s database—useful when generated apps need persistence without direct namespace access.
Durable steps: @cloudflare/dynamic-workflows connects the Worker Loader to the Workflows engine so runtime-loaded Workflow code can step.sleep() and resume after isolate recycling. The loader re-exports DynamicWorkflowBinding, uses wrapWorkflowBinding({ tenantId }) for routing metadata (not secrets), and createDynamicWorkflowEntrypoint to reload tenant code when a step wakes. Full setup is in the Dynamic Workflows guide and changelog post.
Dynamic Workers vs Containers: when to pick which
Section titled “Dynamic Workers vs Containers: when to pick which”Choose a sandbox environment contrasts Linux Containers (full image, processes, packages) with Dynamic Workers when generated code only needs a curated method API on the Workers runtime. Dynamic Workers fit “call known methods, block raw network” agent Code Mode; Containers fit arbitrary Linux tooling and cold-start trade-offs.
Common mistakes:
- Assuming the sandbox inherits
envfrom the host Worker without passing an explicitWorkerCode.env. - Putting secrets in Workflow metadata passed to
wrapWorkflowBinding(metadata is persisted; use props on loader-side bindings instead). - Reusing a
get()idafter code changes. - Expecting warm-isolate guarantees across requests.
- Running Python for latency-sensitive one-off generated code.
Templates to learn from: Dynamic Workers Starter, Dynamic Workers Playground, Code Mode Example, Examples index.
How to check this on your site
Section titled “How to check this on your site”- Add a
worker_loadersbinding namedLOADERper Getting started — Configure Worker Loader and runnpx wrangler deploy(or yarn/pnpm equivalents from Call an authenticated API). - Deploy the Dynamic Workers Starter, optionally the Dynamic Workers Playground, or your own handler that calls
env.LOADER.load()withglobalOutbound: null. - POST test code to your endpoint and confirm the response; for interpreters, compare
resultandlogsshape with Build an AI code interpreter. - Verify egress: sandbox
fetch()to the public Internet should fail whenglobalOutbound: null; allowed calls should only succeed via bindings you defined (Bindings). - You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page does not match current Cloudflare behaviour, or you need a clarification on Dynamic Workers, Worker Loader, or sandbox bindings, email yimasynthetic@gmail.com with the page URL and the exact statement you are questioning.