---
title: Build your startup's product on Vercel Sandbox
description: Build code interpreters, app previews, and upload-processing features with Vercel Sandbox, including authentication, persistence, security, and cost controls.
url: "https://vercel.com/kb/guide/startups-on-vercel-sandbox"
published: 2026-11-25
last_updated: 2026-11-25
authors: Ben Sabic
install_vercel_plugin: npx plugins add vercel/vercel-plugin
search_with_vercel_cli: npx vercel@latest kb search "<query>"
read_with_vercel_cli: "npx vercel@latest kb inspect startups-on-vercel-sandbox"
---

[Vercel Sandbox](https://vercel.com/docs/sandbox) runs untrusted or agent-generated code in isolated Linux microVMs that your application creates through an SDK. Your product can execute code that a model or a customer wrote, outside your own backend and with no virtual machines for your team to operate.

Your backend handles authentication and customer records. Give each sandbox only the files and permissions needed for its task. If you're still choosing an execution environment, compare [AI sandbox providers](https://vercel.com/i/ai-sandbox-providers).

## Decide whether Vercel Sandbox fits your product

Vercel Sandbox is [generally available](https://vercel.com/blog/vercel-sandbox-is-now-generally-available) on the Hobby, Pro, and Enterprise plans. Each sandbox runs in its own Firecracker microVM with a dedicated kernel, a private filesystem, and its own network namespace. Containers share their host's kernel, and [a microVM adds a guest kernel and a virtualization boundary](https://vercel.com/i/microvm-vs-container).

Code in a sandbox has root access. It starts from the default `vercel/sandbox/universal` image, which includes Node.js and Python, or from another [managed or custom image](https://vercel.com/docs/sandbox/concepts/images). Vercel provisions and runs the microVMs. Your code creates them from the [TypeScript SDK](https://vercel.com/docs/sandbox/sdk/javascript), the [Python SDK](https://vercel.com/docs/sandbox/sdk/python), or the CLI.

Sandbox fits when the code your product runs comes from a model, an agent, or a customer, so you can't review it before it executes. For what that boundary does and what it leaves to your application, read [what an AI sandbox is](https://vercel.com/i/what-is-an-ai-sandbox). Each of the three features that follow uses a different sandbox lifecycle:

| Feature                          | Sandbox lifecycle                                          | Main settings                                                       |
| -------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------- |
| Code interpreter for an AI agent | One sandbox for each request, discarded afterward          | `persistent: false`, a short `timeout`, `networkPolicy: 'deny-all'` |
| App builder with live previews   | One named sandbox for each project, stopped and resumed    | `Sandbox.getOrCreate()`, `ports`, `keepLastSnapshots`               |
| Upload or batch processing       | One sandbox for each job, created from a prepared snapshot | `source` with a snapshot ID, `persistent: false`                    |

[Notion runs third-party Workers on Vercel Sandbox](https://vercel.com/customers/notion-workers-vercel-sandbox) so developers and agents can extend its platform. Each Worker has an isolated execution environment with network controls and API credentials that its code cannot read.

### When Sandbox doesn't fit

Sandboxes aren't designed to run continuously. Each session ends at its timeout, and stopping a session ends its processes.

- For application HTTP routes, use [Vercel Functions](https://vercel.com/docs/functions). Choose a traditional VM when a server process must run continuously.
  
- Store large datasets in a database or object store. Persistent sandbox files preserve working state between sessions.
  
- Reviewed code with variable inputs can run on your existing backend.
  

## Prerequisites

Before you begin, make sure you have a [Vercel account](https://vercel.com/signup) ready. For local development, use Node.js 24+ with the latest [Vercel CLI](https://vercel.com/docs/cli).

> **Note:**
>
> The examples use the default 2 vCPUs and stay within Hobby's 45-minute session limit. Hobby is for [personal or non-commercial use](https://vercel.com/legal/terms). Use Pro or Enterprise for a commercial startup product.

## Build with your agent

Use this prompt in your application's repository to build a code interpreter, live app previews, or upload processing with Vercel Sandbox.

### Agent prompt

```txt
Help me add a Vercel Sandbox feature to this application using the guide and its linked SDK documentation. Read and follow the guide using the Vercel CLI: `npx vercel@latest kb inspect startup-on-vercel-sandbox`.

Inspect the repository and its dependencies first. If the intended feature isn't clear, ask whether I want a code interpreter, live app previews, or upload and batch processing. Implement the selected feature using the application's existing framework and conventions.

1. Configure server-side Sandbox authentication for local development and deployment. Use Vercel OIDC when available, and explain any required environment variables without printing secrets.
2. Apply the application's authentication, ownership checks, rate limiting, and input validation before creating or retrieving sandboxes. Identify missing application-specific integrations instead of inventing them.
3. Match persistence to the workload. Use ephemeral sandboxes for interpreter calls and upload jobs. Serialize tool calls that share a script file. For previews, use named persistent sandboxes, restart the server on resume, check readiness, and retain generated source outside the sandbox for recovery after snapshot expiry.
4. Set command and session timeouts, clean up on failures, and surface unsuccessful command exits. Restrict outbound access to what the task needs. Keep credentials outside untrusted code and use credentials brokering for authenticated API calls. Treat preview URLs as public and validate generated output before serving it.
5. Type-check the implementation and test success, failure, timeout, and cleanup paths. Use local mocks where needed and distinguish those results from live Sandbox or model tests.

Return the changed files, required configuration, checks performed, and remaining deployment steps. Explain the relevant plan limits and usage costs before running cloud tests.

To find other KB guides, such as ones on related topics or next steps, search the Vercel Knowledge Base with the Vercel CLI: `npx vercel@latest kb search "<topic>"`
```

## Set up the SDK and authentication

Run these commands from your project directory. Link an existing Vercel project or create one when prompted:

```bash
vercel link
vercel env pull
```

The command saves a project-scoped `VERCEL_OIDC_TOKEN` in `.env.local` for the SDK to read. Development tokens expire after 12 hours, so rerun `vercel env pull` to refresh them. Vercel manages the token for deployed applications.

Install the SDK and the packages for running a TypeScript script locally:

**pnpm**

```bash
pnpm add @vercel/sandbox dotenv @types/node tsx typescript
```

**yarn**

```bash
yarn add @vercel/sandbox dotenv @types/node tsx typescript
```

**npm**

```bash
npm install @vercel/sandbox dotenv @types/node tsx typescript
```

**bun**

```bash
bun add @vercel/sandbox dotenv @types/node tsx typescript
```

Create `index.ts` to test authentication. Running it consumes Sandbox usage and may incur charges on a paid plan:

```typescript
import { config } from 'dotenv';
config({ path: '.env.local' });

import { Sandbox } from '@vercel/sandbox';

async function main() {
  const sandbox = await Sandbox.create({
    persistent: false,
    timeout: 60_000,
  });

  try {
    const result = await sandbox.runCommand('echo', [
      'Hello from Vercel Sandbox!',
    ]);
    console.log(await result.stdout());
  } finally {
    await sandbox.stop();
  }
}

main().catch(console.error);
```

Run the script:

```bash
pnpm tsx index.ts
```

The script prints `Hello from Vercel Sandbox!`. Because it passes `persistent: false` and stops the sandbox in `finally`, the sandbox saves no snapshot and stops as soon as the command finishes.

### Authenticate outside Vercel

Use a team [access token](https://vercel.com/docs/sandbox/concepts/authentication#access-tokens) when Vercel OIDC is unavailable. Set `VERCEL_TEAM_ID`, `VERCEL_PROJECT_ID`, and `VERCEL_TOKEN` in your backend or CI environment.

Pass all three values to every `Sandbox.create()`, `Sandbox.getOrCreate()`, and `Sandbox.get()` call in these examples:

```typescript
const sandbox = await Sandbox.create({
  teamId: process.env.VERCEL_TEAM_ID!,
  projectId: process.env.VERCEL_PROJECT_ID!,
  token: process.env.VERCEL_TOKEN!,
});
```

## Run model-written code as an agent tool

An analytics product can answer questions about a customer's CSV by giving its agent a [code interpreter](https://vercel.com/i/code-interpreter). The model writes Python, the tool runs it in a sandbox, and the agent uses the output to answer.

Add the AI SDK and Zod to your Next.js project:

**pnpm**

```bash
pnpm add ai@latest zod
```

**yarn**

```bash
yarn add ai@latest zod
```

**npm**

```bash
npm install ai@latest zod
```

**bun**

```bash
bun add ai@latest zod
```

Create `app/api/analyze/route.ts` inside an existing Next.js App Router application. Protect it with your application's authentication and rate limiting, and validate the `question` and `csv` strings before creating a sandbox. Enforce input size limits appropriate to your app.

The route omits those application-specific checks. It creates one sandbox per request and gives `ToolLoopAgent` a tool that runs Python:

```typescript
import { Sandbox } from '@vercel/sandbox';
import { ToolLoopAgent, isStepCount, tool } from 'ai';
import { z } from 'zod';

export async function POST(request: Request) {
  // Authenticate the user and validate the input before this point.
  const { question, csv } = await request.json();

  const sandbox = await Sandbox.create({
    persistent: false,
    timeout: 4 * 60 * 1000,
    networkPolicy: 'deny-all',
  });

  try {
    await sandbox.writeFiles([
      { path: 'data.csv', content: Buffer.from(csv) },
    ]);

    const agent = new ToolLoopAgent({
      model: 'anthropic/claude-sonnet-5',
      instructions: [
        'Answer questions about data.csv.',
        'Write a Python script, run it with the runPython tool,',
        'and print the result.',
      ].join(' '),
      tools: {
        runPython: tool({
          description:
            'Run a Python script next to data.csv and return its output.',
          inputSchema: z.object({
            code: z.string().describe('The Python script to run'),
          }),
          execute: async ({ code }) => {
            await sandbox.writeFiles([
              { path: 'main.py', content: Buffer.from(code) },
            ]);
            const result = await sandbox.runCommand({
              cmd: 'python3',
              args: ['main.py'],
              timeoutMs: 30_000,
            });
            return {
              exitCode: result.exitCode,
              stdout: await result.stdout(),
              stderr: await result.stderr(),
            };
          },
        }),
      },
      toolCallConcurrency: 1,
      stopWhen: isStepCount(5),
    });

    const { text } = await agent.generate({ prompt: question });
    return Response.json({ text });
  } finally {
    await sandbox.stop();
  }
}
```

With your development server running, send a question and a small CSV file:

```bash
curl -X POST http://localhost:3000/api/analyze \
  -H "Content-Type: application/json" \
  --data-binary @- <<'JSON'
{
  "question": "What is the total of the amount column?",
  "csv": "product,amount\nApples,20\nPears,30\n"
}
JSON
```

The JSON response should report 50 in `text`. Wording varies by model.

The model string routes the request through AI Gateway. When `AI_GATEWAY_API_KEY` isn't set, the AI SDK [authenticates with the same OIDC token](https://vercel.com/docs/ai-gateway/authentication-and-byok/oidc) that the Sandbox SDK uses. The model call leaves from your route, so the sandbox's network policy doesn't apply to it.

These controls limit the sandbox work and agent loop:

- `timeoutMs` ends a script that runs longer than 30 seconds.
  
- `isStepCount(5)` stops the agent after five steps.
  
- `timeout` stops the sandbox after four minutes, even if the function ends before `finally` runs. With Fluid compute, Vercel Functions default to a [300-second maximum duration](https://vercel.com/docs/functions/configuring-functions/duration). Check for a lower override in your project.
  
- `toolCallConcurrency: 1` runs tools sequentially so one script finishes before the next call replaces `main.py`.
  

With `deny-all`, the script is limited to installed packages and cannot send the CSV to another host. An exit code reports execution status, so validate the answer before customers rely on it.

The [`executeCode`](https://vercel.com/kb/guide/python-ai-sdk-vercel-sandbox) [tool](https://vercel.com/kb/guide/python-ai-sdk-vercel-sandbox) in `ai-sdk-tool-code-execution` creates and stops a sandbox per call. For a full app, [run AI-generated code in Next.js](https://vercel.com/kb/guide/running-ai-generated-code-sandbox).

## Give each project a workspace with a live preview

An app builder turns a prompt into a running application that the customer watches change. Each project needs files that are still there tomorrow, a development server, and a URL to load in an iframe.

> **Warning:**
>
> Persistent sandboxes save a snapshot each time they stop. Snapshot Storage is billed until the snapshot expires or you delete it.

Create `lib/preview.ts`:

```typescript
import { Sandbox } from '@vercel/sandbox';

const STARTER_REPO = 'https://github.com/your-org/starter-app.git';

async function run(sandbox: Sandbox, cmd: string, args: string[]) {
  const result = await sandbox.runCommand(cmd, args);
  if (result.exitCode !== 0) {
    throw new Error(await result.stderr());
  }
}

async function startDevServer(sandbox: Sandbox) {
  await sandbox.runCommand({
    cmd: 'npm',
    args: ['run', 'dev'],
    detached: true,
  });
}

export async function openProject(projectId: string) {
  const sandbox = await Sandbox.getOrCreate({
    name: `project-${projectId}`,
    ports: [3000],
    timeout: 15 * 60 * 1000,
    keepLastSnapshots: { count: 1 },
    resume: true,
    onCreate: async (sbx) => {
      await run(sbx, 'git', ['clone', STARTER_REPO, '.']);
      await run(sbx, 'npm', ['install']);
      await sbx.update({
        networkPolicy: { allow: ['registry.npmjs.org'] },
      });
      await startDevServer(sbx);
    },
    onResume: startDevServer,
  });

  return { sandbox, previewUrl: sandbox.domain(3000) };
}

export async function writeGeneratedFile(
  projectId: string,
  path: string,
  content: string,
) {
  const sandbox = await Sandbox.get({
    name: `project-${projectId}`,
    onResume: startDevServer,
  });
  await sandbox.writeFiles([{ path, content: Buffer.from(content) }]);
}
```

Replace `your-org/starter-app` with your public starter repository.

For a private repository, use a [`git`](https://vercel.com/docs/sandbox/examples/clone-a-private-git-repository) [source with credentials](https://vercel.com/docs/sandbox/examples/clone-a-private-git-repository) in `Sandbox.getOrCreate()` and remove `git clone` from `onCreate`. Keep dependency installation and server startup in the hook. The token stays out of command arguments.

### Create and resume the workspace

On first use, `onCreate` clones the starter, installs its dependencies, and restricts outbound access to the npm registry before starting the server. Add other allowed hosts only when the generated app needs them.

Later calls return the same sandbox without running `onCreate` again. With `resume: true`, a stopped sandbox restores its files and runs `onResume` to restart the server before `openProject()` returns. Processes do not survive a stop. If setup fails, inspect or delete the sandbox before reusing its name because its network policy may still allow unrestricted access.

Two lifecycle rules decide what a customer sees when they come back:

- Sessions end at the `timeout`. Call `sandbox.extendTimeout()` while the customer is active and `sandbox.stop()` when they leave.
  
- Snapshots expire 30 days after their last use by default. With `resume: true`, a project whose snapshot expired is created again from the starter, so keep the generated source in your own database or Git repository.
  

### Serve and update the preview

The starter's `dev` script must listen on port 3000. Detached commands return before the server is ready, so poll `previewUrl` from your backend until it returns a successful response, then load the URL in the iframe.

Anyone with the preview URL can reach it. WebSocket connections can close while the sandbox is still running, so live-reload clients must reconnect.

Before writing to a new directory, create it with `sandbox.mkDir()`. Options such as `ports` apply only on creation; use `sandbox.update()` to change an existing sandbox.

The same pattern gives each customer of a coding agent a workspace. Name the sandbox after the customer or the task, and add [tags](https://vercel.com/docs/sandbox/concepts/tags) to list a customer's sandboxes later. The [v0-style app builder guide](https://vercel.com/kb/guide/v0-clone-openai-agents-vercel-sandbox) builds the complete product, with an agent session, a job queue, and idle shutdown.

## Process uploads and batch jobs from a snapshot

Document-processing products often run the same conversion script on each upload. Prepare its dependencies once in a [snapshot](https://vercel.com/docs/sandbox/concepts/snapshots), then create an isolated sandbox for each untrusted file. Jobs start with outbound access blocked.

Create `scripts/build-snapshot.ts`. It clones your worker repository, installs its dependencies, and saves the result:

```typescript
import { config } from 'dotenv';
config({ path: '.env.local' });

import { Sandbox } from '@vercel/sandbox';

async function main() {
  const sandbox = await Sandbox.create({
    source: {
      type: 'git',
      url: 'https://github.com/your-org/file-worker.git',
      username: 'x-access-token',
      password: process.env.GIT_ACCESS_TOKEN!,
      depth: 1,
    },
    persistent: false,
  });

  try {
    const install = await sandbox.runCommand('npm', ['install']);
    if (install.exitCode !== 0) {
      throw new Error(await install.stderr());
    }

    const snapshot = await sandbox.snapshot();
    console.log(`SANDBOX_SNAPSHOT_ID=${snapshot.snapshotId}`);
  } catch (error) {
    await sandbox.stop().catch(console.error);
    throw error;
  }
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
```

Replace `your-org/file-worker` with your repository, and add a GitHub token that can read it to `.env.local` as `GIT_ACCESS_TOKEN`. Then run the script:

```bash
pnpm tsx scripts/build-snapshot.ts
```

The script prints a line beginning with `SANDBOX_SNAPSHOT_ID=`. Add it to `.env.local` and your project's environment variables. Successful snapshot creation stops the session. If installation or snapshot creation fails, the catch block attempts cleanup and reports the failure.

Create `lib/process-upload.ts` to run `process.js` from your worker repository. Replace that filename if your worker uses another entry point:

```typescript
import { Sandbox } from '@vercel/sandbox';

export async function processUpload(file: Uint8Array) {
  const sandbox = await Sandbox.create({
    source: {
      type: 'snapshot',
      snapshotId: process.env.SANDBOX_SNAPSHOT_ID!,
    },
    persistent: false,
    timeout: 5 * 60 * 1000,
    networkPolicy: 'deny-all',
  });

  try {
    await sandbox.writeFiles([{ path: 'input.bin', content: file }]);

    const result = await sandbox.runCommand({
      cmd: 'node',
      args: ['process.js', 'input.bin', 'output.bin'],
      timeoutMs: 2 * 60 * 1000,
    });
    if (result.exitCode !== 0) {
      throw new Error(await result.stderr());
    }

    const output = await sandbox.readFileToBuffer({ path: 'output.bin' });
    if (!output) {
      throw new Error('The job produced no output file.');
    }
    return output;
  } finally {
    await sandbox.stop();
  }
}
```

The file enters through `writeFiles()` and the result leaves through `readFileToBuffer()`, which resolves to `null` when the file doesn't exist. The job needs no network, so the sandbox starts with `deny-all`. Treat the output as untrusted too, and check its type and size before you store or serve it.

Snapshots keep the software they were built with. New image releases don't change an existing snapshot, so rerun the build script to pick up updates. Each sandbox you create from the snapshot resets its 30-day expiration, so a snapshot in regular use stays available. After it expires it can't start new sandboxes, and you have to build a new one.

Sandbox closes connections that carry no data for 340 seconds, but the command keeps running. For [long-running commands](https://vercel.com/docs/sandbox/examples/execute-long-running-tasks), print progress or start them with `detached: true`. Later log or wait connections still have the idle limit.

For files too large to pass through your function, or jobs that outlast a request, [process uploads through Vercel Blob](https://vercel.com/kb/guide/user-uploaded-files-vercel-sandbox-and-blob).

## Secure the sandbox before customers use it

The microVM separates sandboxed code from your backend, other sandboxes, and the host. Treat this boundary as one layer of protection, then limit the data, network access, and credentials each task receives.

The [Sandbox security challenge](https://vercel.com/blog/findings-from-the-1-million-dollar-vercel-sandbox-challenge) uncovered a Linux kernel vulnerability that leaked host memory from production sandboxes. Vercel worked with the researcher and infrastructure partners to mitigate it.

Sandboxes run on Vercel infrastructure that maintains [SOC 2 Type II certification](https://vercel.com/docs/sandbox/concepts/security), and snapshots are encrypted at rest.

### Restrict outbound network access

Set a [network policy](https://vercel.com/docs/sandbox/concepts/firewall) to limit what untrusted code can reach. The interpreter and upload jobs use `deny-all`. The preview installs dependencies with unrestricted access, then applies an allowlist with `sandbox.update()`.

| Policy             | Effect                                                                              |
| ------------------ | ----------------------------------------------------------------------------------- |
| `'allow-all'`      | The default. All outbound traffic is allowed.                                       |
| `'deny-all'`       | All outbound traffic is blocked, including DNS.                                     |
| `{ allow: [...] }` | TLS connections must negotiate a listed hostname. Other outbound traffic is denied. |

Domain rules match the hostname in the TLS handshake, so they cannot allow plain HTTP. Wildcards such as `*.example.com` match subdomains but exclude `example.com` itself. Test the policy by requesting an unlisted hostname from inside the sandbox and confirming that the command fails.

Shared servers that accept a different HTTP `Host` header can route an allowed TLS connection to another site. Consider [domain fronting](https://vercel.com/docs/sandbox/concepts/firewall#http-and-https) when choosing allowed hosts.

### Keep secrets out of the sandbox

Code in a sandbox can read everything in it, including environment variables you pass with `env`. Keep secrets out of command arguments as well, because Sandbox can store arguments and return them in command API responses. If a command you trust needs a secret, pass it in `env` on that `runCommand()` call.

Use [credentials brokering](https://vercel.com/docs/sandbox/concepts/firewall#credentials-brokering) to add an API credential after a request leaves the sandbox. Create an [AI Gateway API key](https://vercel.com/docs/ai-gateway/authentication-and-byok/authentication) and save it as `AI_GATEWAY_API_KEY` in your backend's environment for this policy:

```typescript
const apiKey = process.env.AI_GATEWAY_API_KEY;
if (!apiKey) {
  throw new Error('AI_GATEWAY_API_KEY is required');
}

const sandbox = await Sandbox.create({
  persistent: false,
  networkPolicy: {
    allow: {
      'ai-gateway.vercel.sh': [
        {
          transform: [
            {
              headers: {
                Authorization: `Bearer ${apiKey}`,
              },
            },
          ],
        },
      ],
    },
  },
});
```

Under this policy, `ai-gateway.vercel.sh` is the one domain the sandbox can reach, and requests to it carry the token. Code in the sandbox can still make any request the token permits, so give the token the narrowest scope the task needs.

### Treat preview URLs as public

Each port in `ports` gets its own public URL, up to 15 for each sandbox. Anyone with the URL can reach the server behind it, and your product's sign-in doesn't cover it. [Expose only the services you intend to share](https://vercel.com/docs/sandbox/examples/expose-a-port).

### Check ownership in your application

Sandbox names are unique within your Vercel project, and your backend can retrieve any of them by name. Sandbox has no record of which of your customers owns `project-123`. Before your backend calls `Sandbox.get()` or `Sandbox.getOrCreate()`, confirm that the signed-in user owns that project. Don't reuse one sandbox for two customers.

## Control what you spend

The examples use the five billing metrics below. [Drives](https://vercel.com/docs/sandbox/concepts/drives) have three more.

| Metric                                                           | What it counts                                                                                                              |
| ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| [Active CPU](https://vercel.com/docs/sandbox/pricing#active-cpu) | Time your code uses the CPU. Waiting on network requests, database queries, or model calls doesn't count.                   |
| Provisioned Memory                                               | Memory allocated to the sandbox, at 2 GB for each vCPU, multiplied by the time it runs, in increments of at least 1 minute. |
| Sandbox Creations                                                | Each `Sandbox.create()` call.                                                                                               |
| Network                                                          | Data the sandbox sends to the internet and all traffic through exposed ports. Downloads are free.                           |
| Snapshot Storage                                                 | The size of your snapshots, in GB each month.                                                                               |

On Pro in `iad1`, [rates](https://vercel.com/docs/sandbox/pricing) are $0.128 per Active CPU hour, $0.0212 per GB-hour of memory, $0.60 per million creations, and $0.08 per GB-month of snapshots.

For a five-minute run with 2 vCPUs averaging 10% CPU utilization, estimated charges are $0.0021 for CPU and $0.0071 for memory. Creations, network transfer, and snapshot storage are extra. For workloads that mostly wait, shorter sessions or fewer vCPUs reduce memory charges.

The examples above apply these controls:

- Pass `persistent: false` for one-off work, so no snapshot is stored.
  
- Set `keepLastSnapshots: { count: 1 }` on sandboxes you keep, so each stop replaces the previous snapshot.
  
- Set the shortest `timeout` the task needs. The default is 5 minutes.
  
- Stop each sandbox as soon as its work is done, in `finally` for one-off jobs. Until a sandbox stops, it accrues Provisioned Memory.
  
- Stay on the default 2 vCPUs, or use 1, until a job proves too slow.
  

Hobby includes a free monthly allowance for personal or non-commercial projects. Sandbox creation pauses when that allowance is exhausted. On Pro, usage draws on the plan's [$20 monthly credit](https://vercel.com/docs/plans/pro-plan#monthly-credit) first and is then billed at the list rates.

Set a [Spend Management](https://vercel.com/docs/spend-management) budget to receive alerts or pause projects at your chosen limit. Track usage by metric in the Usage dashboard.

To attribute cost to a customer, record what `sandbox.stop()` returns. Its result includes `activeCpuDurationMs` and `networkTransfer` for the session that stopped.

Vercel also has a [startups program](https://vercel.com/startups) and [Vercel X](https://vercel.com/x), a six-week accelerator for AI founders at the idea and pre-seed stages. Confirm the current terms with the startups team before you budget around credits.

## Plan for limits as you grow

These limits depend on your plan:

| Limit                                  | Hobby                                                       | Pro                                  |
| -------------------------------------- | ----------------------------------------------------------- | ------------------------------------ |
| Maximum vCPUs for each sandbox         | 4                                                           | 8                                    |
| Maximum memory for each sandbox        | 8 GB                                                        | 16 GB                                |
| Maximum session duration               | 45 minutes                                                  | 24 hours                             |
| Concurrent sandboxes                   | 10                                                          | 10,000                               |
| vCPU allocation rate for new sandboxes | 20 per minute, rising to 40                                 | 150 per minute, rising to 5,000      |
| Control plane requests                 | 1,000 per minute                                            | 10,000 per minute                    |
| Included usage each month              | 5 Active CPU hours, 420 GB-hours of memory, 5,000 creations | Usage draws on the plan's $20 credit |

Enterprise raises the maximum for each sandbox to 32 vCPUs and 64 GB, and has custom pricing and quotas.

On Hobby, 10 concurrent sandboxes means 10 open previews or running jobs at one time. The session maximum applies to one session. You can resume a persistent sandbox for a new session any number of times, so the maximum doesn't limit how long a workspace lives.

The vCPU allocation rate rises with sustained use. An idle Pro team starts at 150 vCPUs per minute, which is 75 new sandboxes at the default 2 vCPUs. The rate climbs by 500 vCPUs per minute each minute up to the maximum, and it returns to the starting rate after 10 minutes without a creation. If a launch or a batch needs more sandboxes than that in its first minute, queue the creations.

Sandboxes run in `iad1` unless you choose one of the 19 [regions](https://vercel.com/docs/sandbox/concepts/regions) for a sandbox or set a project default. Choose the region closest to the data your sandboxes read. Snapshots stay in the region of the sandbox they came from, so rebuild the snapshot when you move jobs to another region.

> **Warning:**
>
> `sandbox.delete()` permanently removes the sandbox and all of its sessions. It can't be undone.

When a customer deletes a project or leaves, call `sandbox.delete({ deleteOrphanSnapshots: true })`. The option also deletes the sandbox's snapshots that no other sandbox uses. Without it, the snapshots remain and are billed until they expire.

## Troubleshooting

| What you observe                                                         | What to check                                                                                                                                      |
| ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| Local SDK calls fail with an authentication error                        | The development token expires after 12 hours. Run `vercel env pull` again.                                                                         |
| The preview URL returns `410` with `SANDBOX_STOPPED`                     | The session was stopped or reached its timeout. Call `openProject()` again to resume the sandbox.                                                  |
| The preview URL returns `502` with `SANDBOX_NOT_LISTENING`               | No process is listening on the port. Confirm that the port in `ports` matches the server's port and that the server is still running.              |
| A resumed sandbox fails with `snapshot_not_found`                        | Its snapshot expired. Call `openProject()`, which passes `resume: true` and creates the sandbox again, then restore the files from your own store. |
| Creating a sandbox from a snapshot fails with `snapshot_region_mismatch` | The snapshot isn't available in the region you're creating the sandbox in. Rebuild the snapshot in that region.                                    |
| Sandbox creation is paused on Hobby                                      | The team used its included allotment. Upgrade to Pro to continue.                                                                                  |

## Next steps

- Look up every option in the [JS SDK reference](https://vercel.com/docs/sandbox/sdk/javascript)
  
- Build the complete app builder with [live Next.js previews and saved projects](https://vercel.com/kb/guide/v0-clone-openai-agents-vercel-sandbox)
  
- Learn [how session duration and persistence work together](https://vercel.com/kb/guide/vercel-sandbox-duration-and-persistence)
  
- Keep working files across sandboxes with [Vercel Drives](https://vercel.com/kb/guide/vercel-drives)
  
- Connect Sandbox to [agent frameworks and model SDKs](https://vercel.com/docs/sandbox/ecosystem)
  
- Check current rates and quotas on the [Sandbox pricing page](https://vercel.com/docs/sandbox/pricing)
  

## Frequently asked questions

### Can I host my startup's app on Vercel Sandbox?

Sandbox sessions have maximum durations of 45 minutes on Hobby and 24 hours on Pro and Enterprise. Stopping a session ends its processes, so use Vercel to host your application and Functions to handle server-side requests. Create sandboxes for the untrusted code your product needs to run.

### Is Vercel Sandbox free to start with?

Hobby includes free Sandbox usage for personal or non-commercial projects, with creation paused when the allowance runs out. Commercial startup products need Pro or Enterprise. On Pro, Sandbox usage draws on the plan's $20 monthly credit before additional charges apply.

### Does Vercel Sandbox have a Python SDK?

Yes. The `vercel-sandbox` package supports Python 3.11 and newer with asynchronous and synchronous APIs. It covers sandbox creation, command execution, file access, snapshots, and network policies.

### Do files in a Vercel Sandbox persist between runs?

By default, yes. When a persistent sandbox stops, Vercel snapshots its filesystem and restores it the next time an SDK call resumes the sandbox. Running processes aren't restored. Sandboxes created with `persistent: false` discard their filesystem when they stop.

## More Vercel Sandbox guides

- [Vercel Sandbox vs CodeSandbox](/kb/guide/vercel-sandbox-vs-codesandbox): A detailed guide to Vercel Sandbox vs CodeSandbox: compute isolation, credential brokering, Active CPU billing, Docker support, persistent environments, and when to choose each product for your AI workloads.
- [Vercel Sandbox vs E2B](/kb/guide/vercel-sandbox-vs-e2b): A detailed guide to Vercel Sandbox vs E2B: compute lifecycle, security controls, code execution, pricing, and when to choose each sandbox for your AI agent workloads.
- [Vercel Sandbox vs Upstash Box](/kb/guide/vercel-sandbox-vs-upstash-box): Compare Vercel Sandbox and Upstash Box as AI agent sandboxes, including isolation, persistence, network controls, SDKs, and deployment regions.

## Reference Architecture

Choose a stack and work through the decisions behind it, with curated documentation, guides, templates, and courses to help you build.

- [Agent stack](/kb/architecture/agents): Build and operate agents with models, tools, and durable workflows.
- [Web applications](/kb/architecture/web): Choose rendering, data, authentication, and caching approaches.
- [Backends](/kb/architecture/backends): Choose a runtime, connect services, and run background work.

[Browse all stacks](/kb/architecture)

## Build with prompts

Build an app, extend an agent, or improve your project with ready-to-use prompts for your coding agent.

[Browse the prompt library](/kb/prompts) · [Read the Markdown index](/kb/prompts.md)

## Search guides from your terminal

Search the Knowledge Base and read guides as Markdown with the Vercel CLI. No login required.

```bash
# Find guides by keyword
npx vercel@latest kb search "rewrites and redirects"
npx vercel@latest kb search "AI SDK streaming"

# Show the latest guides
npx vercel@latest kb

# Print a guide as Markdown, by slug or URL
npx vercel@latest kb inspect <guide>
```
