Skip to main content
Retrieves a list of all code execution contexts currently active in the sandbox.

Method Signature

async listCodeContexts(): Promise<CodeContext[]>

Parameters

This method takes no parameters.

Returns

CodeContext[]
array
Array of code execution contexts

Example

import { getSandbox } from '@cloudflare/sandbox';

const sandbox = getSandbox(env.SANDBOX, 'my-sandbox');

// Create some contexts
await sandbox.createCodeContext({ language: 'python' });
await sandbox.createCodeContext({ language: 'javascript' });

// List all contexts
const contexts = await sandbox.listCodeContexts();

for (const context of contexts) {
  console.log(`Context ${context.id}:`);
  console.log(`  Language: ${context.language}`);
  console.log(`  Working directory: ${context.cwd}`);
  console.log(`  Created: ${context.createdAt.toISOString()}`);
  console.log(`  Last used: ${context.lastUsed.toISOString()}`);
}

Example: Cleanup Old Contexts

const contexts = await sandbox.listCodeContexts();
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);

// Delete contexts not used in the last hour
for (const context of contexts) {
  if (context.lastUsed < oneHourAgo) {
    await sandbox.deleteCodeContext(context.id);
    console.log(`Deleted unused context ${context.id}`);
  }
}

Notes

  • Returns all contexts regardless of language
  • Contexts are ordered by creation time (oldest first)
  • Each context maintains independent state
  • Use this to audit resource usage or implement cleanup policies

See Also

Build docs developers (and LLMs) love