Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/content/changelog/workers/2025-09-26-ctx-exports.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
title: Automatic loopback bindings via ctx.exports
description: You no longer have to configure bindings explicitly when they point back to your own Worker's top-level exports
date: 2025-09-26
---

The [`ctx.exports` API](/workers/runtime-apis/context/#exports) contains automatically-configured bindings corresponding to your Worker's top-level exports. For each top-level export extending `WorkerEntrypoint`, `ctx.exports` will contain a [Service Binding](/workers/runtime-apis/bindings/service-bindings) by the same name, and for each export extending `DurableObject` (and for which storage has been configured via a [migration](/durable-objects/reference/durable-objects-migrations/)), `ctx.exports` will contain a [Durable Object namespace binding](/durable-objects/api/namespace/). This means you no longer have to configure these bindings explicitly in `wrangler.jsonc`/`wrangler.toml`.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

copy over this code snippet?

https://github.com/cloudflare/cloudflare-docs/pull/25303/files#diff-7157aec1a3a350afe6de7fce2cef85501751923d7af1509ee0fee060811039e4R80-R95

so that the reader can read the code snippet and "get it" faster?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could do before/after

Before:

example code

After:

<less config / zero config>
example code

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copied the example, not really feeling how to do before/after.


At present, you must use [the `enable_ctx_exports` compatibility flag](/workers/configuration/compatibility-flags#enable-ctxexports) to enable this API, though it will be on by default in the future.

[See the API reference for more information.](/workers/runtime-apis/context/#exports)
14 changes: 14 additions & 0 deletions src/content/compatibility-flags/enable-ctx-exports.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
_build:
publishResources: false
render: never
list: never

name: "Enable ctx.exports"
sort_date: "2025-09-24"
enable_flag: "enable_ctx_exports"
---

This flag enables [the `ctx.exports` API](/workers/runtime-apis/context/#exports), which contains automatically-configured loopback bindings for your Worker's top-level exports. This allows you to skip configuring explicit bindings for your `WorkerEntrypoint`s and Durable Object namespaces defined in the same Worker.

We may change this API to be enabled by default in the future (regardless of compat date or flags).
6 changes: 5 additions & 1 deletion src/content/docs/durable-objects/api/state.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,11 @@ export class MyDurableObject extends DurableObject {

</TabItem> </Tabs>

## Methods
## Methods and Properties

### `exports`

Contains loopback bindings to the Worker's own top-level exports. This has exactly the same meaning as [`ExecutionContext`'s `ctx.exports`](/workers/runtime-apis/context/#exports).

### `waitUntil`

Expand Down
227 changes: 227 additions & 0 deletions src/content/docs/workers/runtime-apis/bindings/worker-loader.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
---
pcx_content_type: configuration
title: Dynamic Worker Loaders
head: []
description: The Dynamic Worker Loader API, which allows dynamically spawning isolates that run arbitrary code.

---

import {
Type,
MetaInfo,
WranglerConfig
} from "~/components";

:::note[Dynamic Worker Loading is in closed beta]

The Worker Loader API is available in local development with Wrangler and workerd. But, to use it in production, you must [sign up for the closed beta](https://forms.gle/MoeDxE9wNiqdf8ri9).

:::

A Worker Loader binding allows you to load additional Workers containing arbitrary code at runtime.

An isolate is like a lightweight container. [The Workers platform uses isolates instead of containers or VMs](/workers/reference/how-workers-works/), so every Worker runs in an isolate already. But, a Worker Loader binding allows your Worker to create additional isolates that load arbitrary code on-demand.

Isolates are much cheaper than containers. You can start an isolate in milliseconds, and it's fine to start one just to run a snippet of code and immediately throw away. There's no need to worry about pooling isolates or trying to reuse already-warm isolates, as you would need to do with containers.

Worker Loaders also enable **sandboxing** of code, meaning that you can strictly limit what the code is allowed to do. In particular:
* You can arrange to intercept or simply block all network requests made by the Worker within.
* You can supply the sandboxed Worker with custom bindings to represent specific resources which it should be allowed to access.

With proper sandboxing configured, you can safely run code you do not trust in a dynamic isolate.

A Worker Loader is a binding with just one method, `get()`, which loads an isolate. Example usage:

```js
let id = "foo";

// Get the isolate with the given ID, creating it if no such isolate exists yet.
let worker = env.LOADER.get(id, async () => {
// If the isolate does not already exist, this callback is invoked to fetch
// the isolate's Worker code.

return {
compatibilityDate: "2025-06-01",

// Specify the worker's code (module files).
mainModule: "foo.js",
modules: {
"foo.js":
"export default {\n" +
" fetch(req, env, ctx) { return new Response('Hello'); }\n" +
"}\n",
},

// Specify the dynamic Worker's environment (`env`). This is specified
// as a JavaScript object, exactly as you want it to appear to the
// child Worker. It can contain basic serializable types as well as
// Service Bindings (see below).
env: {
SOME_ENV_VAR: 123
},

// To block the worker from talking to the internet using `fetch()` or
// `connect()`, set `globalOutbound` to `null`. You can also set this
// to any service binding, to have calls be intercepted and redirected
// to that binding.
globalOutbound: null,
};
});

// Now you can get the Worker's entrypoint and send requests to it.
let defaultEntrypoint = worker.getEntrypoint();
await defaultEntrypoint.fetch("http://example.com");

// You can get non-default entrypoints as well, and specify the
// `ctx.props` value to be delivered to the entrypoint.
let someEntrypoint = worker.getEntrypoint("SomeEntrypointClass", {
props: {someProp: 123}
});
```

## Configuration

To add a dynamic worker loader binding to your worker, add it to your Wrangler config like so:

<WranglerConfig>

```toml
[[worker_loaders]]
binding = "LOADER"
```

</WranglerConfig>

## API Reference

### `get`

<code>get(id <Type text="string" />, getCodeCallback <Type text="() => Promise<WorkerCode>" />): <Type text="WorkerStub" /></code>

Loads a Worker with the given ID.

As a convenience, the loader implements basic caching of isolates: If this loader has already been used to load a Worker with the same ID in the past, and that Worker's isolate is still resident in memory, then the existing Worker will be returned, and the callback will not be called. When an isolate has not been used in a while, the system will discard it automatically, and then the next attempt to get the same ID will have to load it again. If you frequently run the same code, you should use the same ID in order to get automatic caching. On the other hand, if the code you load is different every time, you can provide a random ID. Note that if your code has many versions, each version will need a unique ID, as there is no way to explicitly evict a previous version.
Copy link
Contributor

@irvinebroque irvinebroque Sep 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
As a convenience, the loader implements basic caching of isolates: If this loader has already been used to load a Worker with the same ID in the past, and that Worker's isolate is still resident in memory, then the existing Worker will be returned, and the callback will not be called. When an isolate has not been used in a while, the system will discard it automatically, and then the next attempt to get the same ID will have to load it again. If you frequently run the same code, you should use the same ID in order to get automatic caching. On the other hand, if the code you load is different every time, you can provide a random ID. Note that if your code has many versions, each version will need a unique ID, as there is no way to explicitly evict a previous version.
As a convenience, the loader implements basic caching of isolates: If this loader has already been used to load a Worker with the same ID in the past, and that Worker's isolate is still resident in memory, then the existing Worker will be returned, and the callback will not be called. When an isolate has not been used in a while, the system will discard it automatically, and then the next attempt to get the same ID will have to load it again.
This means that anytime you update any value returned by the callback (the isolate's code and its configuration), you must use a different ID if you need to guarantee that the updated values will be used.
Best practices:
- If you frequently run the same code with the same configuration provided in the callback, you should use the same ID in order to get automatic caching.
- If the code or configuration you load is different every time, you should provide a random ID.
Note that if your code has many versions, each version will need a unique ID, as there is no way to explicitly evict a previous version.

Thinking about ways to be explicit to people that this means not just that if the code changes you need new ID, but that if the config provided via the callback changes, you also need new ID...

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

riffing on how to be super clear about this...can take or leave language

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At the same time as you were suggesting this I was tweaking my own text a bit, but now I gotta run, so I'll come back and see if I can merge yours and mine later.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK I rewrote this section again, I think it's clearer now, hopefully.


If the system opts not to reuse an existing Worker, then it invokes `codeCallback` to get the Worker's code. This is an async callback, so the application can load the code from remote storage if desired. The callback returns a `WorkerCode` object (described below).

`get()` returns a `WorkerStub`, which can be used to send requests to the loaded Worker. Note that the stub is returned synchronously&mdash;you do not have to await it. If the Worker is not loaded yet, requests made to the stub will wait for the Worker to load before being delivered. If loading fails, the request will throw an exception.

### `WorkerCode`

This is the structure returned by `getCodeCallback` to represent a worker.

#### <code>compatibilityDate <Type text="string" /></code>

The [compatibility date](/workers/configuration/compatibility-dates/) for the Worker. This has the same meaning as the `compatibility_date` setting in a Wrangler config file.

#### <code>compatibilityFlags <Type text="string[]" /> <MetaInfo text='Optional' /></code>

An optional list of [compatibility flags](/workers/configuration/compatibility-flags) augmenting the compatibility date. This has the same meaning as the `compatibility_flags` setting in a Wrangler config file.

#### <code>allowExperimental <Type text="boolean" /> <MetaInfo text='Optional' /></code>

If true, then experimental compatibility flags will be permitted in `compatibilityFlags`. In order to set this, the worker calling the loader must itself have the compatibility flag `"experimental"` set. Experimental flags cannot be enabled in production.

#### <code>mainModule <Type text="string" /></code>

The name of the Worker's main module. This must be one of the modules listed in `modules`.

#### <code>modules <Type text="Record<string, string | Module>"/></code>

A dictionary object mapping module names to their string contents. If the module content is a plain string, then the module name must have a file extension indicating its type: either `.js` or `.py`.

A module's content can also be specified as an object, in order to specify its type independent from the name. The allowed objects are:

* `{js: string}`: A JavaScript module, using ES modules syntax for imports and exports.
* `{cjs: string}`: A CommonJS module, using `require()` syntax for imports.
* `{py: string}`: A [Python module](/workers/languages/python/), but see the warning below.
* `{text: string}`: An importable string value.
* `{data: ArrayBuffer}`: An importable `ArrayBuffer` value.
* `{json: object}`: An importable object. The value must be JSON-serializable. However, note that value is provided as a parsed object, and is delivered as a parsed object; neither side actually sees the JSON serialization.

:::caution[Warning]

While Dynamic Isolates support Python, please note that at this time, Python Workers are much slower to start than JavaScript Workers, which may defeat some of the benefits of dynamic isolate loading. They may also be priced differently, when Worker Loaders become generally available.

:::

#### <code>globalOutbound <Type text="ServiceStub | null" /> Optional</code>

Controls whether the dynamic Worker has access to the network. The global `fetch()` and `connect()` functions (for making HTTP requests and TCP connections, respectively) can be blocked or redirected to isolate the Worker.

If `globalOutbound` is not specified, the default is to inherit the parent's network access, which usually means the dynamic Worker will have full access to the public Internet.

If `globalOutbound` is `null`, then the dynamic Worker will be totally cut off from the network. Both `fetch()` and `connect()` will throw exceptions.

`globalOutbound` can also be set to any service binding, including service bindings in the parent worker's `env` as well as [loopback bindings from `ctx.exports`](/workers/runtime-apis/context/#exports).

Using `ctx.exports` is particularly useful as it allows you to customize the binding further for the specific sandbox, by setting the value of `ctx.props` that should be passed back to it. The `props` can contain information to identify the specific dynamic Worker that made the request.

For example:

```js
import { WorkerEntrypoint } from "cloudflare:workers";

export class Greeter extends WorkerEntrypoint {
fetch(request) {
return new Response(`Hello, ${this.ctx.props.name}!`);
}
}

export default {
async fetch(request, env, ctx) {
let worker = env.LOADER.get("alice", () => {
return {
// Redirect the worker's global outbound to send all requests
// to the `Greeter` class, filling in `ctx.props.name` with
// the name "Alice", so that it always responds "Hello, Alice!".
globalOutbound: ctx.exports.Greeter({props: {name: "Alice"}})

// ... code ...
}
});
}
}
```

#### <code>env <Type text="object" /></code>

The environment object to provide to the dynamic Worker.

Using this, you can provide custom bindings to the Worker.

`env` is serialized and transferred into the dynamic Worker, where it is used directly as the value of `env` there. It may contain:

* [Structured clonable types](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
* [Service Bindings](/workers/runtime-apis/bindings/service-bindings), including [loopback bindings from `ctx.exports`](/workers/runtime-apis/context/#exports).

The second point is the key to creating custom bindings: you can define a binding with any arbitrary API, by defining a [`WorkerEntrypoint` class](/workers/runtime-apis/bindings/service-bindings/rpc) implementing an RPC API, and then giving it to the dynamic Worker as a Service Binding.

Moreover, by using `ctx.exports` loopback bindings, you can further customize the bindings for the specific dynamic Worker by setting `ctx.props`, just as described for `globalOutbound`, above.

```js
import { WorkerEntrypoint } from "cloudflare:workers";

// Implement a binding which can be called by the dynamic Worker.
export class Greeter extends WorkerEntrypoint {
greet() {
return `Hello, ${this.ctx.props.name}!`;
}
}

export default {
async fetch(request, env, ctx) {
let worker = env.LOADER.get("alice", () => {
return {
env: {
// Provide a binding which has a method greet() which can be called
// to receive a greeting. The binding knows the Worker's name.
GREETER: ctx.exports.Greeter({props: {name: "Alice"}})
}

// ... code ...
}
});
}
}
```
Loading
Loading