Commands
Last updated Sep 30, 2026 Note
This page documents Sandbox SDK 0.x for existing applications. For new applications, refer to Container API. To move an existing application to @cloudflare/sandbox 1.0, refer to Migrate from Sandbox SDK 0.x.
Execute commands and manage background processes in the sandbox's isolated container environment.
Methods
exec()
Execute a command and return the complete result.
const result = await sandbox.exec(command: string, options?: ExecOptions): Promise<ExecuteResponse>
Parameters:
command- The command to execute (can include arguments)options(optional):stream- Enable streaming callbacks (default:false)onOutput- Callback for real-time output:(stream: 'stdout' | 'stderr', data: string) => voidtimeout- Maximum execution time in millisecondsenv- Environment variables for this command:Record<string, string | undefined>cwd- Working directory for this commandstdin- Data to pass to the command's standard input (enables arbitrary input without shell injection risks)
Returns: Promise<ExecuteResponse> with success, stdout, stderr, exitCode
const result = await sandbox.exec("npm run build");
if (result.success) {
console.log("Build output:", result.stdout);
} else {
console.error("Build failed:", result.stderr);
}
// With streaming
await sandbox.exec("npm install", {
stream: true,
onOutput: (stream, data) => console.log(`[${stream}] ${data}`),
});
// With environment variables (undefined values are skipped)
await sandbox.exec("node app.js", {
env: {
NODE_ENV: "production",
PORT: "3000",
DEBUG_MODE: undefined, // Skipped, uses container default or unset
},
});
// Pass input via stdin (no shell injection risks)
const result = await sandbox.exec("cat", {
stdin: "Hello, world!",
});
console.log(result.stdout); // "Hello, world!"
// Process user input safely
const userInput = "user@example.com\nsecret123";
await sandbox.exec("python process_login.py", {
stdin: userInput,
});
const result = await sandbox.exec('npm run build');
if (result.success) {
console.log('Build output:', result.stdout);
} else {
console.error('Build failed:', result.stderr);
}
// With streaming
await sandbox.exec('npm install', {
stream: true,
onOutput: (stream, data) => console.log(`[${stream}] ${data}`)
});
// With environment variables (undefined values are skipped)
await sandbox.exec('node app.js', {
env: {
NODE_ENV: 'production',
PORT: '3000',
DEBUG_MODE: undefined // Skipped, uses container default or unset
}
});
// Pass input via stdin (no shell injection risks)
const result = await sandbox.exec('cat', {
stdin: 'Hello, world!'
});
console.log(result.stdout); // "Hello, world!"
// Process user input safely
const userInput = 'user@example.com\nsecret123';
await sandbox.exec('python process_login.py', {
stdin: userInput
});
Timeout behavior
When a command times out, the SDK raises an error on the caller side and closes the connection. The underlying process continues running inside the container. To stop a timed-out process, delete the session with deleteSession() or destroy the sandbox with destroy().
Timeout precedence: per-command timeout on exec() > session-level commandTimeoutMs on createSession() > global COMMAND_TIMEOUT_MS environment variable. If none are set, commands run without a timeout.
execStream()
Execute a command and return a Server-Sent Events stream for real-time processing.
const stream = await sandbox.execStream(command: string, options?: ExecOptions): Promise<ReadableStream>
Parameters:
command- The command to executeoptions- Same asexec()(includingstdinsupport)
Returns: Promise<ReadableStream> emitting ExecEvent objects (start, stdout, stderr, complete, error)
import { parseSSEStream } from "@cloudflare/sandbox";
const stream = await sandbox.execStream("npm run build");
for await (const event of parseSSEStream(stream)) {
switch (event.type) {
case "stdout":
console.log("Output:", event.data);
break;
case "complete":
console.log("Exit code:", event.exitCode);
break;
case "error":
console.error("Failed:", event.error);
break;
}
}
// Stream with stdin input
const inputStream = await sandbox.execStream(
'python -c "import sys; print(sys.stdin.read())"',
{
stdin: "Data from Workers!",
},
);
for await (const event of parseSSEStream(inputStream)) {
if (event.type === "stdout") {
console.log("Python received:", event.data);
}
}
import { parseSSEStream, type ExecEvent } from '@cloudflare/sandbox';
const stream = await sandbox.execStream('npm run build');
for await (const event of parseSSEStream<ExecEvent>(stream)) {
switch (event.type) {
case 'stdout':
console.log('Output:', event.data);
break;
case 'complete':
console.log('Exit code:', event.exitCode);
break;
case 'error':
console.error('Failed:', event.error);
break;
}
}
// Stream with stdin input
const inputStream = await sandbox.execStream('python -c "import sys; print(sys.stdin.read())"', {
stdin: 'Data from Workers!'
});
for await (const event of parseSSEStream<ExecEvent>(inputStream)) {
if (event.type === 'stdout') {
console.log('Python received:', event.data);
}
}
startProcess()
Start a long-running background process.
const process = await sandbox.startProcess(command: string, options?: ProcessOptions): Promise<Process>
Parameters:
command- The command to start as a background processoptions(optional):cwd- Working directoryenv- Environment variables:Record<string, string | undefined>stdin- Data to pass to the command's standard inputtimeout- Maximum execution time in millisecondsprocessId- Custom process IDencoding- Output encoding (default:'utf8')autoCleanup- Whether to clean up process on sandbox sleep
Returns: Promise<Process> object with:
id- Unique process identifierpid- System process IDcommand- The command being executedstatus- Current status ('running','exited', etc.)kill()- Stop the processgetStatus()- Get current statusgetLogs()- Get accumulated logswaitForPort()- Wait for process to listen on a portwaitForLog()- Wait for pattern in process outputwaitForExit()- Wait for process to terminate and return exit code
const server = await sandbox.startProcess("python -m http.server 8000");
console.log("Started with PID:", server.pid);
// With custom environment
const app = await sandbox.startProcess("node app.js", {
cwd: "/workspace/my-app",
env: { NODE_ENV: "production", PORT: "3000" },
});
// Start process with stdin input (useful for interactive applications)
const interactive = await sandbox.startProcess("python interactive_app.py", {
stdin: "initial_config\nstart_mode\n",
});
const server = await sandbox.startProcess('python -m http.server 8000');
console.log('Started with PID:', server.pid);
// With custom environment
const app = await sandbox.startProcess('node app.js', {
cwd: '/workspace/my-app',
env: { NODE_ENV: 'production', PORT: '3000' }
});
// Start process with stdin input (useful for interactive applications)
const interactive = await sandbox.startProcess('python interactive_app.py', {
stdin: 'initial_config\nstart_mode\n'
});
listProcesses()
List all running processes.
const processes = await sandbox.listProcesses(): Promise<ProcessInfo[]>
const processes = await sandbox.listProcesses();
for (const proc of processes) {
console.log(`${proc.id}: ${proc.command} (PID ${proc.pid})`);
}
const processes = await sandbox.listProcesses();
for (const proc of processes) {
console.log(`${proc.id}: ${proc.command} (PID ${proc.pid})`);
}
killProcess()
Terminate a specific process and all of its child processes.
await sandbox.killProcess(processId: string, signal?: string): Promise<void>
Parameters:
processId- The process ID (fromstartProcess()orlistProcesses())signal- Signal to send (default:"SIGTERM")
Sends the signal to the entire process group, ensuring that both the main process and any child processes it spawned are terminated. This prevents orphaned processes from continuing to run after the parent is killed.
const server = await sandbox.startProcess("python -m http.server 8000");
await sandbox.killProcess(server.id);
// Example with a process that spawns children
const script = await sandbox.startProcess(
'bash -c "sleep 10 & sleep 10 & wait"',
);
// killProcess terminates both sleep commands and the bash process
await sandbox.killProcess(script.id);
const server = await sandbox.startProcess('python -m http.server 8000');
await sandbox.killProcess(server.id);
// Example with a process that spawns children
const script = await sandbox.startProcess('bash -c "sleep 10 & sleep 10 & wait"');
// killProcess terminates both sleep commands and the bash process
await sandbox.killProcess(script.id);
killAllProcesses()
Terminate all running processes.
await sandbox.killAllProcesses(): Promise<void>
await sandbox.killAllProcesses();
await sandbox.killAllProcesses();
streamProcessLogs()
Stream logs from a running process in real-time.
const stream = await sandbox.streamProcessLogs(processId: string): Promise<ReadableStream>
Parameters:
processId- The process ID
Returns: Promise<ReadableStream> emitting LogEvent objects
```js import { parseSSEStream } from "@cloudflare/sandbox";
const server = await sandbox.startProcess("node server.js"); const logStream = await sandbox.streamProcessLogs(server.id);
for await (const log of parseSSEStream(logStream)) {
console.log([${log.timestamp}] ${log.data});
