Sandbox SDK Sandbox SDK Sandbox SDK · Lab 3/7 Lab 3/7 Lab 3/7 · 25 phút · 25 min · 25 នាទី

03

Xây code executor Building a Code Executor សង់ code executor

Viết code interpreter chạy JavaScript an toàn với runCode() và createCodeContext(). Create a code interpreter that safely executes JavaScript code. Use the runCode() and createCodeContext() APIs for language-aware execution with structured output. សរសេរ code interpreter រត់ JavaScript ឲ្យសុវត្ថិភាពដោយ runCode() និង createCodeContext()។

Nội dung bước (lệnh, code) giữ nguyên tiếng Anh từ nguồn chính thức. Step body (commands, code) stays in English from the official source. ខ្លឹមសារជំហាន (ពាក្យបញ្ជា និង code) រក្សាភាសាអង់គ្លេសពីប្រភពផ្លូវការ។ labs.cloudflare.dev ↗

Cần trước Prerequisites តម្រូវការជាមុន

  • Đã xong bước 2 Completed Step 2 បានបញ្ចប់ជំហាន 2
  • Hiểu exec() và API file Understanding of exec() and file APIs យល់ exec() និង API file
  • Sandbox đang chạy local Sandbox running locally Sandbox កំពុងរត់ local

Bạn sẽ làm được Learning objectives គោលបំណងសិក្សា

  • Dùng createCodeContext() cho môi trường theo ngôn ngữ Use createCodeContext() for language-specific execution environments ប្រើ createCodeContext() សម្រាប់បរិស្ថានតាមភាសា
  • Chạy code bằng runCode() và xử lý output có cấu trúc Execute code with runCode() and process structured output រត់ code ដោយ runCode() និងដំណើរការ output មានរចនាសម្ព័ន្ធ
  • Nhận code động qua request POST Accept dynamic code input via POST requests ទទួល code ថាមវន្តតាម request POST
  • Hỗ trợ nhiều ngôn ngữ lập trình Support multiple programming languages គាំទ្រភាសាសរសេរកម្មវិធីច្រើន
  • Xử lý lỗi khi chạy code mà không sập Handle code execution errors gracefully ដោះស្រាយ error ពេលរត់ code ដោយមិនដួល

Bước 1: Tạo code context Step 1: Create a Code Context ជំហាន 1: បង្កើត code context

Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
A code execution context that provides a language runtime inside your sandbox.
Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
Code contexts set up the right interpreter (Node.js or Python) and can persist state across multiple executions.

A code context is a persistent runtime environment inside the sandbox. Create one like this:

A code context is a persistent runtime environment inside the sandbox. Create one like this:

A code context is a persistent runtime environment inside the sandbox. Create one like this:

typescript
// JavaScript context (uses Node.js)
const jsCtx = await sandbox.createCodeContext({ language: "javascript" });

// TypeScript context (uses Node.js with TypeScript support)
const tsCtx = await sandbox.createCodeContext({ language: "typescript" });

// Python context (uses Python 3)
const pyCtx = await sandbox.createCodeContext({ language: "python" });

Bước 2: Chạy code bằng runCode() Step 2: Execute Code with runCode() ជំហាន 2: រត់ code ដោយ runCode()

Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
A working /code endpoint that executes code and returns structured output.
Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
runCode() gives you structured log arrays and a clean error field — much easier to work with than raw stdout.

Add a /code endpoint to src/index.ts:

Add a /code endpoint to src/index.ts:

Add a /code endpoint to src/index.ts:

typescript
if (url.pathname === "/code") {
  const ctx = await sandbox.createCodeContext({ language: "javascript" });

  const result = await sandbox.runCode(
    `
    console.log('Hello from the sandbox!');
    const nums = [1, 2, 3, 4, 5];
    console.log('Sum:', nums.reduce((a, b) => a + b, 0));
  `,
    { context: ctx },
  );

  return Response.json({
    success: !result.error,
    error: result.error,
    stdout: result.logs.stdout,
    stderr: result.logs.stderr,
  });
}

Test it:

