On @next, the code interpreter is an opt-in extension, not methods on bare Sandbox. Method names match the stable interpreter. You attach once, then call sandbox.interpreter.*. runCode returns plain serializable data across the Worker and Durable Object boundary.
Signatures and types: Interpreter API.
import { Sandbox as BaseSandbox } from "@cloudflare/sandbox";
import { withInterpreter } from "@cloudflare/sandbox/interpreter";
export class Sandbox extends BaseSandbox {
interpreter = withInterpreter(this);
}import { Sandbox as BaseSandbox } from "@cloudflare/sandbox";
import { withInterpreter } from "@cloudflare/sandbox/interpreter";
export class Sandbox extends BaseSandbox<Env> {
interpreter = withInterpreter(this);
}Export that class from your Worker. The sidecar provisions on first use.
| Language | Image |
|---|---|
| JavaScript / TypeScript | Default sandbox image (or any variant with a JS runtime) |
| Python | -python image variant |
Use the same preview Worker package and container image line. Refer to Dockerfile.
A context keeps variables and imports until you delete it or the container is replaced.
const sandbox = getSandbox(env.Sandbox, "user-123");
const context = await sandbox.interpreter.createCodeContext({
language: "python",
cwd: "/workspace",
});
await sandbox.interpreter.runCode("x = 2", { context });
const result = await sandbox.interpreter.runCode("x * 21", { context });
if (result.error) {
console.error(result.error.name, result.error.message);
} else {
console.log(result.results, result.logs.stdout);
}const sandbox = getSandbox(env.Sandbox, "user-123");
const context = await sandbox.interpreter.createCodeContext({
language: "python",
cwd: "/workspace",
});
await sandbox.interpreter.runCode("x = 2", { context });
const result = await sandbox.interpreter.runCode("x * 21", { context });
if (result.error) {
console.error(result.error.name, result.error.message);
} else {
console.log(result.results, result.logs.stdout);
}If you omit context, runCode uses a default context for the language (default language: python). Languages: python, javascript, typescript.
For result fields, streaming (runCodeStream), and list/delete context methods, refer to the Interpreter API.
Contexts exist only in the current container. After stop or replace, create new ones. Refer to Sandbox lifecycle.
- Interpreter API
- Extensions
- Migrate
- Stable guide: Use code interpreter