Documentation Index
Fetch the complete documentation index at: https://mintlify.com/cloudflare/sandbox-sdk/llms.txt
Use this file to discover all available pages before exploring further.
Creates a new execution session, providing an isolated environment with its own working directory, environment variables, and shell state.
Method Signature
async createSession(
options?: SessionOptions
): Promise<ExecutionSession>
Parameters
Session configuration options
Optional session ID. Auto-generated if not provided.
Session name for identification
env
Record<string, string | undefined>
Environment variables for this session. Undefined values are skipped.
Working directory for the session
Enable PID namespace isolation (requires CAP_SYS_ADMIN)
Returns
The created execution session with all sandbox methods bound to this session
Unique session identifier
Execute commands in this session
Start background processes in this session
File operations in this session’s context
All other sandbox methods, scoped to this session
Example
import { getSandbox } from '@cloudflare/sandbox';
const sandbox = getSandbox(env.SANDBOX, 'my-sandbox');
// Create a session with custom environment
const session = await sandbox.createSession({
name: 'data-analysis',
env: {
API_KEY: 'secret-key',
DEBUG: 'true'
},
cwd: '/workspace/analysis'
});
// Use the session - all operations use session context
const result = await session.exec('echo $API_KEY');
console.log(result.stdout); // "secret-key"
const files = await session.listFiles('.');
console.log(files); // Lists /workspace/analysis
Example: Multiple Isolated Sessions
// Create sessions for different users
const user1Session = await sandbox.createSession({
id: 'user-1',
env: { USER_ID: '1' },
cwd: '/workspace/user1'
});
const user2Session = await sandbox.createSession({
id: 'user-2',
env: { USER_ID: '2' },
cwd: '/workspace/user2'
});
// Each session has isolated state
await user1Session.exec('export TOKEN=abc123');
await user2Session.exec('export TOKEN=xyz789');
const result1 = await user1Session.exec('echo $TOKEN');
console.log(result1.stdout); // "abc123"
const result2 = await user2Session.exec('echo $TOKEN');
console.log(result2.stdout); // "xyz789"
Example: Session with Cleanup
const session = await sandbox.createSession({
name: 'temp-work',
cwd: '/tmp/session'
});
try {
// Do work in session
await session.exec('npm install');
await session.exec('npm test');
} finally {
// Cleanup
await sandbox.deleteSession(session.id);
}
Notes
- Sessions maintain independent shell state (environment variables, working directory)
- Environment variables set in one session don’t affect others
- Each session has its own command history
- Sessions persist until explicitly deleted or the sandbox is destroyed
- The sandbox automatically creates a default session for non-session methods
- Use sessions for multi-tenant scenarios or parallel workflows
- Session operations are isolated but share the same filesystem
See Also