Before deploying, verify each of these:
Before deploying, verify each of these:
Before deploying, verify each of these:
Security
Security
Security
- Input validation on all user-provided data
- Per-user sandbox isolation (never a shared sandbox)
- Secrets stay in the Worker — not in sandbox env vars
- Authentication gates access to code execution
- Rate limiting configured (Workers rate limiting or a KV counter)
Performance & Reliability
Performance & Reliability
Performance & Reliability
- Sandboxes are destroyed with destroy() when no longer needed
- setKeepAlive(true) used for long-running operations, disabled when done
- Error handling and timeouts on all exec() calls
- Logging enabled in wrangler.jsonc
Bước 1: Deploy ứng dụng Step 1: Deploy Your Application ជំហាន 1: Deploy កម្មវិធី
- Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
- Your sandbox application running on Cloudflare's global network.
- Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
- Production deployment makes your app available worldwide via Cloudflare's edge, with automatic scaling and no infrastructure to manage.
Make sure you’re logged in to Wrangler:
Make sure you’re logged in to Wrangler:
Make sure you’re logged in to Wrangler:
npx wrangler login Then deploy:
Then deploy:
Then deploy:
npm run deploy ⛅️ wrangler 4.x.x Uploading worker script… Uploading container image…
(this takes 1-2 minutes on first deploy) ✨ Success! Published my-sandbox
(3.14s) https://my-sandbox.your-subdomain.workers.dev Test the production URL:
Test the production URL:
Test the production URL:
curl https://my-sandbox.your-subdomain.workers.dev/run Bước 2: Cleanup sandbox Step 2: Implement Sandbox Cleanup ជំហាន 2: Cleanup sandbox
- Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
- A pattern that guarantees sandbox resources are freed after every request.
- Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
- Sandboxes consume CPU, memory, and disk space. Failing to destroy them causes resource leaks, higher costs, and eventually hitting capacity limits.
Use try/finally to ensure destroy() is always called, even when errors occur:
Use try/finally to ensure destroy() is always called, even when errors occur:
Use try/finally to ensure destroy() is always called, even when errors occur:
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const sessionId = crypto.randomUUID();
const sandbox = getSandbox(env.Sandbox, sessionId);
try {
const result = await sandbox.exec("npm test");
return Response.json({
success: result.success,
output: result.stdout,
});
} finally {
// Always runs — even if exec() threw or the response already started
await sandbox.destroy();
}
},
}; When to destroy vs. when to keep:
When to destroy vs. when to keep:
When to destroy vs. when to keep:
Bước 3: Quản lý lifecycle sandbox Step 3: Manage Sandbox Lifecycle ជំហាន 3: គ្រប់គ្រង lifecycle sandbox
- Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
- Understanding and controlling every stage of the sandbox lifecycle.
- Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
- Proper lifecycle management prevents timeouts on long tasks and resource leaks on abandoned sandboxes.
The full lifecycle:
The full lifecycle:
The full lifecycle:
getSandbox() → use (exec, files, runCode, ...) → destroy()
↓ ↓
Lazy init on Reuse the same instance
first use across multiple calls Lifecycle methods:
Lifecycle methods:
Lifecycle methods:
const sandbox = getSandbox(env.Sandbox, "my-sandbox");
// Prevent the sandbox from automatically sleeping (sends heartbeat pings)
await sandbox.setKeepAlive(true);
// Re-enable automatic sleep when you're done with long operations
await sandbox.setKeepAlive(false);
// Terminate the container and free all resources
await sandbox.destroy(); const sandbox = getSandbox(env.Sandbox, "my-sandbox", {
sleepAfter: "30m", // sleep after 30 minutes of inactivity (default: "10m")
}); setKeepAlive for long-running tasks:
setKeepAlive for long-running tasks:
setKeepAlive for long-running tasks:
if (url.pathname === "/build" && request.method === "POST") {
const sandbox = getSandbox(env.Sandbox, `build-${crypto.randomUUID()}`);
try {
// Prevent automatic sleep during the long build process
await sandbox.setKeepAlive(true);
// Clone, install, and build
await sandbox.gitCheckout("https://github.com/my-org/my-app.git");
await sandbox.exec("npm ci", {
cwd: "/workspace/my-app",
timeout: 120_000,
});
const buildResult = await sandbox.exec("npm run build", {
cwd: "/workspace/my-app",
timeout: 180_000,
});
return Response.json({
success: buildResult.success,
output: buildResult.stdout,
});
} finally {
await sandbox.destroy();
}
} Bước 4: Cấu hình production Step 4: Production Configuration ជំហាន 4: កំណត់ production
- Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
- An optimized wrangler.jsonc tuned for production workloads.
- Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
- Development defaults (lite instances, low max_instances) are not suitable for real traffic. Choose an instance type that matches your workload.
Update your wrangler.jsonc for production:
Update your wrangler.jsonc for production:
Update your wrangler.jsonc for production:
{
"name": "my-sandbox",
"main": "src/index.ts",
"compatibility_date": "2026-01-06", // Update to your deploy date
"compatibility_flags": ["nodejs_compat"],
"observability": {
"enabled": true,
},
"containers": [
{
"class_name": "Sandbox",
"image": "./Dockerfile",
"instance_type": "standard-1",
"max_instances": 20,
},
],
"durable_objects": {
"bindings": [
{
"class_name": "Sandbox",
"name": "Sandbox",
},
],
},
"migrations": [
{
"new_sqlite_classes": ["Sandbox"],
"tag": "v1",
},
],
} Container instance types:
Container instance types:
Container instance types:
Scale max_instances based on your expected concurrent users. For most production apps, standard-1 is a good starting point.
Scale max_instances based on your expected concurrent users. For most production apps, standard-1 is a good starting point.
Scale max_instances based on your expected concurrent users. For most production apps, standard-1 is a good starting point.
Bước 5: Monitor bản deploy Step 5: Monitor Your Deployment ជំហាន 5: Monitor ការដាក់ឱ្យប្រើ
- Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
- Visibility into your running production deployment via the Cloudflare dashboard and logs.
- Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
- You can't fix what you can't see — monitoring tells you when things go wrong before your users do.
In the Cloudflare Dashboard:
In the Cloudflare Dashboard:
In the Cloudflare Dashboard:
- Go to Workers & Pages → your worker
- Click Logs to see real-time invocation logs
- Check Metrics for request counts, error rates, and CPU time
- Open Settings → Observability to configure log retention
Test production is working:
Test production is working:
Test production is working:
# Basic smoke test
curl https://my-sandbox.your-subdomain.workers.dev/run
# Code execution test
curl -X POST https://my-sandbox.your-subdomain.workers.dev/code \
-H "Content-Type: application/json" \
-d '{"code": "console.log(\"Production sandbox working!\", new Date().toISOString())"}' Bạn đã xong lab Sandbox SDK! You completed the Sandbox SDK lab! អ្នកបានបញ្ចប់ lab Sandbox SDK!
You've gone from zero to a production-ready secure code execution environment on Cloudflare's global network.
You've gone from zero to a production-ready secure code execution environment on Cloudflare's global network.
You've gone from zero to a production-ready secure code execution environment on Cloudflare's global network.
What you built
What you built
What you built
- 01 Set up a sandbox project and executed your first command
- 02 Mastered exec(), writeFile(), readFile(), and listFiles()
- 03 Built a multi-language code executor with runCode()
- 04 Created an AI-powered code executor using Workers AI
- 05 Built a live app preview with git, processes, and port proxying
- 06 Applied production security: isolation, secrets, validation, auth
- 07 Deployed to Cloudflare's global network with proper lifecycle management
What to build next
What to build next
What to build next
Share what you built with #CloudflareSandbox and connect with the community!
Share what you built with #CloudflareSandbox and connect with the community!
Share what you built with #CloudflareSandbox and connect with the community!