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:
// 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:
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:
curl http://localhost:8787/code {
"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:
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:
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:
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)"}' {
"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:
curl -X POST http://localhost:8787/code \
-H "Content-Type: application/json" \
-d '{"code": "this is not valid javascript!!!"}' {
"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:
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.