This is the abridged developer documentation for ComputeSDK # Blog > Blog by Compute SDK. ## From the blog Stay up to date with ComputeSDK's latest news and updates. Aug 13, 2025 [computesdk](#) ### [Introducing ComputeSDK](/blog/announcement/) A free and open-source toolkit for running other people's code in your applications ![](/Garrison-Snelling-sq.jpeg) [Garrison Snelling](#) Founder, ComputeSDK [X ](https://x.com/computesdk)[GitHub ](https://github.com/computesdk/computesdk) © 2025 ComputeSDK, Inc. All rights reserved. # Astro Use ComputeSDK to execute code in secure sandboxes from your Astro API endpoints. ## Setup [Section titled “Setup”](#setup) ### 1. Install Dependencies [Section titled “1. Install Dependencies”](#1-install-dependencies) ``` npm install computesdk # Provider packages (install what you need) npm install @computesdk/e2b # E2B provider npm install @computesdk/vercel # Vercel provider npm install @computesdk/daytona # Daytona provider ``` ### 2. Configure Environment Variables [Section titled “2. Configure Environment Variables”](#2-configure-environment-variables) Create a `.env` file and add your provider credentials: ``` # E2B (get from e2b.dev) E2B_API_KEY=e2b_your_api_key_here # Vercel # Method 1: OIDC Token (recommended) vercel env pull # Downloads VERCEL_OIDC_TOKEN # Method 2: Traditional VERCEL_TOKEN=your_vercel_token_here VERCEL_TEAM_ID=your_team_id_here VERCEL_PROJECT_ID=your_project_id_here # Daytona (get from your Daytona instance) DAYTONA_API_KEY=your_daytona_api_key_here ``` ### 3. Run Development Server [Section titled “3. Run Development Server”](#3-run-development-server) ``` npm run dev ``` Navigate to ## Implementation [Section titled “Implementation”](#implementation) ### API Route with Request Handler [Section titled “API Route with Request Handler”](#api-route-with-request-handler) The simplest way to use ComputeSDK in Astro is with the built-in request handler: ``` // src/pages/api/compute.ts import type { APIRoute } from 'astro'; import { handleComputeRequest } from 'computesdk'; import { e2b } from '@computesdk/e2b'; export const POST: APIRoute = async ({ request }) => { const computeRequest = await request.json(); const response = await handleComputeRequest({ request: computeRequest, provider: e2b({ apiKey: import.meta.env.E2B_API_KEY! }) }); return new Response( JSON.stringify(response), { status: response.success ? 200 : 500, headers: { 'Content-Type': 'application/json' } } ); }; ``` ### Custom API Route [Section titled “Custom API Route”](#custom-api-route) For more control, create a custom API route: ``` // src/pages/api/sandbox.ts import type { APIRoute } from 'astro'; import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; export const POST: APIRoute = async ({ request }) => { try { const { code, runtime } = await request.json(); // Set provider compute.setConfig({ provider: e2b({ apiKey: import.meta.env.E2B_API_KEY! }) }); // Create sandbox and execute code const sandbox = await compute.sandbox.create({}); const result = await sandbox.runCode(code, runtime); // Clean up await compute.sandbox.destroy(sandbox.sandboxId); return new Response(JSON.stringify({ success: true, stdout: result.stdout, stderr: result.stderr, executionTime: result.executionTime }), { status: 200, headers: { 'Content-Type': 'application/json' } }); } catch (error: any) { return new Response(JSON.stringify({ success: false, error: error.message || 'Unknown error' }), { status: 500, headers: { 'Content-Type': 'application/json' } }); } }; ``` ### Frontend Integration [Section titled “Frontend Integration”](#frontend-integration) Call your API from Astro components: ``` --- // src/pages/playground.astro --- ComputeSDK Playground

Code Executor

