Skip to main content
The Sandbox class extends the Cloudflare Container class and provides a complete API for executing commands, managing files, running background processes, and exposing network services within isolated sandbox environments.

Overview

The Sandbox is a Durable Object that manages the lifecycle of a container instance. It provides:
  • Command execution with streaming output
  • Background process management
  • File system operations
  • Git repository cloning
  • Port exposure with preview URLs
  • Session management for isolated execution contexts
  • Code interpreter for Python/JavaScript
  • S3-compatible bucket mounting
  • Directory backup and restore

Getting a sandbox instance

Use getSandbox() to get a type-safe sandbox instance:
import { getSandbox, Sandbox } from '@cloudflare/sandbox';

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const sandbox = getSandbox(env.Sandbox, 'my-sandbox-id');
    
    // Execute a command
    const result = await sandbox.exec('ls -la');
    
    return new Response(result.stdout);
  }
};

Constructor

The Sandbox constructor is typically not called directly. Use getSandbox() instead.
ctx
DurableObjectState
required
Durable Object state provided by Cloudflare Workers runtime.
env
object
required
Environment bindings containing configuration values:

Properties

defaultPort
number
Default port for the container’s control plane. Always 3000.
sleepAfter
string | number
Duration after which the sandbox sleeps if no requests are received. Default: "10m". Can be a string like "30s", "5m", "1h" or a number representing seconds.
client
SandboxClient
HTTP client for communicating with the container runtime.
envVars
Record<string, string>
Environment variables set at the sandbox level.

Command execution

exec()

Execute a shell command in the default session.
const result = await sandbox.exec('npm install', {
  cwd: '/workspace',
  timeout: 30000
});

console.log(result.stdout);
command
string
required
Shell command to execute.
options
ExecOptions
Execution options:
result
ExecResult
Execution result:

execStream()

Execute a command with streaming output (Server-Sent Events).
const stream = await sandbox.execStream('npm run build');

for await (const event of parseSSEStream(stream)) {
  if (event.type === 'stdout') {
    console.log(event.data);
  }
}
command
string
required
Shell command to execute.
options
StreamOptions
Streaming options (extends BaseExecOptions with signal and bufferSize).
stream
ReadableStream<Uint8Array>
SSE stream of execution events. Use parseSSEStream() to consume.

Background processes

startProcess()

Start a long-running background process.
const proc = await sandbox.startProcess('npm run dev', {
  onOutput: (stream, data) => console.log(`[${stream}]`, data)
});

// Wait for server to be ready
await proc.waitForPort(3000);
command
string
required
Shell command to execute.
options
ProcessOptions
Process options:
process
Process
Process handle with methods for monitoring and control.

listProcesses()

List all tracked processes in the sandbox.
const processes = await sandbox.listProcesses();
for (const proc of processes) {
  console.log(`${proc.id}: ${proc.status}`);
}
processes
Process[]
Array of process handles.

getProcess()

Get a specific process by ID.
const proc = await sandbox.getProcess('my-process-id');
if (proc) {
  console.log(proc.status);
}
id
string
required
Process ID.
process
Process | null
Process handle, or null if not found.

killProcess()

Terminate a running process.
await sandbox.killProcess('my-process-id', 'SIGTERM');
id
string
required
Process ID.
signal
string
Signal to send. Default: 'SIGTERM'.

killAllProcesses()

Terminate all running processes.
const count = await sandbox.killAllProcesses();
console.log(`Killed ${count} processes`);
count
number
Number of processes terminated.

cleanupCompletedProcesses()

Remove completed process records from tracking.
const count = await sandbox.cleanupCompletedProcesses();
console.log(`Cleaned up ${count} processes`);
count
number
Number of processes cleaned up.

getProcessLogs()

Get accumulated logs for a process.
const logs = await sandbox.getProcessLogs('my-process-id');
console.log(logs.stdout);
id
string
required
Process ID.
logs
object
Process logs:

streamProcessLogs()

Stream logs from a running process (Server-Sent Events).
const stream = await sandbox.streamProcessLogs('my-process-id');

