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.
Environment bindings containing configuration values: Show Environment configuration
Logging level: debug, info, warn, or error. Default: info.
Log format: json or pretty. Default: json.
Transport mode: http or websocket. Default: http.
R2 bucket binding for backup storage.
R2 access key for presigned URLs (backup operations).
R2 secret key for presigned URLs (backup operations).
Cloudflare account ID for R2 operations.
Name of R2 bucket for backups.
SANDBOX_INSTANCE_TIMEOUT_MS
Container instance provisioning timeout in milliseconds (5000-300000). Default: 30000.
Application startup timeout in milliseconds (10000-600000). Default: 90000.
Container readiness polling interval in milliseconds (100-5000). Default: 1000.
Properties
Default port for the container’s control plane. Always 3000.
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.
HTTP client for communicating with the container runtime.
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 );
Shell command to execute.
Execution options: Show ExecOptions properties
Maximum execution time in milliseconds.
env
Record<string, string | undefined>
Environment variables for this command. Temporarily overrides session-level variables.
Working directory for command execution.
Text encoding for output. Default: 'utf8'.
Enable real-time output streaming via callbacks.
onOutput
(stream: 'stdout' | 'stderr', data: string) => void
Callback for real-time output data.
onComplete
(result: ExecResult) => void
Callback when command completes (only with stream: true).
Callback for execution errors.
AbortSignal for cancelling execution.
Execution result: Show ExecResult properties
Whether the command succeeded (exitCode === 0).
Command that was executed.
Execution duration in milliseconds.
ISO timestamp when command started.
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 );
}
}
Shell command to execute.
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 );
Shell command to execute.
Process options: Show ProcessOptions properties
Custom process ID for later reference. Auto-generated if not provided.
Automatically cleanup process record after exit. Default: true.
onExit
(code: number | null) => void
Callback when process exits.
onOutput
(stream: 'stdout' | 'stderr', data: string) => void
Callback for real-time output.
onStart
(process: Process) => void
Callback when process starts successfully.
Callback for process errors.
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 } ` );
}
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 );
}
Process handle, or null if not found.
killProcess()
Terminate a running process.
await sandbox . killProcess ( 'my-process-id' , 'SIGTERM' );
Signal to send. Default: 'SIGTERM'.
killAllProcesses()
Terminate all running processes.
const count = await sandbox . killAllProcesses ();
console . log ( `Killed ${ count } processes` );
Number of processes terminated.
cleanupCompletedProcesses()
Remove completed process records from tracking.
const count = await sandbox . cleanupCompletedProcesses ();
console . log ( `Cleaned up ${ count } processes` );
Number of processes cleaned up.
getProcessLogs()
Get accumulated logs for a process.
const logs = await sandbox . getProcessLogs ( 'my-process-id' );
console . log ( logs . stdout );
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 );
}
}
Streaming options: AbortSignal for cancelling the stream.
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' })
);
Write options: Text encoding. Default: 'utf8'.
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 );
Read options: Text encoding. Default: 'utf8'.
Read operation result: Show ReadFileResult properties
Whether the read succeeded.
Encoding used for content.
Whether the file is detected as binary.
MIME type (e.g., 'image/png', 'text/plain').
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 } ` );
stream
ReadableStream<Uint8Array>
SSE stream of file chunks. Use streamFile() helper to consume.
mkdir()
Create a directory.
await sandbox . mkdir ( '/workspace/data' , { recursive: true });
Directory options: Create parent directories if needed. Default: false.
Create operation result with success, path, recursive, and timestamp fields.
deleteFile()
Delete a file or directory.
await sandbox . deleteFile ( '/workspace/temp.txt' );
Absolute file or directory path.
Delete operation result with success, path, and timestamp fields.
renameFile()
Rename a file or directory.
await sandbox . renameFile ( '/workspace/old.txt' , '/workspace/new.txt' );
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' );
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)` );
}
Listing options: Show ListFilesOptions properties
List files recursively. Default: false.
Include hidden files (starting with .). Default: false.
List operation result: Show ListFilesResult properties
Whether the list succeeded.
Array of file information objects.
exists()
Check if a file or directory exists.
const result = await sandbox . exists ( '/workspace/config.json' );
if ( result . exists ) {
console . log ( 'File exists' );
}
Absolute file or directory path.
Existence check result: Show FileExistsResult properties
Whether the check succeeded.
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
});
Clone options: Branch to checkout. Default: repository default branch.
Target directory path. Default: /workspace/{repo-name}.
Clone depth for shallow clones (e.g., 1 for latest commit only).
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' );
Session options: Show SessionOptions properties
Session ID. Auto-generated if not provided.
Session name for identification.
env
Record<string, string | undefined>
Environment variables for this session.
Working directory. Default: /workspace.
Enable PID namespace isolation (requires CAP_SYS_ADMIN). Default: false.
Session handle with the same API as Sandbox, bound to this session.
deleteSession()
Delete an execution session.
await sandbox . deleteSession ( 'build-session' );
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 );
Execution options: Show RunCodeOptions properties
Programming language. Default: 'python'.
Existing context ID to reuse. Creates new context if not provided.
Maximum execution time in milliseconds.
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
Context options: Show CreateContextOptions properties
Programming language. Default: 'python'.
Working directory. Default: /workspace.
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 } ` );
}
Array of context handles.
deleteCodeContext()
Delete a code execution context.
await sandbox . deleteCodeContext ( 'ctx-id' );
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
});
Absolute path in container to mount at.
options
MountBucketOptions
required
Mount configuration: Show MountBucketOptions properties
S3-compatible endpoint URL (e.g., 'https://abc123.r2.cloudflarestorage.com').
Provider hint for automatic s3fs flag configuration.
Explicit credentials (overrides environment variable auto-detection).
Mount filesystem as read-only. Default: false.
Advanced s3fs options to override or extend defaults.
Optional prefix/subdirectory within the bucket to mount. Must start with /.
unmountBucket()
Unmount a bucket filesystem.
await sandbox . unmountBucket ( '/workspace/data' );
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 );
Backup configuration: Show BackupOptions properties
Directory to back up (absolute path).
Human-readable name for this backup.
Seconds until automatic garbage collection. Default: 259200 (3 days).
Backup handle: Show DirectoryBackup properties
Unique backup identifier.
Directory that was backed up.
restoreBackup()
Restore a directory from a backup.
const result = await sandbox . restoreBackup ( backup );
if ( result . success ) {
console . log ( `Restored ${ result . dir } ` );
}
Backup handle from createBackup().
Restore operation result: Show RestoreBackupResult properties
Whether the restore succeeded.
Directory that was restored.
Backup ID that was restored.
Lifecycle management
destroy()
Cleanup and destroy the sandbox container.
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 ;
WebSocket upgrade request.
Port number to connect to (1024-65535, excluding 3000).
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
});
Timeout configuration: Container instance provisioning timeout (5000-300000ms).
Application startup timeout (10000-600000ms).
Container readiness polling interval (100-5000ms).
Timeout configuration can also be set via SandboxOptions in getSandbox() or environment variables.