``` ### With React Component [Section titled “With React Component”](#with-react-component) ``` // src/components/CodeExecutor.tsx import { useState } from 'react'; export default function CodeExecutor() { const [code, setCode] = useState('print("Hello World!")'); const [output, setOutput] = useState(''); const [loading, setLoading] = useState(false); const [runtime, setRuntime] = useState<'python' | 'node'>('python'); const executeCode = async () => { setLoading(true); try { const response = await fetch('/api/compute', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'compute.sandbox.runCode', code, runtime }) }); const data = await response.json(); if (data.success) { setOutput(data.result.stdout); } else { setOutput(`Error: ${data.error}`); } } catch (error: any) { setOutput(`Error: ${error.message}`); } finally { setLoading(false); } }; return (

Code Executor

``` ## Configuration [Section titled “Configuration”](#configuration) ### Astro Config [Section titled “Astro Config”](#astro-config) ``` // astro.config.mjs import { defineConfig } from 'astro/config'; import react from '@astrojs/react'; export default defineConfig({ integrations: [react()], output: 'server', adapter: /* your adapter */ }); ``` ### TypeScript Config [Section titled “TypeScript Config”](#typescript-config) ``` // tsconfig.json { "extends": "astro/tsconfigs/strict", "compilerOptions": { "types": ["astro/client"] } } ``` ## Deployment [Section titled “Deployment”](#deployment) ### Environment Variables [Section titled “Environment Variables”](#environment-variables) Set your environment variables in your deployment platform: ``` # Production environment variables E2B_API_KEY=your_production_e2b_key VERCEL_TOKEN=your_production_vercel_token VERCEL_TEAM_ID=your_team_id VERCEL_PROJECT_ID=your_project_id DAYTONA_API_KEY=your_production_daytona_key ``` ### Build Configuration [Section titled “Build Configuration”](#build-configuration) Ensure your build includes all necessary dependencies and environment variables are properly configured for your deployment platform. ## Troubleshooting [Section titled “Troubleshooting”](#troubleshooting) **Environment variables not loading?** * Check `.env` file exists and has correct format * Restart dev server after changes * Use `import.meta.env` to access variables in Astro * Ensure variables are not prefixed with `PUBLIC_` if they contain secrets **Sandbox creation fails?** * Verify API keys are correct and have proper format * Check provider-specific setup requirements * Monitor rate limits and quotas **Server-side only errors?** * ComputeSDK must run on server-side only (API endpoints) * Don’t import ComputeSDK in client-side components or scripts * Use API endpoints to bridge between client and ComputeSDK **Build errors?** * Ensure all ComputeSDK imports are in API routes only * Check that environment variables are properly typed * Verify provider packages are correctly installed **Client hydration issues?** * ComputeSDK operations should happen in API endpoints * Use `client:load` or other client directives appropriately for interactive components * Avoid server-side imports in client-side code # Next.js Use ComputeSDK to execute code in secure sandboxes from your Next.js API routes. ## Setup [Section titled “Setup”](#setup) ### 1. Install Dependencies [Section titled “1. Install Dependencies”](#1-install-dependencies) ``` npm install computesdk # Provider packages (install what you need) npm install @computesdk/e2b # E2B provider npm install @computesdk/vercel # Vercel provider npm install @computesdk/daytona # Daytona provider ``` ### 2. Configure Environment Variables [Section titled “2. Configure Environment Variables”](#2-configure-environment-variables) Create a `.env.local` file and add your provider credentials: ``` # E2B (get from e2b.dev) E2B_API_KEY=e2b_your_api_key_here # Vercel # Method 1: OIDC Token (recommended) vercel env pull # Downloads VERCEL_OIDC_TOKEN # Method 2: Traditional VERCEL_TOKEN=your_vercel_token_here VERCEL_TEAM_ID=your_team_id_here VERCEL_PROJECT_ID=your_project_id_here # Daytona (get from your Daytona instance) DAYTONA_API_KEY=your_daytona_api_key_here ``` ### 3. Run Development Server [Section titled “3. Run Development Server”](#3-run-development-server) ``` npm run dev ``` Navigate to ## Implementation [Section titled “Implementation”](#implementation) ### App Router API Route with Request Handler [Section titled “App Router API Route with Request Handler”](#app-router-api-route-with-request-handler) The simplest way to use ComputeSDK in Next.js App Router is with the built-in request handler: ``` // app/api/compute/route.ts import { handleComputeRequest } from 'computesdk'; import { e2b } from '@computesdk/e2b'; export async function POST(request: Request) { return handleComputeRequest({ request, provider: e2b({ apiKey: process.env.E2B_API_KEY! }) }); } ``` ### Pages Router API Route [Section titled “Pages Router API Route”](#pages-router-api-route) For Pages Router, create an API route: ``` // pages/api/compute.ts import type { NextApiRequest, NextApiResponse } from 'next'; import { handleComputeRequest } from 'computesdk'; import { e2b } from '@computesdk/e2b'; export default async function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method !== 'POST') { return res.status(405).json({ error: 'Method not allowed' }); } const response = await handleComputeRequest({ request: req.body, provider: e2b({ apiKey: process.env.E2B_API_KEY! }) }); return res.status(response.success ? 200 : 500).json(response); } ``` ### Custom API Route (App Router) [Section titled “Custom API Route (App Router)”](#custom-api-route-app-router) For more control, create a custom API route: ``` // app/api/sandbox/route.ts import { NextRequest, NextResponse } from 'next/server'; import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; export async function POST(request: NextRequest) { try { const { code, runtime } = await request.json(); // Set provider compute.setConfig({ provider: e2b({ apiKey: process.env.E2B_API_KEY! }) }); // Create sandbox and execute code const sandbox = await compute.sandbox.create({}); const result = await sandbox.runCode(code, runtime); // Clean up await compute.sandbox.destroy(sandbox.sandboxId); return NextResponse.json({ success: true, stdout: result.stdout, stderr: result.stderr, executionTime: result.executionTime }); } catch (error: any) { return NextResponse.json({ success: false, error: error.message || 'Unknown error' }, { status: 500 }); } } ``` ### Frontend Integration (App Router) [Section titled “Frontend Integration (App Router)”](#frontend-integration-app-router) ``` // app/playground/page.tsx 'use client'; import { useState } from 'react'; export default function Playground() { const [code, setCode] = useState('print("Hello World!")'); const [output, setOutput] = useState(''); const [loading, setLoading] = useState(false); const [runtime, setRuntime] = useState<'python' | 'node'>('python'); const executeCode = async () => { setLoading(true); try { const response = await fetch('/api/compute', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'compute.sandbox.runCode', code, runtime }) }); const data = await response.json(); if (data.success) { setOutput(data.result.stdout); } else { setOutput(`Error: ${data.error}`); } } catch (error: any) { setOutput(`Error: ${error.message}`); } finally { setLoading(false); } }; return (

