Vercel Sandbox tutorial: run untrusted code safely
By Flavio
Tagged: Services
Create a Vercel Sandbox, upload and run JavaScript, collect its output, restrict network access, enforce a timeout, and stop it safely.
Vercel Sandbox runs code inside an isolated Linux microVM.
You need something like this whenever you’re running code you didn’t write yourself, whether it came from a user, an AI agent, a plugin, or a repo you’re inspecting.
In this tutorial, we’ll send a JavaScript file to a sandbox, run it, read the output, and shut down the session when we’re done.
Why not run the code in a Function?
A regular Vercel Function runs right inside your app, with access to the same environment variables and services you’ve configured. If you execute untrusted code there, it can poke around in that exact same environment.
A sandbox spins up a separate machine with its own filesystem and network rules, keeping the untrusted code completely separate from the Function handling the request:
application -> Sandbox API -> isolated microVM
You’ll still want input validation, authentication, and spending limits in your app. The sandbox just gives untrusted code a safe box to run in.
Create a Node.js project
Start by creating a small TypeScript project:
mkdir sandbox-demo
cd sandbox-demo
npm init -y
Next, install the Sandbox SDK and tsx:
npm install @vercel/sandbox
npm install --save-dev tsx typescript
For authentication, Vercel recommends OIDC. Link this directory to a Vercel project first:
npx vercel link
Then pull down a development token:
npx vercel env pull
The SDK picks up the VERCEL_OIDC_TOKEN written to .env.local. Once you deploy to the linked Vercel project, authentication happens automatically.
Create, run, and stop a sandbox
Create a run.ts file with a minimal script:
import { Sandbox } from '@vercel/sandbox'
const sandbox = await Sandbox.create()
const result = await sandbox.runCommand('node', [
'-e',
"console.log('Hello from the sandbox')",
])
console.log(result.stdout)
console.log(result.exitCode)
await sandbox.stop()
Run it with tsx:
npx tsx --env-file=.env.local run.ts
That prints the command output and exit code:
Hello from the sandbox
0
An exit code of 0 means the command succeeded.
Node.js is the default runtime, though Vercel also offers other Node.js versions and Python runtimes. Check the current runtime list before pinning a specific one.
Always stop in a finally block
There’s a catch with our first script: if runCommand() throws an error, the sandbox stays running.
Wrap your commands in a try block and stop the sandbox inside finally:
import { Sandbox } from '@vercel/sandbox'
const sandbox = await Sandbox.create()
try {
const result = await sandbox.runCommand('node', [
'-e',
"console.log('Hello from the sandbox')",
])
console.log(result.stdout)
} finally {
await sandbox.stop()
}
That way, finally runs whether the command succeeds or fails. Stopping the sandbox right away also keeps your bill down, since you aren’t paying for an idle session waiting to time out.
Upload a file
Passing a one-liner with node -e works fine for quick tests, but for anything bigger you’ll want to write files to the sandbox filesystem.
Add this inside your try block:
const code = `
const prices = [12, 18, 25]
const total = prices.reduce((sum, price) => sum + price, 0)
console.log(JSON.stringify({ total }))
`
await sandbox.writeFiles([
{
path: 'calculate.js',
content: Buffer.from(code),
},
])
Because writeFiles() takes an array, you can upload multiple files in a single call.
Now run the file you just uploaded:
const result = await sandbox.runCommand('node', ['calculate.js'])
if (result.exitCode !== 0) {
throw new Error(result.stderr)
}
const output = JSON.parse(result.stdout)
console.log(output.total)
Your app gets back 55.
Be careful when you parse what comes back. Untrusted code can print whatever it wants, including a huge string or broken JSON, so check the output size and catch any parsing errors.
Add a hard timeout
Sooner or later, someone will submit code that never finishes:
while (true) {}
To guard against that, set a timeout when you create the sandbox:
const sandbox = await Sandbox.create({
timeout: 60 * 1000,
})
This caps the session at one minute. The default timeout is longer, and the maximum allowed depends on your Vercel plan. My advice is to pick the shortest limit that still gives your job room to finish.
Keep in mind that this timeout covers the whole session. Your app should also set its own deadline for waiting on any single command.
Block outgoing network requests
Our calculation doesn’t need internet access at all.
You can lock it down by creating the sandbox with a deny-all network policy:
const sandbox = await Sandbox.create({
timeout: 60 * 1000,
networkPolicy: 'deny-all',
})
With that in place, nothing running inside the sandbox can reach external services.
If your job needs to install packages first, start with network access enabled, run your own setup steps, and then cut off the network before you execute untrusted code:
const sandbox = await Sandbox.create({
networkPolicy: 'allow-all',
})
await sandbox.runCommand('npm', ['install'])
await sandbox.update({
networkPolicy: 'deny-all',
})
If a tool only needs to talk to one specific API, use an allowlist instead of leaving the whole internet open.
Vercel Sandbox can also inject credentials at the network boundary. The firewall attaches the credential only to approved outgoing requests, so the secret never lives as an environment variable inside the sandbox. That’s much safer than handing untrusted code a raw API key.
Return command output from an API route
Now we can move that same flow into a Next.js Route Handler. This route accepts JavaScript from the request and returns its standard output:
import { Sandbox } from '@vercel/sandbox'
export async function POST(request: Request) {
const code = await request.text()
if (code.length > 10_000) {
return new Response('Code is too large', { status: 413 })
}
const sandbox = await Sandbox.create({
timeout: 30 * 1000,
networkPolicy: 'deny-all',
})
try {
await sandbox.writeFiles([
{
path: 'program.js',
content: Buffer.from(code),
},
])
const result = await sandbox.runCommand('node', ['program.js'])
return Response.json({
stdout: result.stdout.slice(0, 20_000),
stderr: result.stderr.slice(0, 20_000),
exitCode: result.exitCode,
})
} finally {
await sandbox.stop()
}
}
It already caps the input and output sizes, but before you expose an endpoint like this publicly, add authentication and rate limiting.
You’ll also want to limit how many sandboxes a single user can spin up. Isolation keeps your app safe, though it won’t stop an open endpoint from running up your bill.
Use snapshots for repeated setup
If every run needs the same set of packages, reinstalling them every time slows everything down. Instead, you can take a snapshot of the filesystem once the packages are installed:
const snapshot = await sandbox.snapshot()
console.log(snapshot.snapshotId)
Taking a snapshot stops that sandbox automatically. Later, you can boot a fresh sandbox straight from it:
const sandbox = await Sandbox.create({
source: {
type: 'snapshot',
snapshotId,
},
})
Stick to snapshots for your own repeatable setup, and never save a shared base snapshot after running untrusted code in that sandbox.
What the sandbox does not solve
A sandbox limits how much damage untrusted code can do, but your app still needs guardrails around it.
Before you ship, decide on a few rules:
- who’s allowed to run code
- which runtimes you’ll allow
- how much CPU time each user gets
- which network destinations are allowed
- how much input and output you keep around
- when files and snapshots expire
Treat any output you get back as untrusted, too, and escape it before rendering it in HTML.
Vercel eve uses Sandbox for code written by an AI agent. The main app handles the coordination, while the agent works with files and commands inside a separate sandbox.
Keep in mind that sandboxes are short-lived. If you need a persistent, always-on Linux VM instead, check out exe.dev.
When you’re ready to try this live, the Vercel deployment documentation walks through deploying the API as a Preview before you send real code to it.
Want me to talk about your product? You can sponsor this site.
Related posts about services: