Code Sandbox
Run a JavaScript snippet in an isolated Sandbox SDK container
Run a JavaScript snippet in an isolated environment using the Cloudflare Sandbox SDK (@cloudflare/sandbox) backed by Containers and a Durable Object.
API Reference
POST /exec
Execute code and return stdout, stderr, and exit code.
language string (required)
Currently only javascript is supported.
code string (required)
Snippet to run. Max length 5,000 characters.
Example Request
curl -X POST "https://your-worker.workers.dev/exec" \
-H "Content-Type: application/json" \
-d '{"language":"javascript","code":"console.log(2 + 2)"}'Success Response
{
"stdout": "4\n",
"stderr": "",
"exitCode": 0
}Error Codes
400- Invalid body, language, or code (INVALID_BODY,INVALID_LANGUAGE,INVALID_CODE)502- Sandbox execution failure (EXEC_ERROR)
Use Cases
- Learn Sandbox SDK
getSandbox+execpatterns - Safely evaluate untrusted JavaScript snippets at the edge
- Prototype coding tutors or REPL APIs
- Compare Sandbox containers vs Dynamic Workers isolation
Limitations
- Only
javascriptis supported in this demo - Code max length 5,000 characters
- Docker required for local
wrangler dev/ deploy - Container
max_instancesis 1 (liteinstance type)
Deployment
Deploy
Wrangler builds the sandbox image, registers the Sandbox Durable Object, and enables nodejs_compat.
Test your deployment
curl -X POST "https://your-worker.workers.dev/exec" \
-H "Content-Type: application/json" \
-d '{"language":"javascript","code":"console.log(2 + 2)"}'Local Development
Docker must be running for container image builds.
cd apps/experiments/code-sandbox
npm install
npm run devcurl -X POST "http://localhost:8787/exec" \
-H "Content-Type: application/json" \
-d '{"language":"javascript","code":"console.log(2 + 2)"}'Unit tests mock the sandbox client so Docker is not required for npm run test.
Configuration
wrangler.json declares:
- Container
Sandboxfrom./Dockerfile(instance_type: lite) - Durable Object binding
Sandbox→ classSandbox - Compatibility flag
nodejs_compat
Cloudflare Features Used
- Workers - Edge compute runtime
- Sandbox SDK - Isolated code execution
- Containers - Official sandbox image
- Durable Objects - Sandbox class binding