Test it:

Test it:

bash
curl http://localhost:8787/code
json
{
  "success": true,
  "error": null,
  "stdout": ["Hello from the sandbox!\nSum: 15\n"],
  "stderr": []
}

Bước 3: Nhận code động Step 3: Accept Dynamic Code Input ជំហាន 3: ទទួល code ថាមវន្ត

Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
An endpoint that accepts and executes user-provided code via a POST request.
Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
Dynamic code execution is the foundation of AI code executors, coding playgrounds, and interactive tutorials.

Update the /code endpoint to accept a POST body. First, define a type for the request payload:

Update the /code endpoint to accept a POST body. First, define a type for the request payload:

Update the /code endpoint to accept a POST body. First, define a type for the request payload:

typescript
interface CodeRequest {
  code: string;
  language?: "javascript" | "typescript";
}

Then use it in the handler:

Then use it in the handler:

Then use it in the handler:

typescript
if (url.pathname === "/code" && request.method === "POST") {
  const { code, language = "javascript" } =
    (await request.json()) as CodeRequest;

  if (!code || typeof code !== "string") {
    return Response.json({ error: "code is required" }, { status: 400 });
  }

  const ctx = await sandbox.createCodeContext({ language });
  const result = await sandbox.runCode(code, { context: ctx });

  return Response.json({
    success: !result.error,
    error: result.error,
    stdout: result.logs.stdout,
    stderr: result.logs.stderr,
  });
}

Test with JavaScript:

Test with JavaScript:

Test with JavaScript:

bash
curl -X POST http://localhost:8787/code \
  -H "Content-Type: application/json" \
  -d '{"code": "const fibs = [0,1]; for(let i=2;i<8;i++) fibs.push(fibs[i-1]+fibs[i-2]); console.log(fibs)"}'
json
{
  "success": true,
  "error": null,
  "stdout": ["[0, 1, 1, 2, 3, 5, 8, 13]"],
  "stderr": []
}

Bước 4: Xử lý lỗi khi chạy Step 4: Handle Execution Errors ជំហាន 4: ដោះស្រាយ error ពេលរត់

Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
Graceful handling of syntax errors, runtime errors, and invalid input.
Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
Users will submit broken code — your executor needs to return useful error information rather than crashing.

Test with invalid JavaScript:

Test with invalid JavaScript:

Test with invalid JavaScript:

bash
curl -X POST http://localhost:8787/code \
  -H "Content-Type: application/json" \
  -d '{"code": "this is not valid javascript!!!"}'
json
{
  "success": false,
  "error": "SyntaxError: Unexpected identifier 'is'",
  "stdout": [],
  "stderr": []
}

Now wrap the handler in a try/catch to handle unexpected errors too:

Now wrap the handler in a try/catch to handle unexpected errors too:

Now wrap the handler in a try/catch to handle unexpected errors too:

typescript
if (url.pathname === "/code" && request.method === "POST") {
  try {
    const { code, language = "javascript" } = (await request.json()) as {
      code: string;
      language?: "javascript" | "typescript" | "python";
    };

    if (!code || typeof code !== "string") {
      return Response.json({ error: "code is required" }, { status: 400 });
    }

    const ctx = await sandbox.createCodeContext({ language });
    const result = await sandbox.runCode(code, { context: ctx });

    return Response.json({
      success: !result.error,
      error: result.error,
      stdout: result.logs.stdout,
      stderr: result.logs.stderr,
    });
  } catch (err) {
    return Response.json(
      { error: err instanceof Error ? err.message : "Execution failed" },
      { status: 500 },
    );
  }
}

✅ Code executor complete! You can now safely execute JavaScript and Python inside an isolated container and return structured results. Next, you’ll integrate Workers AI to generate the code automatically.

✅ Code executor complete! You can now safely execute JavaScript and Python inside an isolated container and return structured results. Next, you’ll integrate Workers AI to generate the code automatically.

✅ Code executor complete! You can now safely execute JavaScript and Python inside an isolated container and return structured results. Next, you’ll integrate Workers AI to generate the code automatically.