Code Executor

{#if form?.success}
{form.stdout}
{/if} {#if form?.error}
Error: {form.error}
{/if}
``` ## Advanced Examples [Section titled “Advanced Examples”](#advanced-examples) ### Data Analysis API [Section titled “Data Analysis API”](#data-analysis-api) ``` // src/routes/api/analyze/+server.ts import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; import { E2B_API_KEY } from '$env/static/private'; import { json, error } from '@sveltejs/kit'; export async function POST({ request }) { try { const { csvData } = await request.json(); compute.setConfig({ provider: e2b({ apiKey: E2B_API_KEY }) }); const sandbox = await compute.sandbox.create({}); // Save CSV data await sandbox.filesystem.writeFile('/data/input.csv', csvData); // Process data const result = await sandbox.runCode(` import pandas as pd import json # Read and analyze data df = pd.read_csv('/data/input.csv') analysis = { 'rows': len(df), 'columns': len(df.columns), 'summary': df.describe().to_dict(), 'missing_values': df.isnull().sum().to_dict() } print(json.dumps(analysis, indent=2)) `); await compute.sandbox.destroy(sandbox.sandboxId); return json({ success: true, analysis: JSON.parse(result.stdout) }); } catch (err: any) { throw error(500, err.message); } } ``` ### File Upload Processing [Section titled “File Upload Processing”](#file-upload-processing) ``` // src/routes/api/upload/+server.ts import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; import { E2B_API_KEY } from '$env/static/private'; import { json, error } from '@sveltejs/kit'; export async function POST({ request }) { try { const formData = await request.formData(); const file = formData.get('file') as File; if (!file) { throw error(400, 'No file provided'); } const fileContent = await file.text(); const sandbox = await compute.sandbox.create({ provider: e2b({ apiKey: E2B_API_KEY }) }); // Save uploaded file await sandbox.filesystem.writeFile(`/uploads/${file.name}`, fileContent); // Process file const result = await sandbox.runCode(` import os # Get file info file_path = '/uploads/${file.name}' file_size = os.path.getsize(file_path) with open(file_path, 'r') as f: content = f.read() lines = len(content.split('\\n')) chars = len(content) print(f"File: ${file.name}") print(f"Size: {file_size} bytes") print(f"Lines: {lines}") print(f"Characters: {chars}") `); await compute.sandbox.destroy(sandbox.sandboxId); return json({ success: true, info: result.stdout }); } catch (err: any) { throw error(500, err.message); } } ``` ### Multi-Provider Support [Section titled “Multi-Provider Support”](#multi-provider-support) ``` // src/routes/api/multi-provider/+server.ts import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; import { vercel } from '@computesdk/vercel'; import { daytona } from '@computesdk/daytona'; import { E2B_API_KEY, VERCEL_TOKEN, DAYTONA_API_KEY } from '$env/static/private'; import { json, error } from '@sveltejs/kit'; export async function POST({ request }) { try { const { provider: providerName, code, runtime } = await request.json(); let provider; switch (providerName) { case 'e2b': provider = e2b({ apiKey: E2B_API_KEY }); break; case 'vercel': provider = vercel({ token: VERCEL_TOKEN }); break; case 'daytona': provider = daytona({ apiKey: DAYTONA_API_KEY }); break; default: throw error(400, 'Invalid provider specified'); } const sandbox = await compute.sandbox.create({ provider }); try { const result = await sandbox.runCode(code, runtime); return json({ success: true, provider: providerName, result: result.stdout }); } finally { await compute.sandbox.destroy(sandbox.sandboxId); } } catch (err: any) { throw error(500, err.message); } } ``` ### Real-time Updates with Stores [Section titled “Real-time Updates with Stores”](#real-time-updates-with-stores) ``` // src/routes/api/stream/+server.ts import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; import { E2B_API_KEY } from '$env/static/private'; export async function POST({ request }) { const { code } = await request.json(); const stream = new ReadableStream({ async start(controller) { const encoder = new TextEncoder(); try { controller.enqueue(encoder.encode('data: Starting execution...\n\n')); const sandbox = await compute.sandbox.create({ provider: e2b({ apiKey: E2B_API_KEY }) }); controller.enqueue(encoder.encode('data: Sandbox created\n\n')); const result = await sandbox.runCode(code); controller.enqueue(encoder.encode(`data: ${JSON.stringify({ type: 'result', stdout: result.stdout, executionTime: result.executionTime })}\n\n`)); await compute.sandbox.destroy(sandbox.sandboxId); controller.enqueue(encoder.encode('data: Execution completed\n\n')); controller.close(); } catch (error: any) { controller.enqueue(encoder.encode(`data: ${JSON.stringify({ type: 'error', message: error.message })}\n\n`)); controller.close(); } } }); return new Response(stream, { headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' } }); } ``` ### Load Functions with Server-Side Data [Section titled “Load Functions with Server-Side Data”](#load-functions-with-server-side-data) ``` // src/routes/data-demo/+page.server.ts import { compute } from 'computesdk'; import { e2b } from '@computesdk/e2b'; import { E2B_API_KEY } from '$env/static/private'; export async function load() { try { compute.setConfig({ provider: e2b({ apiKey: E2B_API_KEY }) }); const sandbox = await compute.sandbox.create({}); // Generate sample data on the server const result = await sandbox.runCode(` import json import random # Generate sample data data = [] for i in range(10): data.append({ 'id': i + 1, 'name': f'Item {i + 1}', 'value': round(random.uniform(10, 100), 2) }) print(json.dumps(data)) `); await compute.sandbox.destroy(sandbox.sandboxId); return { data: JSON.parse(result.stdout) }; } catch (error) { return { data: [], error: error.message }; } } ``` ```

Server-Side Data Demo

{#if data.error}
Error: {data.error}
{:else}
{#each data.data as item}

{item.name}

ID: {item.id}

Value: ${item.value}

{/each}
{/if}
``` ## Best Practices [Section titled “Best Practices”](#best-practices) ### 1. Environment Variable Management [Section titled “1. Environment Variable Management”](#1-environment-variable-management) ``` // src/lib/server/env.ts import { E2B_API_KEY, VERCEL_TOKEN, VERCEL_TEAM_ID, VERCEL_PROJECT_ID, DAYTONA_API_KEY } from '$env/static/private'; import { e2b } from '@computesdk/e2b'; import { vercel } from '@computesdk/vercel'; import { daytona } from '@computesdk/daytona'; export const getProvider = (providerName?: string) => { const provider = providerName || 'e2b'; switch (provider) { case 'e2b': if (!E2B_API_KEY) throw new Error('E2B API key not configured'); return e2b({ apiKey: E2B_API_KEY }); case 'vercel': if (!VERCEL_TOKEN) throw new Error('Vercel token not configured'); return vercel({ token: VERCEL_TOKEN, teamId: VERCEL_TEAM_ID, projectId: VERCEL_PROJECT_ID }); case 'daytona': if (!DAYTONA_API_KEY) throw new Error('Daytona API key not configured'); return daytona({ apiKey: DAYTONA_API_KEY }); default: throw new Error('Invalid provider specified'); } }; ``` ### 2. Error Handling [Section titled “2. Error Handling”](#2-error-handling) ``` // src/lib/server/error-handler.ts import { error } from '@sveltejs/kit'; import { dev } from '$app/environment'; export const handleComputeError = (err: any) => { console.error('Sandbox error:', err); // Don't expose sensitive error details in production const message = dev ? err.message : 'Internal server error'; throw error(500, message); }; ``` ### 3. Input Validation [Section titled “3. Input Validation”](#3-input-validation) ``` // src/lib/server/validation.ts import { z } from 'zod'; import { error } from '@sveltejs/kit'; export const executeSchema = z.object({ code: z.string().min(1).max(10000), runtime: z.enum(['python', 'node']), timeout: z.number().optional().default(30000) }); export const validateExecuteRequest = (body: any) => { try { return executeSchema.parse(body); } catch (err) { throw error(400, 'Invalid request data'); } }; ``` ### 4. Resource Management [Section titled “4. Resource Management”](#4-resource-management) ``` // src/lib/server/sandbox-manager.ts import { compute } from 'computesdk'; export const withSandbox = async ( provider: any, callback: (sandbox: any) => Promise ): Promise => { const sandbox = await compute.sandbox.create({ provider }); try { return await callback(sandbox); } finally { await compute.sandbox.destroy(sandbox.sandboxId); } }; ``` ### 5. Reusable Components [Section titled “5. Reusable Components”](#5-reusable-components) ```