Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Cloudflare platform skill covering Workers, D1, R2, KV, AI, Durable Objects, and security.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/sandbox/patterns.md
1# Common Patterns23## AI Code Execution with Code Context45```typescript6export default {7async fetch(request: Request, env: Env): Promise<Response> {8const { code, variables } = await request.json();9const sandbox = getSandbox(env.Sandbox, 'ai-agent');1011// Create context with persistent variables12const ctx = await sandbox.createCodeContext({13language: 'python',14variables: variables || {}15});1617// Execute with rich outputs (text, images, HTML)18const result = await sandbox.runCode(code, { context: ctx });1920return Response.json({21results: result.results, // RichOutput[] (text, html, png, json, etc.)22error: result.error,23success: !result.error24});25}26};27```2829## Interactive Dev Environment3031```typescript32export default {33async fetch(request: Request, env: Env): Promise<Response> {34const proxyResponse = await proxyToSandbox(request, env);35if (proxyResponse) return proxyResponse;3637const sandbox = getSandbox(env.Sandbox, 'ide', { normalizeId: true });3839if (request.url.endsWith('/start')) {40await sandbox.exec('curl -fsSL https://code-server.dev/install.sh | sh');41await sandbox.startProcess('code-server --bind-addr 0.0.0.0:8080', {42processId: 'vscode'43});4445const exposed = await sandbox.exposePort(8080);46return Response.json({ url: exposed.url });47}4849return new Response('Try /start');50}51};52```5354## WebSocket Real-Time Service5556```typescript57export default {58async fetch(request: Request, env: Env): Promise<Response> {59const proxyResponse = await proxyToSandbox(request, env);60if (proxyResponse) return proxyResponse;6162if (request.headers.get('Upgrade')?.toLowerCase() === 'websocket') {63const sandbox = getSandbox(env.Sandbox, 'realtime-service');64return await sandbox.wsConnect(request, 8080);65}6667// Non-WebSocket: expose preview URL68const sandbox = getSandbox(env.Sandbox, 'realtime-service');69const { url } = await sandbox.exposePort(8080, {70hostname: new URL(request.url).hostname71});72return Response.json({ wsUrl: url.replace('https', 'wss') });73}74};75```7677**Dockerfile**:78```dockerfile79FROM docker.io/cloudflare/sandbox:0.7.080RUN npm install -g ws81EXPOSE 808082```8384## Process Readiness Pattern8586```typescript87export default {88async fetch(request: Request, env: Env): Promise<Response> {89const sandbox = getSandbox(env.Sandbox, 'app-server');9091// Start server92const process = await sandbox.startProcess(93'node server.js',94{ processId: 'server' }95);9697// Wait for server to be ready98await process.waitForPort(8080); // Wait for port listening99100// Now safe to expose101const { url } = await sandbox.exposePort(8080);102return Response.json({ url });103}104};105```106107## Persistent Data with Bucket Mounting108109```typescript110export default {111async fetch(request: Request, env: Env): Promise<Response> {112const sandbox = getSandbox(env.Sandbox, 'data-processor');113114// Mount R2 bucket (production only)115await sandbox.mountBucket(env.DATA_BUCKET, '/data', {116readOnly: false117});118119// Process files in bucket120const result = await sandbox.exec('python3 /workspace/process.py', {121env: { DATA_DIR: '/data/input' }122});123124// Results written to /data/output are persisted in R2125return Response.json({ success: result.success });126}127};128```129130## CI/CD Pipeline131132```typescript133export default {134async fetch(request: Request, env: Env): Promise<Response> {135const { repo, branch } = await request.json();136const sandbox = getSandbox(env.Sandbox, `ci-${repo}-${Date.now()}`);137138await sandbox.exec(`git clone -b ${branch} ${repo} /workspace/repo`);139140const install = await sandbox.exec('npm install', {141cwd: '/workspace/repo',142stream: true,143onOutput: (stream, data) => console.log(data)144});145146if (!install.success) {147return Response.json({ success: false, error: 'Install failed' });148}149150const test = await sandbox.exec('npm test', { cwd: '/workspace/repo' });151152return Response.json({153success: test.success,154output: test.stdout,155exitCode: test.exitCode156});157}158};159```160161162163164165## Multi-Tenant Pattern166167```typescript168export default {169async fetch(request: Request, env: Env): Promise<Response> {170const userId = request.headers.get('X-User-ID');171const sandbox = getSandbox(env.Sandbox, 'multi-tenant');172173// Each user gets isolated session174let session;175try {176session = await sandbox.getSession(userId);177} catch {178session = await sandbox.createSession({179id: userId,180cwd: `/workspace/users/${userId}`,181env: { USER_ID: userId }182});183}184185const code = await request.text();186const result = await session.exec(`python3 -c "${code}"`);187188return Response.json({ output: result.stdout });189}190};191```192193## Git Operations194195```typescript196// Clone repo197await sandbox.exec('git clone https://github.com/user/repo.git /workspace/repo');198199// Authenticated (use env secrets)200await sandbox.exec(`git clone https://${env.GITHUB_TOKEN}@github.com/user/repo.git`);201```202