---
description: Build secure, isolated code execution environments powered by Cloudflare Workers and Containers.
title: Sandbox SDK
image: https://developers.cloudflare.com/og-docs.png
---

[Skip to content](#main-content)

> Documentation Index  
> Fetch the complete documentation index at: https://developers.cloudflare.com/sandbox/llms.txt  
> Use this file to discover all available pages before exploring further.

# Sandbox SDK

Last updated Aug 24, 2026|Copy as Markdown|[View as Markdown](https://e8aee267.previews.developers.cloudflare.com/sandbox/index.md)|[Agent setup](https://e8aee267.previews.developers.cloudflare.com/agent-setup/)

Build secure, isolated code execution environments

Available on Workers Paid plan

Sandbox SDK 1.0 preview

These pages document the current stable `@cloudflare/sandbox` package. The next major release is **Sandbox SDK 1.0**, available as a preview on `@cloudflare/sandbox@next`.

We recommend starting new projects on the preview, and migrating existing apps when you can, so you are ready when 1.0 becomes the stable release. Refer to the [1.0 preview](https://e8aee267.previews.developers.cloudflare.com/sandbox/1-0-preview/) section for install, concepts, API reference, and migration.

The Sandbox SDK enables you to run untrusted code securely in isolated environments. Built on [Containers](https://e8aee267.previews.developers.cloudflare.com/containers/), Sandbox SDK provides a simple API for executing commands, managing files, running background processes, and exposing services — all from your [Workers](https://e8aee267.previews.developers.cloudflare.com/workers/) applications.

Sandboxes are ideal for building AI agents that need to execute code, interactive development environments, data analysis platforms, CI/CD systems, and any application that needs secure code execution at the edge. Each sandbox runs in its own isolated container with a full Linux environment, providing strong security boundaries while maintaining performance.

With Sandbox, you can execute Python scripts, run Node.js applications, analyze data, compile code, and perform complex computations — all with a simple TypeScript API and no infrastructure to manage.

```typescript
import { getSandbox } from '@cloudflare/sandbox';

export { Sandbox } from '@cloudflare/sandbox';

export default {
	async fetch(request: Request, env: Env): Promise<Response> {
		const sandbox = getSandbox(env.Sandbox, 'user-123');

		// Execute a command and get the result
		const result = await sandbox.exec('python --version');

		return Response.json({
			output: result.stdout,
			exitCode: result.exitCode,
			success: result.success
		});
	}
};
```

```typescript
import { getSandbox } from '@cloudflare/sandbox';

export { Sandbox } from '@cloudflare/sandbox';

export default {
	async fetch(request: Request, env: Env): Promise<Response> {
		const sandbox = getSandbox(env.Sandbox, 'user-123');

		// Create a Python execution context
		const ctx = await sandbox.createCodeContext({ language: 'python' });

		// Execute Python code with automatic result capture
		const result = await sandbox.runCode(`
import pandas as pd
data = {'product': ['A', 'B', 'C'], 'sales': [100, 200, 150]}
df = pd.DataFrame(data)
df['sales'].sum()  # Last expression is automatically returned
	`, { context: ctx });

			return Response.json({
				result: result.results?.[0]?.text,
				logs: result.logs
			});
		}
	};
```

```typescript
import { getSandbox } from '@cloudflare/sandbox';

export { Sandbox } from '@cloudflare/sandbox';

export default {
	async fetch(request: Request, env: Env): Promise<Response> {
		const sandbox = getSandbox(env.Sandbox, 'user-123');

		// Create a project structure
		await sandbox.mkdir('/workspace/project/src', { recursive: true });

		// Write files
		await sandbox.writeFile(
			'/workspace/project/package.json',
			JSON.stringify({ name: 'my-app', version: '1.0.0' })
		);

		// Read a file back
		const content = await sandbox.readFile('/workspace/project/package.json');

		return Response.json({ content });
	}
};
```

```typescript
import { getSandbox } from '@cloudflare/sandbox';

export { Sandbox } from '@cloudflare/sandbox';

export default {
	async fetch(request: Request, env: Env): Promise<Response> {
		const sandbox = getSandbox(env.Sandbox, 'user-123');

		// Watch for file changes in real-time
		const watcher = await sandbox.watch('/workspace/src', {
			include: ['*.js', '*.ts'],
			onEvent: (event) => {
				console.log(`${event.type}: ${event.path}`);
				if (event.type === 'modify') {
					// Trigger rebuild or hot reload
					console.log('Code changed, recompiling...');
				}
			},
			onError: (error) => {
				console.error('Watch error:', error);
			}
		});

		// Stop watching when done
		setTimeout(() => watcher.stop(), 60000);

		return Response.json({ message: 'File watcher started' });
	}
};
```

```typescript
import { getSandbox } from '@cloudflare/sandbox';

export { Sandbox } from '@cloudflare/sandbox';

export default {
	async fetch(request: Request, env: Env): Promise<Response> {
		const url = new URL(request.url);

		// Terminal WebSocket connection
		if (url.pathname === '/ws/terminal') {
			const sandbox = getSandbox(env.Sandbox, 'user-123');
			return sandbox.terminal(request, { cols: 80, rows: 24 });
		}

		return Response.json({ message: 'Terminal endpoint' });
	}
};
```

Connect browser terminals directly to sandbox shells via WebSocket. Learn more: [Browser terminals](https://e8aee267.previews.developers.cloudflare.com/sandbox/guides/browser-terminals/).

```typescript
import { getSandbox } from '@cloudflare/sandbox';

export { Sandbox } from '@cloudflare/sandbox';

export default {
	async fetch(request: Request, env: Env): Promise<Response> {
		// Connect to WebSocket services in sandbox
		if (request.headers.get('Upgrade')?.toLowerCase() === 'websocket') {
			const sandbox = getSandbox(env.Sandbox, 'user-123');
			return await sandbox.wsConnect(request, 8080);
		}

		return Response.json({ message: 'WebSocket endpoint' });
	}
};
```

Connect to WebSocket servers running in sandboxes. Learn more: [WebSocket Connections](https://e8aee267.previews.developers.cloudflare.com/sandbox/guides/websocket-connections/).

[Get started](https://e8aee267.previews.developers.cloudflare.com/sandbox/get-started/)[API Reference](https://e8aee267.previews.developers.cloudflare.com/sandbox/api/) 

---

## Features

[Deploy a Sandbox application](https://e8aee267.previews.developers.cloudflare.com/sandbox/guides/deploy/)

Deploy your Worker and keep the npm package and container image on the same release line.

Deploy a Sandbox app

[Execute commands securely](https://e8aee267.previews.developers.cloudflare.com/sandbox/guides/execute-commands/)

Run shell commands, Python scripts, Node.js applications, and more with streaming output support and automatic timeout handling.

Learn about command execution

[Manage files and processes](https://e8aee267.previews.developers.cloudflare.com/sandbox/guides/manage-files/)

Read, write, and manipulate files in the sandbox filesystem. Run background processes, monitor output, and manage long-running operations.

Learn about file operations

[Expose services with preview URLs](https://e8aee267.previews.developers.cloudflare.com/sandbox/guides/expose-services/)

Expose HTTP services running in your sandbox with automatically generated preview URLs, perfect for interactive development environments and application hosting.

Learn about preview URLs

[Execute code directly](https://e8aee267.previews.developers.cloudflare.com/sandbox/guides/code-execution/)

Execute Python and JavaScript code with rich outputs including charts, tables, and images. Maintain persistent state between executions for AI-generated code and interactive workflows.

Learn about code execution

[Build interactive terminals](https://e8aee267.previews.developers.cloudflare.com/sandbox/guides/browser-terminals/)

Create browser-based terminal interfaces that connect directly to sandbox shells via WebSocket. Build collaborative terminals, interactive development environments, and real-time shell access with automatic reconnection.

Learn about terminal UIs

[Persistent storage with object storage](https://e8aee267.previews.developers.cloudflare.com/sandbox/guides/mount-buckets/)

Mount S3-compatible object storage (R2, S3, GCS, and more) as local filesystems. Access buckets using standard file operations with data that persists across sandbox lifecycles. Production deployment required.

Learn about bucket mounting

[Watch files for real-time changes](https://e8aee267.previews.developers.cloudflare.com/sandbox/guides/file-watching/)

Monitor files and directories for changes using native filesystem events. Perfect for building hot reloading development servers, build automation systems, and configuration monitoring tools.

Learn about file watching

[Handle outbound traffic](https://e8aee267.previews.developers.cloudflare.com/sandbox/guides/outbound-traffic/)

Block, allow, and intercept outbound HTTP from sandboxes. Keep credentials in your Worker by injecting authorization headers in outbound handlers.

Learn about outbound traffic

---

## Use Cases

Build powerful applications with Sandbox:

### AI Code Execution

Execute code generated by Large Language Models safely and reliably. Native integration with [Workers AI](https://e8aee267.previews.developers.cloudflare.com/workers-ai/) models like GPT-OSS enables function calling with sandbox execution. Perfect for AI agents, code assistants, and autonomous systems that need to run untrusted code.

### Data Analysis & Notebooks

Create interactive data analysis environments with pandas, NumPy, and Matplotlib. Generate charts, tables, and visualizations with automatic rich output formatting.

### Interactive Development Environments

Build cloud IDEs, coding playgrounds, and collaborative development tools with full Linux environments and preview URLs.

### CI/CD & Build Systems

Run tests, compile code, and execute build pipelines in isolated environments with parallel execution and streaming logs.

---

## Related products

[Containers](https://e8aee267.previews.developers.cloudflare.com/containers/)

Serverless container runtime that powers Sandbox, enabling you to run any containerized workload on the edge.

[Workers AI](https://e8aee267.previews.developers.cloudflare.com/workers-ai/)

Run machine learning models and LLMs on the network. Combine with Sandbox for secure AI code execution workflows.

[Durable Objects](https://e8aee267.previews.developers.cloudflare.com/durable-objects/)

Stateful coordination layer that enables Sandbox to maintain persistent environments with strong consistency.

---

## More resources

## Coding agents

Install [Cloudflare Skills ↗](https://github.com/cloudflare/skills) for your agent ([Agent setup](https://e8aee267.previews.developers.cloudflare.com/agent-setup/)). Use **`sandbox-stable`** with the main docs on this site while you are on the current stable package. Use **`sandbox-next`** for `@cloudflare/sandbox@next` (recommended for new projects). When you are ready to port an existing app, use **`sandbox-migrate-to-next`**.

### [Tutorials](https://e8aee267.previews.developers.cloudflare.com/sandbox/tutorials/)

Explore complete examples including AI code execution, data analysis, and interactive environments.

### [Deploy a Sandbox application](https://e8aee267.previews.developers.cloudflare.com/sandbox/guides/deploy/)

Deploy and keep package and image aligned.

### [How-to Guides](https://e8aee267.previews.developers.cloudflare.com/sandbox/guides/)

Learn how to solve specific problems and implement features with the Sandbox SDK.

### [1.0 preview](https://e8aee267.previews.developers.cloudflare.com/sandbox/1-0-preview/)

Install `@cloudflare/sandbox@next` and prepare for the Sandbox SDK 1.0 release.

### [API reference](https://e8aee267.previews.developers.cloudflare.com/sandbox/api/)

Explore the complete API documentation for the Sandbox SDK.

### [Concepts](https://e8aee267.previews.developers.cloudflare.com/sandbox/concepts/)

Learn about the key concepts and architecture of the Sandbox SDK.

### [Configuration](https://e8aee267.previews.developers.cloudflare.com/sandbox/configuration/)

Learn about the configuration options for the Sandbox SDK.

### [GitHub Repository](https://github.com/cloudflare/sandbox-sdk)

View the SDK source code, report issues, and contribute to the project.

### [Pricing](https://e8aee267.previews.developers.cloudflare.com/sandbox/platform/pricing/)

Understand Sandbox pricing based on the underlying Containers platform.

### [Limits](https://e8aee267.previews.developers.cloudflare.com/sandbox/platform/limits/)

Learn about resource limits, quotas, and best practices for working within them.

### [Discord Community](https://discord.cloudflare.com)

Connect with the community on Discord. Ask questions, share what you're building, and get help from other developers.

Was this helpful?

YesNo

## On this page

[![](https://e8aee267.previews.developers.cloudflare.com/_astro/logo.te5VL_aD.svg)Docs](https://e8aee267.previews.developers.cloudflare.com/)

```json
{"@context":"https://schema.org","@type":"WebPage","@id":"https://developers.cloudflare.com/sandbox/#page","headline":"Overview · Cloudflare Sandbox SDK docs","description":"Build secure, isolated code execution environments powered by Cloudflare Workers and Containers.","url":"https://developers.cloudflare.com/sandbox/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","dateModified":"2026-08-24","publisher":{"@type":"Organization","name":"Cloudflare","url":"https://www.cloudflare.com/"},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
```
