Skip to main content
Creates an isolated execution context for running code. Each context maintains its own state, variables, and execution history.

Method Signature

async createCodeContext(
  options?: CreateContextOptions
): Promise<CodeContext>

Parameters

options
CreateContextOptions
Configuration options for the context

Returns

CodeContext
object
The created code execution context

Example

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

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

// Create a Python context
const pythonContext = await sandbox.createCodeContext({
  language: 'python',
  cwd: '/workspace/analysis',
  envVars: {
    API_KEY: 'secret-key'
  }
});

console.log(pythonContext.id); // "ctx_abc123..."

// Create a JavaScript context
const jsContext = await sandbox.createCodeContext({
  language: 'javascript'
});

Notes

  • Contexts are isolated from each other - variables and state are not shared
  • Multiple contexts can exist simultaneously
  • Each context has its own execution history
  • Contexts persist until explicitly deleted or the sandbox is destroyed
  • Use the same context for related code executions to maintain state

See Also

Build docs developers (and LLMs) love