Lifecycle
Create and manage sandbox containers. Get sandbox instances, configure options, and clean up resources.
Get or create a sandbox instance by ID.
const sandbox = getSandbox( binding: DurableObjectNamespace<Sandbox>, sandboxId: string, options?: SandboxOptions): SandboxParameters:
binding- The Durable Object namespace binding from your Worker environmentsandboxId- Unique identifier for this sandbox. The same ID always returns the same sandbox instanceoptions(optional):keepAlive- Set totrueto prevent automatic container timeout after 10 minutes of inactivity
Returns: Sandbox instance
import { getSandbox } from "@cloudflare/sandbox";
export default { async fetch(request, env) { const sandbox = getSandbox(env.Sandbox, "user-123"); const result = await sandbox.exec("python script.py"); return Response.json(result); },};import { getSandbox } from '@cloudflare/sandbox';
export default { async fetch(request: Request, env: Env): Promise<Response> { const sandbox = getSandbox(env.Sandbox, 'user-123'); const result = await sandbox.exec('python script.py'); return Response.json(result); }};Destroy the sandbox container and free up resources.
await sandbox.destroy(): Promise<void>Immediately terminates the container and permanently deletes all state:
- All files in
/workspace,/tmp, and/home - All running processes
- All sessions (including the default session)
- Network connections and exposed ports
async function executeCode(code) { const sandbox = getSandbox(env.Sandbox, `temp-${Date.now()}`);
try { await sandbox.writeFile("/tmp/code.py", code); const result = await sandbox.exec("python /tmp/code.py"); return result.stdout; } finally { await sandbox.destroy(); }}async function executeCode(code: string): Promise<string> { const sandbox = getSandbox(env.Sandbox, `temp-${Date.now()}`);
try { await sandbox.writeFile('/tmp/code.py', code); const result = await sandbox.exec('python /tmp/code.py'); return result.stdout; } finally { await sandbox.destroy(); }}- Sandbox lifecycle concept - Understanding container lifecycle and state
- Sandbox options configuration - Configure
keepAliveand other options - Sessions API - Create isolated execution contexts within a sandbox
Was this helpful?
- Resources
- API
- New to Cloudflare?
- Directory
- Sponsorships
- Open Source
- Support
- Help Center
- System Status
- Compliance
- GDPR
- Company
- cloudflare.com
- Our team
- Careers
- © 2025 Cloudflare, Inc.
- Privacy Policy
- Terms of Use
- Report Security Issues
- Trademark