for await (const event of parseSSEStream(stream)) {
  if (event.type === 'stdout') {
    console.log(event.data);
  }
}
processId
string
required
Process ID.
options
object
Streaming options:
stream
ReadableStream<Uint8Array>
SSE stream of log events.

File operations

writeFile()

Write content to a file.
await sandbox.writeFile('/workspace/config.json', 
  JSON.stringify({ setting: 'value' })
);
path
string
required
Absolute file path.
content
string
required
File content to write.
options
object
Write options:
result
WriteFileResult
Write operation result with success, path, and timestamp fields.

readFile()

Read content from a file.
const result = await sandbox.readFile('/workspace/config.json');
console.log(result.content);
path
string
required
Absolute file path.
options
object
Read options:
result
ReadFileResult
Read operation result:

readFileStream()

Stream file content for large files (Server-Sent Events).
import { streamFile } from '@cloudflare/sandbox';

const stream = await sandbox.readFileStream('/workspace/large-file.bin');
const { metadata, data } = await streamFile(stream);

console.log(`Size: ${metadata.size}, Type: ${metadata.mimeType}`);
path
string
required
Absolute file path.
stream
ReadableStream<Uint8Array>
SSE stream of file chunks. Use streamFile() helper to consume.

mkdir()

Create a directory.
await sandbox.mkdir('/workspace/data', { recursive: true });
path
string
required
Absolute directory path.
options
object
Directory options:
result
MkdirResult
Create operation result with success, path, recursive, and timestamp fields.

deleteFile()

Delete a file or directory.
await sandbox.deleteFile('/workspace/temp.txt');
path
string
required
Absolute file or directory path.
result
DeleteFileResult
Delete operation result with success, path, and timestamp fields.

renameFile()

Rename a file or directory.
await sandbox.renameFile('/workspace/old.txt', '/workspace/new.txt');
oldPath
string
required
Current file path.
newPath
string
required
New file path.
result
RenameFileResult
Rename operation result with success, path, newPath, and timestamp fields.

moveFile()

Move a file or directory to a different location.
await sandbox.moveFile('/workspace/file.txt', '/workspace/subdir/file.txt');
sourcePath
string
required
Source file path.
destinationPath
string
required
Destination file path.
result
MoveFileResult
Move operation result with success, path, newPath, and timestamp fields.

listFiles()

List files in a directory.
const result = await sandbox.listFiles('/workspace', { 
  recursive: true,
  includeHidden: false 
});

for (const file of result.files) {
  console.log(`${file.name} (${file.size} bytes)`);
}
path
string
required
Absolute directory path.
options
ListFilesOptions
Listing options:
result
ListFilesResult
List operation result:

exists()

Check if a file or directory exists.
const result = await sandbox.exists('/workspace/config.json');
if (result.exists) {
  console.log('File exists');
}
path
string
required
Absolute file or directory path.
result
FileExistsResult
Existence check result:

Git operations

gitCheckout()

Clone a Git repository into the sandbox.
await sandbox.gitCheckout('https://github.com/user/repo', {
  branch: 'main',
  targetDir: '/workspace/repo',
  depth: 1  // Shallow clone
});
repoUrl
string
required
Git repository URL.
options
object
Clone options:
result
GitCheckoutResult
Checkout operation result with success, repoUrl, branch, targetDir, and timestamp fields.

Environment management

setEnvVars()

Set or unset environment variables in the default session.
await sandbox.setEnvVars({
  API_KEY: 'secret-key',
  DEBUG: 'true',
  OLD_VAR: undefined  // Unset this variable
});
envVars
Record<string, string | undefined>
required
Environment variables to set or unset. Undefined values unset the variable.

Session management

createSession()

Create a new isolated execution session.
const session = await sandbox.createSession({
  id: 'build-session',
  env: { NODE_ENV: 'production' },
  cwd: '/workspace/app'
});

// Use session methods
await session.exec('npm run build');
options
SessionOptions
Session options:
session
ExecutionSession
Session handle with the same API as Sandbox, bound to this session.

