---
title: Session management
description: Sandbox SDK sessions are shell execution contexts within a single sandbox.
image: https://developers.cloudflare.com/dev-products-preview.png
---

> 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. 

[Skip to content](#%5Ftop) 

# Session management

Sessions are bash shell execution contexts within a sandbox. Think of them as terminal tabs in the same computer.

* **Sandbox** \= A user or task workspace
* **Session** \= A shell in that workspace

Sessions are useful for organizing work inside one sandbox. They are not a security boundary between users because sessions share the same filesystem and process space.

## Default session

By default, every sandbox has a default session that maintains shell state between commands while the container is active:

TypeScript

```
const sandbox = getSandbox(env.Sandbox, 'my-sandbox');
// These commands run in the default sessionawait sandbox.exec("cd /app");await sandbox.exec("pwd");  // Output: /app
await sandbox.exec("export MY_VAR=hello");await sandbox.exec("echo $MY_VAR");  // Output: hello
```

Working directory, environment variables, and exported variables carry over between commands. This state resets if the container restarts due to inactivity.

If you set `enableDefaultSession: false` when calling `getSandbox()`, operations without an explicit `sessionId` run in isolation instead of using the default session:

TypeScript

```
const sandbox = getSandbox(env.Sandbox, 'my-sandbox', {  enableDefaultSession: false});
await sandbox.exec("cd /app");await sandbox.exec("pwd");  // Output: /workspace (cd was not inherited)
```

Without the default session, the second command does not inherit shell state from the first command. It is recommended that you always apply this setting as it will become the default in a future Sandbox SDK release. Create or retrieve an explicit session when you want commands to share shell state.

### Automatic session creation

The container automatically creates sessions on first use. If you reference a non-existent session ID, the container creates it with default settings:

TypeScript

```
// This session does not exist yetconst result = await sandbox.exec('echo hello', { sessionId: 'new-session' });// Container automatically creates 'new-session' with defaults:// - cwd: '/workspace'// - env: {} (empty)
```

This behavior is particularly relevant after deleting a session:

TypeScript

```
// Create and configure a sessionconst session = await sandbox.createSession({  id: 'temp',  env: { MY_VAR: 'value' }});
// Delete the sessionawait sandbox.deleteSession('temp');
// Using the same session ID again works - auto-created with defaultsconst result = await sandbox.exec('echo $MY_VAR', { sessionId: 'temp' });// Output: (empty) - MY_VAR is not set in the freshly created session
```

This auto-creation means commands still run when they reference a non-existent session. However, custom configuration (environment variables, working directory) is lost after deletion.

## Creating sessions

Create additional sessions for separate workflows in the same sandbox:

TypeScript

```
const buildSession = await sandbox.createSession({  id: "build",  env: { NODE_ENV: "production" },  cwd: "/build"});
const testSession = await sandbox.createSession({  id: "test",  env: { NODE_ENV: "test" },  cwd: "/test"});
// Different shell contextsawait buildSession.exec("npm run build");await testSession.exec("npm test");
```

You can also set a default command timeout for all commands in a session:

TypeScript

```
const session = await sandbox.createSession({  id: "ci",  commandTimeoutMs: 30000 // 30s timeout for all commands});
await session.exec("npm test"); // Times out after 30s if still running
```

Individual commands can override the session timeout with the `timeout` option on `exec()`. For more details, refer to the [Sessions API](https://developers.cloudflare.com/sandbox/api/sessions/) and the [execute commands guide](https://developers.cloudflare.com/sandbox/guides/execute-commands/#timeouts).

## What is scoped to a session

Each session has its own:

**Shell environment**:

TypeScript

```
await session1.exec("export MY_VAR=hello");await session2.exec("echo $MY_VAR");  // Empty - different shell
```

**Working directory**:

TypeScript

```
await session1.exec("cd /workspace/project1");await session2.exec("pwd");  // Different working directory
```

**Environment variables** (set via `createSession` options):

TypeScript

```
const session1 = await sandbox.createSession({  env: { API_KEY: 'key-1' }});const session2 = await sandbox.createSession({  env: { API_KEY: 'key-2' }});
```

## What is shared across sessions

All sessions in a sandbox share:

**Filesystem**:

TypeScript

```
await session1.writeFile('/workspace/file.txt', 'data');await session2.readFile('/workspace/file.txt');  // Can read it
```

**Processes**:

TypeScript

```
await session1.startProcess('node server.js');await session2.listProcesses();  // Sees the server
```

## When to use sessions

**Use sessions when**:

* You need separate shell state for one user's tasks
* Running parallel operations with different environments
* Keeping AI agent credentials separate from app runtime

**Example - separate dev and runtime environments**:

TypeScript

```
// Phase 1: AI agent writes code (with API keys)const devSession = await sandbox.createSession({  id: "dev",  env: { ANTHROPIC_API_KEY: env.ANTHROPIC_API_KEY }});await devSession.exec('ai-tool "build a web server"');
// Phase 2: Run the code (without API keys)const appSession = await sandbox.createSession({  id: "app",  env: { PORT: "3000" }});await appSession.exec("node server.js");
```

**Use separate sandboxes when**:

* You need complete isolation for untrusted code
* Different users need separate workspaces
* User data must stay separated
* Independent resource allocation is needed

## Best practices

### Session cleanup

**Clean up temporary sessions** to free resources while keeping the sandbox running:

TypeScript

```
try {  const session = await sandbox.createSession({ id: 'temp' });  await session.exec('command');} finally {  await sandbox.deleteSession('temp');}
```

**Default session cannot be deleted**:

TypeScript

```
// This throws an errorawait sandbox.deleteSession('default');// Error: Cannot delete default session. Use sandbox.destroy() instead.
```

### Filesystem scope

**Sessions share the sandbox filesystem** \- file operations affect all sessions:

TypeScript

```
// Bad - affects all sessionsawait session.exec('rm -rf /workspace/*');
// For user data or untrusted code, use a separate sandboxconst userSandbox = getSandbox(env.Sandbox, `user-${userId}`);
```

## Related resources

* [Sandbox lifecycle](https://developers.cloudflare.com/sandbox/concepts/sandboxes/) \- Understanding sandbox management
* [Sessions API](https://developers.cloudflare.com/sandbox/api/sessions/) \- Complete session API reference

```json
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/sandbox/concepts/sessions/#page","headline":"Session management · Cloudflare Sandbox SDK docs","description":"Sandbox SDK sessions are shell execution contexts within a single sandbox.","url":"https://developers.cloudflare.com/sandbox/concepts/sessions/","inLanguage":"en","image":"https://developers.cloudflare.com/dev-products-preview.png","dateModified":"2026-05-27","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/"}}
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/sandbox/","name":"Sandbox SDK"}},{"@type":"ListItem","position":3,"item":{"@id":"/sandbox/concepts/","name":"Concepts"}},{"@type":"ListItem","position":4,"item":{"@id":"/sandbox/concepts/sessions/","name":"Session management"}}]}
```
