Skip to content

Dynamic Workers Starter

A starter template for deploying a Worker that loads and runs Dynamic Workers.

Deploy to Workers

What it does

This template demonstrates how to use the Worker Loader API to execute code at runtime. The host Worker exposes an /api/run endpoint that accepts code from the frontend, loads it into a sandboxed Dynamic Worker, and returns the result.

Use this pattern for AI agents that need to execute a snippet of code to complete an action.

Configuration

Add a worker_loaders binding to your Wrangler file:

JSONC
{
"worker_loaders": [
{
"binding": "LOADER"
}
]
}

Loading and executing a Dynamic Worker

In this example:

  • env.LOADER.load() creates a one-off dynamic isolate
  • globalOutbound: null blocks all outbound network access from the Dynamic Worker
JavaScript
export default {
async fetch(request, env) {
const { code } = await request.json();
const worker = env.LOADER.load({
compatibilityDate: "2026-05-01",
mainModule: "worker.js",
modules: {
"worker.js": code,
},
// Block all outbound network access
globalOutbound: null,
});
const result = await worker.getEntrypoint().fetch(request);
return result;
},
};

Running locally

Terminal window
npm install
npm run dev