deleteSession()

Delete an execution session.
await sandbox.deleteSession('build-session');
sessionId
string
required
Session ID to delete.
result
SessionDeleteResult
Delete operation result with success, sessionId, and timestamp fields.

Code interpreter

runCode()

Execute Python or JavaScript code with structured output.
const result = await sandbox.runCode(`
import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3]})
df.describe()
`, { language: 'python' });

console.log(result.results);
code
string
required
Code to execute.
options
RunCodeOptions
Execution options:
result
ExecutionResult
Execution result with structured output, including text, charts, and errors.

createCodeContext()

Create a reusable code execution context.
const ctx = await sandbox.createCodeContext({ 
  language: 'python',
  cwd: '/workspace' 
});

await sandbox.runCode('x = 42', { contextId: ctx.id });
await sandbox.runCode('print(x)', { contextId: ctx.id });  // Uses same context
options
CreateContextOptions
Context options:
context
CodeContext
Context handle with id and language properties.

listCodeContexts()

List all code execution contexts.
const contexts = await sandbox.listCodeContexts();
for (const ctx of contexts) {
  console.log(`${ctx.id}: ${ctx.language}`);
}
contexts
CodeContext[]
Array of context handles.

deleteCodeContext()

Delete a code execution context.
await sandbox.deleteCodeContext('ctx-id');
contextId
string
required
Context ID to delete.

Bucket mounting

mountBucket()

Mount an S3-compatible bucket as a local directory using S3FS-FUSE.
await sandbox.mountBucket('my-bucket', '/workspace/data', {
  endpoint: 'https://abc123.r2.cloudflarestorage.com',
  provider: 'r2',
  credentials: {
    accessKeyId: env.R2_ACCESS_KEY_ID,
    secretAccessKey: env.R2_SECRET_ACCESS_KEY
  },
  prefix: '/user-data/',
  readOnly: true
});
bucket
string
required
Bucket name.
mountPath
string
required
Absolute path in container to mount at.
options
MountBucketOptions
required
Mount configuration:

unmountBucket()

Unmount a bucket filesystem.
await sandbox.unmountBucket('/workspace/data');
mountPath
string
required
Absolute path where the bucket is mounted.

Backup operations

createBackup()

Create a backup of a directory to R2 storage.
const backup = await sandbox.createBackup({
  dir: '/workspace',
  name: 'project-backup',
  ttl: 604800  // 7 days
});

// Store backup handle for later restore
console.log(backup.id);
options
BackupOptions
required
Backup configuration:
backup
DirectoryBackup
Backup handle:

restoreBackup()

Restore a directory from a backup.
const result = await sandbox.restoreBackup(backup);
if (result.success) {
  console.log(`Restored ${result.dir}`);
}
backup
DirectoryBackup
required
Backup handle from createBackup().
result
RestoreBackupResult
Restore operation result:

Lifecycle management

destroy()

Cleanup and destroy the sandbox container.
await sandbox.destroy();
This method:
  • Disconnects WebSocket transport if active
  • Unmounts all mounted buckets
  • Stops the container
  • Cleans up resources
Always call destroy() when using keepAlive: true to prevent resource leaks.

WebSocket connection

wsConnect()

Create a WebSocket connection to a specific port.
const response = await sandbox.wsConnect(request, 8080);
return response;
request
Request
required
WebSocket upgrade request.
port
number
required
Port number to connect to (1024-65535, excluding 3000).
response
Response
WebSocket upgrade response.
This method must be called on the stub returned by getSandbox(), not directly on the Sandbox instance.

Configuration methods

setContainerTimeouts()

Configure container startup timeout values.
await sandbox.setContainerTimeouts({
  instanceGetTimeoutMS: 15000,
  portReadyTimeoutMS: 30000,
  waitIntervalMS: 500
});
timeouts
object
required
Timeout configuration:
Timeout configuration can also be set via SandboxOptions in getSandbox() or environment variables.

Build docs developers (and LLMs) love