---
title: Migrate from Upstash Box to Vercel Sandbox
description: Migrate from Upstash Box to Vercel Sandbox in TypeScript or Python, including runtimes, persistent files, network policies, agents, and a staged cutover.
keywords: ["Vercel Sandbox","Upstash Box","migrate from Upstash Box","AI agent sandbox","sandbox migration","coding agent sandbox"]
url: "https://vercel.com/kb/guide/migrate-from-upstash-box-to-vercel-sandbox"
published: 2026-12-01
last_updated: 2026-12-01
authors: Ben Sabic
related_resources:
  - title: "Vercel Sandbox vs Upstash Box"
    url: "/kb/guide/vercel-sandbox-vs-upstash-box"
    description: "Compare Vercel Sandbox and Upstash Box as AI agent sandboxes, including isolation, persistence, network controls, SDKs, and deployment regions."
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 migrate-from-upstash-box-to-vercel-sandbox"
---

To move sandbox workloads from [Upstash Box](https://upstash.com/docs/box/overall/how-it-works) to [Vercel Sandbox](https://vercel.com/docs/sandbox), update your application's Box calls to use Vercel's TypeScript or Python SDK and adapt runtime setup, lifecycle handling, and network rules. Review the [migration limitations](#what-doesn%27t-map-from-upstash-box) before starting if your application relies on the agent API, schedules, keep-alive boxes, or authenticated public URLs.

Both products preserve files by default, but their sessions end differently. Standard boxes pause after 1 hour of inactivity on Free or 6 hours on paid plans, then wake when new work arrives. Vercel sessions end at their timeout or when your code stops them, and your application must restart any processes it needs after resuming the sandbox by name.

You can use Vercel Sandbox from an application on any host. Your backend connects through the SDK using [Vercel credentials](https://vercel.com/docs/sandbox/concepts/authentication), while sandboxed code runs on Vercel's infrastructure. Your application can stay with its current hosting provider.

## Prerequisites

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

## Migrate with your agent

Use this prompt in your application's repository to have a coding agent check where Upstash Box is used and prepare the migration:

### Agent prompt

```txt
Migrate this codebase from Upstash Box to Vercel Sandbox.

1. Read and follow the migration guide using the Vercel CLI: `npx vercel@latest kb inspect migrate-from-upstash-box-to-vercel-sandbox`.
2. Inventory `@upstash/box` and `upstash_box` imports and call sites, including runtimes, sizes, commands, code execution, files, pauses, snapshots, ephemeral boxes, init commands, git helpers, public URLs, environment variables, attached headers, and network policies. Preserve the application's language and authorization checks.
3. Identify features that need a different design, including the agent API, schedules, the managed browser, idle auto-pause, keep-alive boxes, authenticated public URLs, live sessions, read-only API keys, and SSH. Ask for a decision only where that choice blocks implementation.
4. Keep both providers behind one application module. Select the provider for each new agent session and retain that choice for the session's lifetime. Keep the Upstash path available until I approve cutover.
5. Port one call site at a time. Check units, paths, users, shell use, cleanup, and persistence against the guide and the SDK references: https://vercel.com/docs/sandbox/sdk/javascript and https://vercel.com/docs/sandbox/sdk/python
6. Plan how to stop writes, export and verify files, and reconcile changes if we roll back. Do not delete Upstash boxes or snapshots, or revoke API keys.
7. Run local checks first. Describe any live test and the resources it creates before running it. Report the results, remaining configuration, and cutover plan. Do not switch production traffic without my approval.
```

## How Upstash Box features map to Vercel Sandbox

Box API keys map to Vercel project credentials, runtimes map to images, and named persistent sandboxes replace box IDs and pauses. Other features, such as the agent API and schedules, require a [different approach](#what-doesn%27t-map-from-upstash-box). Before migrating, [compare Vercel Sandbox and Upstash Box](https://vercel.com/kb/guide/vercel-sandbox-vs-upstash-box) for your workload.

You can keep using TypeScript or Python. The mappings use TypeScript names for both SDKs, and [step 5](#5.-replace-box-creation,-commands,-and-file-operations) lists the Python names.

### Projects, runtimes, and compute

Replace the Box API key with Vercel project credentials, and select an image in place of a runtime.

| Upstash Box                                                                                                                                               | Vercel Sandbox                                                                                                                              | What you change                                                                                                                                                                                                                                                                                                              |
| --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Upstash account that issued the Box API key                                                                                                               | Vercel project                                                                                                                              | Each sandbox belongs to the project that issued its credentials.                                                                                                                                                                                                                                                             |
| API key in `UPSTASH_BOX_API_KEY`                                                                                                                          | [OIDC token](https://vercel.com/docs/sandbox/concepts/authentication) in `VERCEL_OIDC_TOKEN`, or an access token with team and project IDs  | Run `vercel link` and `vercel env pull` for local development.                                                                                                                                                                                                                                                               |
| [`runtime`](https://upstash.com/docs/box/overall/how-it-works) of `node`, `python`, `golang`, `ruby`, or `rust` on Debian, each with an `-alpine` variant | [Managed image](https://vercel.com/docs/sandbox/concepts/images) for Node.js and Python, or a custom OCI image in Vercel Container Registry | Vercel has no managed Go, Ruby, or Rust image. Install the toolchain and save it in a snapshot, or build a custom image.                                                                                                                                                                                                     |
| `size` of `small` (2 vCPUs, 4 GB), `medium` (4 vCPUs, 8 GB), or `large` (8 vCPUs, 16 GB)                                                                  | `resources.vcpus`, with 2 GB of memory per vCPU                                                                                             | Set 2, 4, or 8 vCPUs to keep the same CPU and memory. An 8-vCPU sandbox requires Pro or Enterprise.                                                                                                                                                                                                                          |
| Disk of 10 GB, 20 GB, or 30 GB, set by `size`                                                                                                             | 64 GB of local disk for every size                                                                                                          | Remove disk sizing from your size choice.                                                                                                                                                                                                                                                                                    |
| AWS `us-east-1` for every box                                                                                                                             | `region`, with one of [19 region IDs](https://vercel.com/docs/sandbox/concepts/regions) such as `iad1`                                      | The default region, `iad1`, is in Washington, D.C. Choose a region for each sandbox or set a project default. Snapshots and [Drives](https://vercel.com/docs/sandbox/concepts/drives) use the main region; configured [failover](https://vercel.com/docs/sandbox/concepts/regions#failover-regions) can load them elsewhere. |
| Commands run through `sh -c` as the non-root `boxuser`, in `/workspace/home`                                                                              | Commands run without a shell as the image's default user, which is `ubuntu` or `arch` on managed images, in `/vercel`                       | Use `bash -c` for shell syntax and `sudo: true` for root commands. Update absolute paths.                                                                                                                                                                                                                                    |
| Box ID from `box.id`, with an optional `name`                                                                                                             | Sandbox `name`                                                                                                                              | Choose a name at creation and store it in place of the ID.                                                                                                                                                                                                                                                                   |
| Up to five `labels`                                                                                                                                       | Up to five `tags`                                                                                                                           | Labels are strings, and tags are key-value pairs. Store additional metadata in your application database, keyed by sandbox name.                                                                                                                                                                                             |

### Lifecycle and state

Vercel saves a persistent sandbox's filesystem when it stops. Use its name to find the sandbox later and resume it from that saved state.

| Upstash Box                                                                                                 | Vercel Sandbox                                                              | What you change                                                                                                                              |
| ----------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| Idle auto-pause after 1 hour on Free or 6 hours on paid plans                                               | Session `timeout`, 5 minutes by default, extended with `extendTimeout()`    | Vercel Sandbox has no idle timeout. Set a timeout that covers the work, extend it while work continues, and stop the sandbox from your code. |
| No session limit for a standard box                                                                         | Session of up to 45 minutes on Hobby, or 24 hours on Pro and Enterprise     | Persistent sandboxes span multiple sessions.                                                                                                 |
| `box.pause()`, which keeps files and stops processes                                                        | `sandbox.stop()`, which saves files                                         | Rename the call. Neither product keeps running processes.                                                                                    |
| `box.resume()`, or new work sent to a paused box                                                            | Resume on SDK operations such as `runCommand()`                             | Remove the resume call. The next command or file operation resumes a stopped sandbox.                                                        |
| `Box.get(id)` or `Box.getByName(name)`                                                                      | `Sandbox.get({ name })`                                                     | Look up sandboxes by name.                                                                                                                   |
| `box.delete()`                                                                                              | `sandbox.delete()`                                                          | Pass `persistent: false` for disposable sandboxes.                                                                                           |
| `initCommand`, which runs on create and on each resume                                                      | `onCreate` and `onResume` hooks in the TypeScript SDK                       | Start processes with a detached `runCommand()` after creation and after each resume.                                                         |
| [`keepAlive: true`](https://upstash.com/docs/box/overall/keep-alive)                                        | No equivalent                                                               | Sessions end at their timeout. See the [keep-alive alternatives](#idle-auto-pause-and-keep-alive-boxes).                                     |
| [`EphemeralBox`](https://upstash.com/docs/box/overall/ephemeral-box), deleted after a `ttl` of up to 3 days | `persistent: false`, with a `timeout`                                       | Convert the TTL from seconds to milliseconds. Your plan's session limit replaces the 3-day maximum.                                          |
| [`box.snapshot()`](https://upstash.com/docs/box/overall/snapshots), then `Box.fromSnapshot(id)`             | Automatic snapshot on stop, or `sandbox.snapshot()`, then a snapshot source | `snapshot()` stops the session. Reconnect by sandbox name, and store a snapshot ID only to seed new sandboxes.                               |
| Snapshots that stay until you delete them                                                                   | Snapshots that expire 30 days after last use by default                     | Set `snapshotExpiration` to match your retention policy. Use `0` to disable expiry.                                                          |

### Networking and secrets

The firewall's `networkPolicy` option replaces Box's `networkPolicy` and `attachHeaders` options, and public port URLs replace `getPublicURL()`.

| Upstash Box                                                                                                         | Vercel Sandbox                                                                        | What you change                                                                                                                   |
| ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| [`box.getPublicURL(port)`](https://upstash.com/docs/box/overall/preview), without declaring a port list at creation | `ports` and `sandbox.domain(port)`                                                    | List up to 15 ports at creation. `domain()` returns the URL string, and `getPublicURL()` returns an object with a `url` property. |
| `bearerToken` and `basicAuth` on a public URL                                                                       | No equivalent                                                                         | Anyone with a port's URL can reach it. Authenticate callers in the server that runs inside the sandbox.                           |
| HTTP requests that resume a paused box                                                                              | No equivalent                                                                         | Requests to a stopped sandbox's URL return HTTP 410. Resume the sandbox from your backend first.                                  |
| `networkPolicy` with `mode: 'deny-all'`                                                                             | `deny-all` network policy                                                             | `deny-all` also blocks DNS.                                                                                                       |
| `mode: 'custom'` with `allowedDomains`                                                                              | Domain allow list in `networkPolicy`                                                  | On both products, a custom policy denies other destinations, and `*.example.com` doesn't match `example.com`.                     |
| `allowedCidrs` and `deniedCidrs`                                                                                    | CIDR lists in `subnets.allow` and `subnets.deny`                                      | Denied CIDR ranges take precedence over allowed domains and ranges on both products.                                              |
| `box.updateNetworkPolicy()`                                                                                         | `update()` with `networkPolicy`                                                       | Each Vercel update replaces the whole policy.                                                                                     |
| `env`, set at creation                                                                                              | `env`, at creation or for each command                                                | Keep the option name.                                                                                                             |
| [`attachHeaders`](https://upstash.com/docs/box/overall/attach-headers), matched by host and set at creation         | [Brokering rules](https://vercel.com/docs/sandbox/concepts/firewall) with `transform` | Vercel rules can also match on path, method, query, and headers, and can change on a running sandbox.                             |
| `git` option and [`box.git`](https://upstash.com/docs/box/overall/git) helpers                                      | `git` source at creation, then `runCommand('git', [...])`                             | Pass the token as the source's `password`. Run commits and pushes as commands.                                                    |

### Agents, schedules, and the browser

Upstash Box runs coding agents, cron schedules, and a managed browser. Vercel Sandbox has no built-in equivalent, so your application runs each in a sandbox.

| Upstash Box                                                                                               | Vercel Sandbox                   | What you change                                                                                                     |
| --------------------------------------------------------------------------------------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| [`agent`](https://upstash.com/docs/box/overall/agent) option, `box.agent.run()`, and `box.agent.stream()` | No equivalent in the Sandbox SDK | Run the coding agent in the sandbox from your application. See the [coding agent options](#built-in-coding-agents). |
| `mcpServers` and `skills`                                                                                 | No equivalent                    | Configure MCP servers and skills in the agent you run.                                                              |
| [`box.schedule`](https://upstash.com/docs/box/overall/schedules)                                          | No equivalent                    | Call the Sandbox SDK from a scheduled function or your own scheduler. See the [schedule options](#box-schedules).   |
| `browser: true` and [`box.browser`](https://upstash.com/docs/box/overall/browser/overview)                | No equivalent                    | Install a browser in an image, or connect a hosted browser. See the [browser options](#managed-browser).            |

## Steps

### 1\. Find where your application uses Upstash Box

Search for Upstash Box imports, call sites, and environment variables, then trace aliases through your code to identify features that need a replacement.

```bash
grep -rnE \
  "@upstash/box|upstash_box|UPSTASH_BOX" \
  --include="*.py" --include="*.ts" --include="*.tsx" \
  --include="*.js" --include="*.mjs" \
  --exclude-dir=node_modules --exclude-dir=.venv \
  --exclude-dir=venv .
```

Also check `.env` files, `package.json`, and `requirements.txt` or `pyproject.toml` for the `@upstash/box` or `upstash-box` dependency and `UPSTASH_BOX_API_KEY`.

Match what you find to the steps that follow:

| In your code                                                                                                                  | Go to                                                                                   |
| ----------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| `runtime`, `size`, or packages installed with `sudo apt-get`                                                                  | [Step 4](#4.-move-your-box-runtime-to-a-vercel-image)                                   |
| `Box.create()`, `box.exec`, `box.files`, or `box.cd()`                                                                        | [Step 5](#5.-replace-box-creation,-commands,-and-file-operations)                       |
| `Box.get()`, `box.pause()`, `box.snapshot()`, `Box.fromSnapshot()`, `EphemeralBox`, or `initCommand`                          | [Step 6](#6.-replace-pause-and-resume-with-named-sandboxes)                             |
| The `git` option or `box.git`                                                                                                 | [Step 7](#7.-replace-box-git-helpers-with-a-git-source-and-git-commands)                |
| `box.getPublicURL()`                                                                                                          | [Step 8](#8.-replace-box-public-urls-with-public-ports)                                 |
| `networkPolicy`, `env`, or `attachHeaders`                                                                                    | [Step 9](#9.-replace-box-network-policies,-environment-variables,-and-attached-headers) |
| `agent`, `box.schedule`, `box.browser`, `keepAlive`, `box.exec.session()`, `bearerToken`, `basicAuth`, or a read-only API key | [What doesn't map from Upstash Box](#what-doesn%27t-map-from-upstash-box)               |

### 2\. Link a Vercel project and authenticate

Vercel Sandbox supports OpenID Connect (OIDC) tokens and access tokens. Link your local directory to the project that will own your sandboxes:

```bash
vercel link
```

Save the environment variables and development OIDC token to `.env.local`:

```bash
vercel env pull
```

Load `.env.local` for local runs with Node.js's `--env-file=.env.local` option or the Python sample's `python-dotenv` dependency. The development OIDC token expires after 12 hours; run `vercel env pull` again to refresh it. Applications deployed on Vercel receive automatically managed tokens.

For a backend hosted elsewhere, create a [Vercel access token](https://vercel.com/docs/rest-api#creating-an-access-token) and copy your [team ID](https://vercel.com/docs/accounts#find-your-team-id) and [project ID](https://vercel.com/docs/project-configuration/general-settings#project-id). Save them as environment variables and pass them to the SDK:

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

Without an OIDC token, the Python SDK reads these three environment variables automatically. No authentication arguments are needed in `create_sandbox()`.

Keep `UPSTASH_BOX_API_KEY` until the migrated workloads pass verification. Retain keys used by workloads remaining on Upstash Box.

### 3\. Install the Vercel Sandbox SDK

Install `@vercel/sandbox` for TypeScript and JavaScript:

**pnpm**

```bash
pnpm i @vercel/sandbox
```

**npm**

```bash
npm i @vercel/sandbox
```

**yarn**

```bash
yarn add @vercel/sandbox
```

**bun**

```bash
bun add @vercel/sandbox
```

For Python, install `vercel-sandbox` and `python-dotenv` to load local credentials. The SDK requires Python 3.11 or later, while `upstash-box` supports Python 3.9, so upgrade older interpreters first:

**uv**

```bash
uv add vercel-sandbox python-dotenv
```

**pip**

```bash
pip install vercel-sandbox python-dotenv
```

Keep the `@upstash/box` or `upstash-box` package until no workloads use it.

### 4\. Move your Box runtime to a Vercel image

Choose a Vercel [managed image](https://vercel.com/docs/sandbox/concepts/images) or a custom image in Vercel Container Registry based on your Box `runtime` and dependency setup:

| Box runtime                                                            | Vercel replacement                                                                                                                                                       |
| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `node`                                                                 | A managed image such as `vercel/sandbox/node:24`. With no `image`, a sandbox uses `vercel/sandbox/universal`, which includes current Node.js LTS and Python versions.    |
| `python`                                                               | `vercel/sandbox/python:3.14`, or the default `vercel/sandbox/universal` image. Build a custom image if the required runtime version is not available as a managed image. |
| `golang`, `ruby`, or `rust`                                            | A managed image with the toolchain installed and saved in a snapshot, or a custom image built into Vercel Container Registry                                             |
| An `-alpine` variant                                                   | A managed image, after you rebuild native code that was compiled for Alpine's musl libc                                                                                  |
| Packages installed with `sudo apt-get install`, or by an `initCommand` | The same packages installed once and saved in a snapshot, or `RUN` instructions in a custom image's Dockerfile                                                           |

Check the tool versions in your box, for example with `node --version` or `python3 --version`, and compare them with the managed image before you choose. Managed images use Ubuntu or Arch Linux with glibc, so rebuild native code compiled for an Alpine runtime's musl libc.

If a managed image meets your needs, continue to [step 5](#5.-replace-box-creation,-commands,-and-file-operations). For a custom image, install Docker and start from the runtime's official image. Target `linux/amd64` and stay within the registry limits of 15 GB per image and 2 GB per compressed layer. This Dockerfile installs a system package on a Go image:

```docker
FROM golang:1.25
RUN apt-get update && apt-get install -y jq
WORKDIR /workspace
```

Set the base image tag to the toolchain version your box uses. Log in, then build and push the image from the linked project:

```bash
vercel vcr login docker
vercel vcr build docker . agent-runtime:latest --push
```

Wait for Ready on the registry repository's details page before creating a sandbox. Creation fails with `image_not_ready` while the image is being prepared. Pass the repository and tag as `image`:

**Vercel Sandbox (TypeScript)**

```javascript
const sandbox = await Sandbox.create({ image: 'agent-runtime:latest' });
```

**Vercel Sandbox (Python)**

```python
box = await sandbox.create_sandbox(image="agent-runtime:latest")
```

Box runs `initCommand` whenever its container starts. Vercel Sandbox has no init command and doesn't run an image's `ENTRYPOINT` or `CMD`, so start processes with `runCommand()` after creation and [restart them after each resume](#restart-processes-after-a-resume). Custom images use their configured user and `WORKDIR`, or `/` when no working directory is set. Managed images use `/vercel` instead of Box's `/workspace/home`.

Set CPU resources when creating the sandbox with `resources.vcpus`; each vCPU includes 2 GB of memory. This replaces Box's creation-time `size` choice.

#### Install dependencies in a managed image

For an Ubuntu-based managed image, update the package index before installing packages with `apt-get` and `sudo`. These calls replace a `sudo apt-get install` command on a box:

```javascript
await sandbox.runCommand({ cmd: 'apt-get', args: ['update'], sudo: true });
await sandbox.runCommand({
  cmd: 'apt-get',
  args: ['install', '-y', 'golang'],
  sudo: true,
});
```

Installed packages remain across persistent sessions. To reuse them in new sandboxes, take a snapshot after the install and create each sandbox from it. The Ubuntu package provides the distribution's Go version, so build a custom image to pin a toolchain version. Use the package manager supplied by your image when running Arch or a custom image.

### 5\. Replace box creation, commands, and file operations

Replace Box's creation, command, and file calls with the corresponding Vercel methods. `Sandbox.create()` uses project credentials and an image reference instead of an API key and a runtime name.

Route every sandbox operation through one module in your application, and add a flag that selects Upstash Box or Vercel for each new agent session. Add the Vercel calls beside the Box calls, and keep the Box path until step 10.

#### TypeScript SDK calls

| Task                          | Upstash Box                                             | Vercel Sandbox                                                                       |
| ----------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| Import                        | `Box` from `@upstash/box`                               | `Sandbox` from `@vercel/sandbox`                                                     |
| Create a sandbox              | `Box.create()` with a `runtime`                         | `Sandbox.create()`                                                                   |
| Set the lifetime              | No session limit, or `ttl` in seconds on `EphemeralBox` | `timeout`, in milliseconds                                                           |
| Set resources                 | `size`                                                  | `vcpus` in `resources`                                                               |
| Set environment variables     | `env`                                                   | `env`                                                                                |
| Run a command                 | `box.exec.command()` with a shell command string        | `sandbox.runCommand()` with the binary and argument array                            |
| Run a code snippet            | `box.exec.code()` with `code` and `lang`                | `writeFiles()`, then `runCommand()`                                                  |
| Read output                   | `run.result`, or `run.stdout` and `run.stderr`          | Await `result.stdout()` and `result.stderr()`                                        |
| Get the exit code             | `run.exitCode`                                          | `result.exitCode`                                                                    |
| Stream output                 | `box.exec.stream()`                                     | `runCommand()` with `detached: true`, then `command.logs()`                          |
| Change directory              | `box.cd(path)`                                          | `cwd` on each command                                                                |
| Write a file                  | `box.files.write()` with `path` and `content`           | `sandbox.writeFiles()` with an array of file objects                                 |
| Read a file                   | `box.files.read(path)`                                  | `sandbox.fs.readFile()` with `'utf8'`, or `readFileToBuffer()` with `path` for bytes |
| List, create, or remove paths | `files.list()`, `files.mkdir()`, and `files.remove()`   | `sandbox.fs.readdir()`, `sandbox.fs.mkdir()`, and `sandbox.fs.rm()`                  |
| Find a sandbox                | `Box.get(id)` or `Box.getByName(name)`                  | `Sandbox.get({ name })`                                                              |
| List sandboxes                | `Box.list({ label })`                                   | `Sandbox.list({ tags })`, which filters on one tag                                   |
| End a session                 | `box.pause()`                                           | `sandbox.stop()`                                                                     |
| Delete a sandbox              | `box.delete()`                                          | `sandbox.delete()`                                                                   |

The Box script selects a runtime and runs commands as strings:

```javascript
import { Box } from '@upstash/box';

const box = await Box.create({
  runtime: 'python',
  size: 'small',
  env: { PYTHONUNBUFFERED: '1' },
});

try {
  await box.files.write({ path: 'main.py', content: 'print(21 * 2)' });

  const run = await box.exec.command('timeout 60 python3 main.py');
  console.log(run.result);
  console.log('exit code', run.exitCode);
} finally {
  await box.delete();
}
```

The Vercel version runs the same Python script in a disposable sandbox:

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

const sandbox = await Sandbox.create({
  timeout: 10 * 60 * 1000,
  resources: { vcpus: 2 },
  env: { PYTHONUNBUFFERED: '1' },
  persistent: false,
});

try {
  await sandbox.writeFiles([
    { path: 'main.py', content: Buffer.from('print(21 * 2)') },
  ]);

  const result = await sandbox.runCommand({
    cmd: 'python',
    args: ['main.py'],
    timeoutMs: 60_000,
  });
  console.log(await result.stdout());
  console.log('exit code', result.exitCode);
} finally {
  await sandbox.stop();
}
```

The Vercel script uses the default image with 2 vCPUs and 4 GB of memory, matching a `small` box. `timeoutMs` replaces the Box command's `timeout 60` wrapper, and the 10-minute `timeout` limits the session. With `persistent: false`, stopping the sandbox discards its files, as `box.delete()` does.

Save the Vercel script as `sandbox.mjs`, then run it with the environment file loaded:

```bash
node --env-file=.env.local sandbox.mjs
```

The script prints `42` and `exit code 0`, then stops the sandbox.

#### Python SDK calls

The Vercel Python samples import the `sandbox` module and store the resulting Vercel sandbox in a local variable named `box`. That variable is unrelated to Upstash's `Box` class.

For synchronous code, such as an application using Upstash's `Box` rather than `AsyncBox`, import `sync` from `vercel.sandbox` as `sandbox`. Remove `await` and use regular context managers.

| Task                          | Upstash Box                                             | Vercel Sandbox                                              |
| ----------------------------- | ------------------------------------------------------- | ----------------------------------------------------------- |
| Import                        | `Box` or `AsyncBox` from `upstash_box`                  | `sandbox` from `vercel`                                     |
| Create a sandbox              | `Box.create()` with `runtime="python"`                  | `sandbox.create_sandbox()`                                  |
| Set the lifetime              | No session limit, or `ttl` in seconds on `EphemeralBox` | `execution_time_limit`, in seconds or as a `timedelta`      |
| Set resources                 | `size`                                                  | `resources` with `SandboxResources`                         |
| Set environment variables     | `env`                                                   | `env`                                                       |
| Run a command                 | `box.exec.command()` with a shell command string        | `box.run_command()` with the binary and argument list       |
| Run a code snippet            | `box.exec.code()` with `code` and `lang`                | `box.fs.write_text()`, then `run_command()`                 |
| Read output                   | `run.result`, or `run.stdout` and `run.stderr`          | `result.stdout.decode()`, with `capture_output=True`        |
| Get the exit code             | `run.exit_code`                                         | `result.returncode`                                         |
| Change directory              | `box.cd(path)`                                          | `cwd` on each call                                          |
| Write a file                  | `box.files.write()` with `path` and `content`           | `box.fs.write_text()` with the path and text                |
| Read a file                   | `box.files.read(path)`                                  | `box.fs.read_text(path)`                                    |
| List, create, or remove paths | `files.list()`, `files.mkdir()`, and `files.remove()`   | `box.fs.listdir()`, `box.fs.mkdir()`, and `box.fs.remove()` |
| Find a sandbox                | `Box.get(box_id)` or `Box.get_by_name(name)`            | `sandbox.get_sandbox()` with `name`                         |
| List sandboxes                | `Box.list(label=...)`                                   | `sandbox.query_sandboxes()`                                 |
| End a session                 | `box.pause()`                                           | `box.stop()`                                                |
| Delete a sandbox              | `box.delete()`                                          | `box.destroy()`                                             |

Upstash's synchronous Python client performs the same operations:

```python
from upstash_box import Box

box = Box.create(
    runtime="python",
    size="small",
    env={"PYTHONUNBUFFERED": "1"},
)

try:
    box.files.write(path="main.py", content="print(21 * 2)")

    run = box.exec.command("timeout 60 python3 main.py")
    print(run.result)
    print("exit code", run.exit_code)
finally:
    box.delete()
```

Save the Vercel version as `sandbox_example.py` in your linked project directory:

```python
import asyncio

from dotenv import load_dotenv
from vercel import sandbox
from vercel.sandbox import SandboxResources


load_dotenv(".env.local")


async def main() -> None:
    async with sandbox.create_sandbox(
        execution_time_limit=10 * 60,
        resources=SandboxResources(vcpus=2, memory=4096),
        env={"PYTHONUNBUFFERED": "1"},
        persistent=False,
    ) as box:
        await box.fs.write_text("main.py", "print(21 * 2)")

        result = await box.run_command(
            "python", ["main.py"], kill_after=60, capture_output=True
        )
        print(result.stdout.decode(), end="")
        print("exit code", result.returncode)


asyncio.run(main())
```

Run the script from your project directory to load `.env.local`:

```bash
python sandbox_example.py
```

The script prints `42` and `exit code 0`. Its `async with` block stops and destroys the Vercel sandbox on exit, matching the Upstash script's explicit `box.delete()`. Upstash's own `with box:` context manager only closes the SDK's HTTP client and leaves the box running.

To save the Vercel sandbox's files when the context manager exits, pass both `persistent=True` and `destroy=False` to `create_sandbox()`. Alternatively, await `create_sandbox()` directly and call `stop()` when work ends.

#### Commands, paths, and users

Box runs each `exec.command()` and `exec.stream()` string through `sh -c`. Vercel starts the binary directly, with its arguments in an array. Use `bash -c` for pipes, redirection, command chains, or variable expansion, and `bash -lc` when you need the login shell's profile. To replace `box.exec.code()`, write the snippet to a file and run its interpreter, or pass it to `python -c` or `node -e`.

Box's `box.cd()` sets the directory for later SDK calls. Vercel requires `cwd` on each command or absolute paths. Check paths in commands, prompts, and tool descriptions, because Box resolves relative paths from `/workspace/home` and Vercel managed images use `/vercel`.

Commands on Box run as the non-root `boxuser` and invoke `sudo` themselves. Vercel managed images use `ubuntu` or `arch` with passwordless sudo. Replace the command's `sudo` prefix with `sudo: true` in TypeScript or `sudo=True` in Python.

#### Command output and failures

Box's `run.result` contains stdout after a successful command. After a failure, it contains stderr, or stdout if stderr is empty. Read the streams separately on Vercel: `stdout()` and `stderr()` are asynchronous TypeScript methods. Python's `run_command()` streams output to your local stdout by default; pass `capture_output=True` to capture it as `bytes`.

Neither SDK throws for a non-zero exit code by default. Replace checks of Box's `run.status` with `exitCode` in Vercel's TypeScript SDK or `returncode` in Python. For Python code that should raise an exception, `check=True` raises `subprocess.CalledProcessError`.

#### Timeouts and session limits

Box's `timeout` limits the SDK request, so a command can keep running after the request gives up. Vercel Sandbox has no default command limit. Set `timeoutMs` in TypeScript or `kill_after` in Python to stop the command itself, and check the units when copying values:

| Setting                                                         | Unit                     |
| --------------------------------------------------------------- | ------------------------ |
| Box `timeout` in either SDK                                     | Milliseconds             |
| Box `EphemeralBox` TTL                                          | Seconds                  |
| Vercel TypeScript `timeout`, `timeoutMs`, and `extendTimeout()` | Milliseconds             |
| Vercel Python `execution_time_limit` and `kill_after`           | Seconds or a `timedelta` |

Standard boxes stay running until they have been idle for 1 hour on Free or 6 hours on paid plans. Vercel sessions end after 5 minutes by default. Set `timeout` in TypeScript or `execution_time_limit` in Python to cover the work, then extend it with `extendTimeout()` or `extend_execution_time_limit()` while work continues.

#### Background commands and streamed output

Box's `box.exec.stream()` maps to a detached command and its log stream. On Box, the stream yields output chunks while the command runs:

```javascript
const stream = await box.exec.stream(
  'for i in 1 2 3; do echo $i; sleep 1; done',
);

for await (const chunk of stream) {
  if (chunk.type === 'output') process.stdout.write(chunk.data);
}

console.log('exit code', stream.exitCode);
```

For foreground Vercel commands, set `stdout` to `process.stdout` and `stderr` to `process.stderr` to print output as it arrives. With `detached: true`, the call returns when the command starts so you can stream output through `command.logs()`:

```javascript
const command = await sandbox.runCommand({
  cmd: 'bash',
  args: ['-c', 'for i in 1 2 3; do echo $i; sleep 1; done'],
  detached: true,
});

for await (const line of command.logs()) {
  process.stdout.write(line.data);
}

const finished = await command.wait();
console.log('exit code', finished.exitCode);
```

In the Python SDK, `create_command()` starts a command without waiting for it:

```python
from anyio.streams.text import TextReceiveStream

process = await box.create_command(
    "bash", ["-c", "for i in 1 2 3; do echo $i; sleep 1; done"]
)
async for text in TextReceiveStream(process.stdout):
    print(text, end="")

returncode = await process.wait()
```

On Box, a long-running server starts through `initCommand` or a background shell command using `nohup` with output redirected to a log file. Start it as a detached command on Vercel, and start it again after each resume.

Store `command.cmdId` to reconnect with `sandbox.getCommand()` during the current session; that ID cannot reconnect to a process after a resume. Connections close after 340 seconds without data while the command keeps running. For these quiet jobs, use the [long-running task pattern](https://vercel.com/docs/sandbox/examples/execute-long-running-tasks).

### 6\. Replace pause and resume with named sandboxes

Use a named persistent sandbox in place of pausing a box and tracking its ID for each agent session.

#### Reconnect to a sandbox by name

On Upstash Box, your application pauses the box when an agent session ends, stores the box ID, and gets the box by that ID to continue. The excerpt assumes that `boxStore` is your application's persistent mapping of session IDs to box IDs, and that `box` and `sessionId` identify the current session.

```javascript
// End of an agent session
await box.files.write({ path: 'notes.txt', content: 'draft' });
await box.pause();
await boxStore.set(sessionId, box.id);

// Next agent session
const resumed = await Box.get(await boxStore.get(sessionId));
console.log(await resumed.files.read('notes.txt'));
```

Give the Vercel sandbox a name derived from the agent session. It saves files both when the session times out and when your code calls `stop()`, so this also replaces Box workloads that rely on idle auto-pause. Later file or command operations resume the sandbox from its saved state:

**Vercel Sandbox (TypeScript)**

```javascript
// End of an agent session
const sandbox = await Sandbox.getOrCreate({ name: `session-${sessionId}` });
await sandbox.writeFiles([
  { path: 'notes.txt', content: Buffer.from('draft') },
]);
await sandbox.stop();

// Next agent session
const resumed = await Sandbox.get({ name: `session-${sessionId}` });
const result = await resumed.runCommand('cat', ['notes.txt']);
console.log(await result.stdout());
```

**Vercel Sandbox (Python)**

```python
# End of an agent session
box, created = await sandbox.get_or_create_sandbox(name=f"session-{session_id}")
await box.fs.write_text("notes.txt", "draft")
await box.stop()

# Next agent session
box = await sandbox.get_sandbox(name=f"session-{session_id}")
print(await box.fs.read_text("notes.txt"))
```

The Vercel samples print `draft` after resuming the saved workspace in a new session with a new timeout. Store the sandbox name and provider in your application's session record so requests stay with the right provider throughout migration. Set the name at creation or use the generated name; it is unique within its project and cannot change.

#### Set retention and recover missing state

Each stop saves the persistent sandbox's files in a snapshot that counts toward Snapshot Storage. Use `persistent: false` or `persistent=False` for one-off work that doesn't need saved files. Vercel snapshots expire after 30 days without use by default; Upstash documents no expiry for a paused box. To match your retention policy, set `snapshotExpiration` in milliseconds or Python's `snapshot_expiration` in seconds, with `0` disabling expiry.

Choose how to handle a missing snapshot before accepting work:

| Lookup                                                   | Behavior when the saved snapshot is missing                                                           |
| -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| Python's `get_or_create_sandbox()`                       | Recreates the sandbox and returns `created=True`. Check that flag before relying on existing files.   |
| TypeScript's `Sandbox.getOrCreate()` with `resume: true` | Recreates the sandbox. Initialize or restore the replacement in `onCreate`.                           |
| Python's `get_sandbox()` or TypeScript's `Sandbox.get()` | Lets the resume fail instead of replacing the workspace. Handle the error before accepting more work. |

Deleting a sandbox preserves snapshots by default. To also delete snapshots that no other sandbox uses, enable `deleteOrphanSnapshots` in `sandbox.delete()` or `delete_orphan_snapshots` in Python's `box.destroy()`.

#### Restart processes after a resume

Box reruns `initCommand` each time its container starts, so a server started that way comes back after a resume:

```javascript
const box = await Box.create({
  runtime: 'python',
  initCommand: 'python3 -m http.server 8000',
});
```

Vercel Sandbox restores files on resume and has no init command, so restart the processes your application needs. Install dependencies once and keep them in the persistent filesystem. In the TypeScript SDK, request a resume and use lifecycle hooks to start the server:

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

const sessionId = 'your-session-id';

async function startServer(sandbox) {
  await sandbox.runCommand({
    cmd: 'python',
    args: ['-m', 'http.server', '8000'],
    detached: true,
  });
}

const sandbox = await Sandbox.getOrCreate({
  name: `session-${sessionId}`,
  ports: [8000],
  resume: true,
  onCreate: startServer,
  onResume: startServer,
});

// Check service readiness before sending application traffic.
```

`onCreate` starts the server for a new sandbox. With `resume: true`, an existing stopped sandbox resumes and `getOrCreate()` waits for `onResume` before returning. Check your service's readiness before sending traffic because the detached command can return before the server accepts connections.

The Python SDK has no resume hook. After lookup, check that the required processes are running and start them if needed. `get_sandbox()` only retrieves a handle; a command or filesystem operation resumes a stopped persistent sandbox. `get_or_create_sandbox()` resumes by default.

#### Start many sandboxes from one snapshot

On Box, `box.snapshot()` returns an object whose `id` you pass to `Box.fromSnapshot()`:

```javascript
const snapshot = await box.snapshot({ name: 'after-setup' });
const worker = await Box.fromSnapshot(snapshot.id);
```

To start many Vercel sandboxes from one prepared environment, take a snapshot and pass its ID as the `source`. The `git` source clones into a directory named after the repository, so the install command sets `cwd` to `your-repo`:

```javascript
const base = await Sandbox.create({
  name: 'base-environment',
  source: {
    type: 'git',
    url: 'https://github.com/your-org/your-repo.git',
    depth: 1,
  },
});
const install = await base.runCommand({
  cmd: 'npm',
  args: ['install'],
  cwd: 'your-repo',
});
if (install.exitCode !== 0) {
  const error = await install.stderr();
  await base.stop();
  throw new Error(error || `npm install exited with ${install.exitCode}`);
}

const snapshot = await base.snapshot();

const worker = await Sandbox.create({
  source: { type: 'snapshot', snapshotId: snapshot.snapshotId },
});
```

Taking `base.snapshot()` saves the files and ends the current session, so another command on `base` starts a new one. Both products restore files from snapshots; configure each worker as follows and start its processes after creation:

| Method                                             | Configuration and saved state                                                                                                                                                                                                                    |
| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Box's `Box.fromSnapshot()`                         | Pass the network policy, attached headers, init command, and size again; the restored box doesn't inherit them.                                                                                                                                  |
| Vercel's `Sandbox.create()` with a snapshot source | Pass resources, ports, and network policy with each creation call.                                                                                                                                                                               |
| Vercel's `Sandbox.fork()`                          | Set `sourceSandbox` to the source's name. The fork uses its latest snapshot and inherits configuration, including environment variables, but excludes Drive mounts. Stop or snapshot the source first to include changes from a running session. |

Create workers in the region where their snapshot is available. Configured [failover](https://vercel.com/docs/sandbox/concepts/regions#failover-regions) can load it elsewhere when Vercel cannot provision capacity in the main region.

In Python, await `create_sandbox()` directly for the base sandbox, because `async with` destroys it and its unused snapshots on exit. Pass `snapshot.id` to `SnapshotSource` through `snapshot_id` to create workers from that snapshot, or fork by name with `sandbox.fork_sandbox()`.

#### Replace ephemeral boxes with disposable sandboxes

On Box, `EphemeralBox` creates a box that Upstash deletes when its `ttl` ends:

```javascript
const box = await EphemeralBox.create({ runtime: 'node', ttl: 1800 });
```

On Vercel, set `persistent: false` to discard a sandbox's files when it stops:

```javascript
const sandbox = await Sandbox.create({
  persistent: false,
  timeout: 30 * 60 * 1000,
});
```

Box's `ttl` is in seconds and allows up to 3 days. Vercel's `timeout` is in milliseconds, and a session lasts up to 45 minutes on Hobby or 24 hours on Pro and Enterprise. In Python, pass `persistent=False` and the same number of seconds as `execution_time_limit`.

Call `sandbox.stop()` when the work ends instead of waiting for the timeout. For work that outlasts one session, use a persistent sandbox and resume it.

#### Copy files from existing boxes and snapshots

Vercel Sandbox can't read a box or a Box snapshot, so export the workspace as an archive first. Stop application writers and schedules, and prevent `initCommand` from restarting a writer when the export resumes a paused box. To export a snapshot, create a box with `Box.fromSnapshot()`, run the same export, and delete that temporary box afterward.

This script archives `/workspace/home` and refuses to reuse an existing `box-export` directory locally or in the box. Preserve or rename any existing directory before running it, and replace `your_box_id_here` with the source box ID:

```javascript
import { mkdir } from 'node:fs/promises';
import { Box } from '@upstash/box';

const box = await Box.get('your_box_id_here');

await mkdir('box-export');
await box.files.mkdir('box-export');

const pack = await box.exec.command([
  'tar -czf /workspace/home/box-export/workspace.tgz',
  '--exclude=./box-export -C /workspace/home .',
].join(' '));
if (pack.exitCode !== 0) throw new Error(pack.stderr || pack.result);

await box.files.download({ folder: 'box-export' });
await box.files.remove('box-export', { recursive: true });
```

Save the script as `export-box.mjs` and run it with `node export-box.mjs` while `UPSTASH_BOX_API_KEY` is set. It saves `box-export/workspace.tgz` locally, then removes only the temporary export directory it created in the box. The archive lives inside `/workspace/home`, where Box's file API can reach it. Archiving preserves nested files that `files.download()` would skip when copying the folder's immediate contents into a local directory of the same name.

The workspace archive includes Box's agent directories, such as `.claude`, `.codex`, `.cursor`, and `.local`. Point `-C` at a project subdirectory to exclude them or to export a large workspace one project at a time. Tools installed under `/home/boxuser` remain outside the archive and need reinstalling; rebuild system packages as described in step 4.

#### Import the archive into Vercel

Install the [Sandbox CLI](https://vercel.com/docs/sandbox/sdk/cli) for the file transfer. The yarn command requires Yarn Classic; choose the npm command if you use modern Yarn:

**pnpm**

```bash
pnpm add --global sandbox
```

**yarn**

```bash
yarn global add sandbox
```

**npm**

```bash
npm install --global sandbox
```

**bun**

```bash
bun add --global sandbox
```

Save the import sequence as a Bash script and run it from the linked project directory, or select a project with `--project` and `--scope`. Keep `set -e` at the start so a failed copy or extraction stops the import before later commands can hide the failure. Retain the source archive until the imported files pass verification.

Before importing, configure `sandbox create` with the image, resources, public ports, and network policy your application needs. Set retention for the expected idle period, or use `--snapshot-expiration none` to keep saved files indefinitely. With a custom image, extract into its working directory.

```bash
set -e

sandbox create --name session-123 --timeout 30m
sandbox copy ./box-export/workspace.tgz session-123:/vercel/workspace.tgz
sandbox exec session-123 -- tar -xzf /vercel/workspace.tgz -C /vercel
sandbox stop session-123
```

`Sandbox.getOrCreate()` ignores creation options when the named sandbox already exists, so configure the imported sandbox at creation. Use `sandbox.update()` afterward only for settings the SDK allows you to change.

### 7\. Replace Box Git helpers with a Git source and Git commands

Vercel Sandbox has no equivalent to the `box.git` helpers. Clone the repository with a `git` source when you create the sandbox, then run `git` with `runCommand()`.

Box's Git helpers clone the repository and read its state. They use the token in `git` or the GitHub connection saved in the Upstash Console:

```javascript
const box = await Box.create({
  runtime: 'node',
  git: { token: process.env.GITHUB_TOKEN },
});

await box.git.clone({
  repo: 'https://github.com/your-org/your-repo',
  branch: 'main',
});
await box.cd('your-repo');
console.log(await box.git.status());
```

Set the Vercel source's `password` to the token and each Git command's `cwd` to the repository directory:

**Vercel Sandbox (TypeScript)**

```javascript
const sandbox = await Sandbox.create({
  source: {
    type: 'git',
    url: 'https://github.com/your-org/your-repo.git',
    username: 'x-access-token',
    password: process.env.GITHUB_TOKEN,
    revision: 'main',
    depth: 1,
  },
});

const status = await sandbox.runCommand({
  cmd: 'git',
  args: ['status'],
  cwd: 'your-repo',
});
console.log(await status.stdout());
```

**Vercel Sandbox (Python)**

```python
import os

from vercel.sandbox import GitSource

box = await sandbox.create_sandbox(
    source=GitSource(
        url="https://github.com/your-org/your-repo.git",
        username="x-access-token",
        password=os.environ["GITHUB_TOKEN"],
        revision="main",
        depth=1,
    )
)

status = await box.run_command(
    "git", ["status"], cwd="your-repo", capture_output=True
)
print(status.stdout.decode(), end="")
```

Both Vercel samples print the repository's `git status` output. The repository is cloned into a directory named after it, so each command sets `cwd` to that directory. For a private GitHub repository, use `x-access-token` as the username and a token as the password; omit both for a public repository. Create a GitHub token if your boxes currently rely on the Console's GitHub connection.

Run the corresponding Git command through the object form of `runCommand()` shown above. Set `cmd` to `git`, supply the arguments in `args`, and select the repository directory with `cwd`:

| Box helper                                       | On Vercel Sandbox                                                                                |
| ------------------------------------------------ | ------------------------------------------------------------------------------------------------ |
| `box.git.clone()`                                | Use a `git` source at creation, or run `git clone` with the repository URL in a running sandbox. |
| `box.git.status()` and `box.git.diff()`          | Run `git status` and `git diff HEAD`.                                                            |
| `box.git.checkout()`                             | Run `git checkout` with the branch name.                                                         |
| `box.git.commit()`                               | Stage changes with `git add`, then run `git commit -m` with the message.                         |
| `box.git.push()`                                 | Run `git push` with a token passed through the command's `env`.                                  |
| `box.git.exec()`                                 | Pass its arguments to `runCommand()` with `git` as the binary.                                   |
| `box.git.updateConfig()`                         | Run `git config user.name` and `git config user.email` with the corresponding values.            |
| `box.git.createPR()` and `box.git.createIssue()` | Call the GitHub API from your backend.                                                           |

#### Commit and push changes

Before committing, set `user.name` and `user.email` with `git config`. Box supplies Upstash Box as the identity unless you set `userName` and `userEmail`. Its `git.push()` also defaults to a branch named after the box ID. Name your intended destination branch explicitly in the Vercel push command.

Box reuses its `git.token` or Console GitHub connection for cloning, pushing, and pull requests. For a Vercel push, pass a token with write access through `env` and keep it out of command arguments. The command pushes the current commit to `fix/empty-state`; substitute your organization, repository, and branch:

```javascript
await sandbox.runCommand({
  cmd: 'bash',
  args: [
    '-c',
    'git push "https://x-access-token:${GITHUB_TOKEN}@github.com/' +
      'your-org/your-repo.git" HEAD:refs/heads/fix/empty-state',
  ],
  cwd: 'your-repo',
  env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN },
});
```

Bash expands `${GITHUB_TOKEN}` from the command's environment, so the token doesn't appear in the stored arguments. Code in the sandbox can read it while the command runs; use a token limited to that repository. After the push, replace `box.git.createPR()` with a GitHub API request from your backend so the pull request credential stays outside the sandbox.

### 8\. Replace Box public URLs with public ports

Replace `box.getPublicURL()` or `box.get_public_url()` with the Vercel port URL. Expose the port through `ports`, then read its URL with `sandbox.domain()` in TypeScript or the matching entry in Python's `box.routes`.

Vercel port URLs are public. Before exposing a replacement for a Box URL that uses `bearerToken` or `basicAuth`, add [authentication inside the sandbox server](#authenticated-public-urls).

```javascript
const box = await Box.create({ runtime: 'python' });

await box.exec.command(
  'nohup python3 -m http.server 8000 > server.log 2>&1 &',
);

const publicUrl = await box.getPublicURL(8000);
console.log(publicUrl.url);
```

On Vercel, list the port at creation, start the server as a detached command, and read the port's URL:

```javascript
const sandbox = await Sandbox.create({ ports: [8000] });

await sandbox.runCommand({
  cmd: 'python',
  args: ['-m', 'http.server', '8000'],
  detached: true,
});

console.log(sandbox.domain(8000));
```

In the Python SDK, read the URL from `box.routes`:

```python
box = await sandbox.create_sandbox(ports=[8000])
url = next(route.url for route in box.routes if route.port == 8000)
```

Box creates a URL for a port on request and returns an object with a `url` property. Vercel's `domain()` returns a string. Declare up to 15 ports at creation, and replace the exposed list later by passing `ports` to `sandbox.update()`. Removing a port from that list replaces `box.deletePublicURL()`.

Requests to a paused box resume it and wait for the port to open. Requests to a stopped Vercel sandbox return HTTP 410 without resuming it. Before sending traffic, have your backend run a command to resume the sandbox, restart the server as shown in step 6, and check that it is ready.

### 9\. Replace Box network policies, environment variables, and attached headers

#### Map the network policy

Use Vercel's `networkPolicy` to replace each Box `networkPolicy` mode:

| Box policy                             | Vercel replacement              |
| -------------------------------------- | ------------------------------- |
| No policy, or `mode: 'allow-all'`      | Default `allow-all` policy      |
| `mode: 'deny-all'`                     | `deny-all` policy               |
| `mode: 'custom'` with `allowedDomains` | Domain entries in `allow`       |
| `mode: 'custom'` with `allowedCidrs`   | CIDR entries in `subnets.allow` |
| `deniedCidrs`                          | CIDR entries in `subnets.deny`  |

This Box policy allows three domain patterns and blocks other destinations:

```javascript
networkPolicy: {
  mode: 'custom',
  allowedDomains: ['api.openai.com', 'github.com', '*.github.com'],
}
```

Set the policy at creation or replace it with `update()`, which stands in for `box.updateNetworkPolicy()`. In Python, pass a `NetworkPolicy` instance as `network_policy`. Updates replace the policy in full:

**Vercel Sandbox (TypeScript)**

```javascript
const sandbox = await Sandbox.create({
  networkPolicy: {
    allow: ['api.openai.com', 'github.com', '*.github.com'],
  },
});

await sandbox.update({ networkPolicy: 'deny-all' });
```

**Vercel Sandbox (Python)**

```python
from vercel.sandbox import NetworkPolicy

box = await sandbox.create_sandbox(
    network_policy=NetworkPolicy.custom(
        allow={"api.openai.com": (), "github.com": (), "*.github.com": ()}
    ),
)

await box.update(network_policy=NetworkPolicy.deny_all())
```

For an IP range instead of domains, configure the subnet rules:

```javascript
networkPolicy: {
  subnets: { allow: ['203.0.113.0/24'] },
}
```

Both products deny destinations that a custom policy doesn't name. On both, `*.github.com` covers only subdomains, so add `github.com` to allow the main domain. Denied CIDR ranges also take precedence over allowed domains and ranges on both products.

Check two differences when you port a policy. Vercel matches domains on the TLS hostname, so plain HTTP requests need an IP-based rule or a switch to HTTPS. On Vercel, `deny-all` and a policy that contains only `subnets.deny` also block DNS.

#### Pass environment variables

Box's `env` option keeps its name on Vercel. Pass values from your application when creating the sandbox or running a command:

```javascript
const databaseUrl = process.env.DATABASE_URL;
const apiToken = process.env.API_TOKEN;
if (!databaseUrl || !apiToken) {
  throw new Error('DATABASE_URL and API_TOKEN are required');
}

const sandbox = await Sandbox.create({
  env: { DATABASE_URL: databaseUrl },
});

await sandbox.runCommand({
  cmd: 'python',
  args: ['sync.py'],
  env: { API_TOKEN: apiToken },
});
```

In the Python SDK, pass `env` to `create_sandbox()` or `run_command()`. Keep secrets out of command arguments, because Vercel Sandbox can store arguments and return them in command API responses.

Box also sets `UPSTASH_BOX_ID`, `UPSTASH_BOX_NAME`, and `UPSTASH_BOX_RUNTIME` inside each box, and `UPSTASH_BOX_AGENT` when an agent is configured. If code in the sandbox reads them, pass your own variables through `env`. Do the same for account-level variables that Box merges into every new box.

#### Broker credentials with firewall rules

Code in the sandbox can read every value in its environment. To keep a credential outside the sandbox, replace `attachHeaders` with a brokering rule that adds the header after the request leaves the sandbox. Credential brokering and the other Sandbox firewall features are available on Hobby, Pro, and Enterprise:

**Upstash Box (TypeScript)**

```javascript
const box = await Box.create({
  runtime: 'node',
  attachHeaders: {
    'api.example.com': {
      Authorization: `Bearer ${process.env.API_TOKEN}`,
    },
  },
});
```

**Vercel Sandbox (TypeScript)**

```javascript
const sandbox = await Sandbox.create({
  networkPolicy: {
    allow: {
      'api.example.com': [
        {
          transform: [
            { headers: { Authorization: `Bearer ${process.env.API_TOKEN}` } },
          ],
        },
      ],
      '*': [],
    },
  },
});
```

**Vercel Sandbox (Python)**

```python
import os

from vercel.sandbox import (
    NetworkPolicy,
    NetworkPolicyRule,
    NetworkPolicyTransform,
)

box = await sandbox.create_sandbox(
    network_policy=NetworkPolicy.custom(
        allow={
            "api.example.com": [
                NetworkPolicyRule(
                    transform=[
                        NetworkPolicyTransform(
                            headers={
                                "Authorization": (
                                    f"Bearer {os.environ['API_TOKEN']}"
                                )
                            }
                        )
                    ]
                )
            ],
            "*": [],
        }
    ),
)
```

The examples add the header to requests for `api.example.com` and leave other domains reachable. Remove the `'*'` entry to block domains the Vercel policy doesn't name. Box configures attached headers and network reachability separately; Vercel combines them in each domain's `allow` entry.

Box sets attached headers at creation and can't change them while the box runs. On Vercel, pass a complete `networkPolicy` to `sandbox.update()` to change rules on a running sandbox. Keep the policy you authored because Vercel redacts header values on readback. For shared headers that Box merges from the Upstash Console, read the values from your application's environment or secret manager when creating or updating the Vercel policy.

Box's attached header applies to every HTTPS request on port 443 to its host. To restrict which Vercel requests receive a credential, add a `match` for path, method, query string, or headers. The query matcher is `queryString` in TypeScript and `query` in Python. End the domain's rules with a `response` rule that returns 403 to reject the rest, using `statusCode` in TypeScript or `status_code` in Python.

### 10\. Verify and cut over

#### Validate workload behavior and resource use

Run both providers side by side before switching traffic:

- Compare output, exit codes, and written files for a representative workload.
  
- Measure peak CPU and memory on Vercel, then choose enough `vcpus` for that peak. Maximums are 4 vCPUs and 8 GB on Hobby, 8 vCPUs and 16 GB on Pro, and 32 vCPUs and 64 GB on Enterprise.
  
- Check concurrency and creation rate against the plan quotas. Hobby allows 10 concurrent sandboxes. Pro and Enterprise allow 10,000, with a vCPU allocation rate that starts at 150 vCPUs per minute and ramps to 5,000.
  
- Estimate usage with [Sandbox pricing](https://vercel.com/docs/sandbox/pricing). Vercel meters Active CPU, Provisioned Memory, Sandbox Creations, Data Transfer, and Snapshot Storage, plus Drive Storage, Drive Reads, and Drive Writes. Box has no separate memory charge. Vercel meters memory while a session waits for a model, so stop each sandbox when its work ends.
  

#### Move session state and switch traffic

If shared data must stay writable during cutover, plan replication between providers. Otherwise, stop writes during the final export and import.

1. Record which provider owns each existing session and keep its requests on that provider while you migrate its state.
   
2. Stop writes to the affected workspaces, export their Box files and snapshots using step 6, then import and verify them before routing sessions to Vercel.
   
3. Switch the flag for new sessions and monitor output and errors. Keep existing Box sessions on Upstash until they finish or their state has been imported. For scheduled jobs, pause the Box schedule and let its active run finish before activating the Vercel schedule.
   

#### Keep a rollback path until cleanup

To roll back, send new sessions to Upstash Box. Before returning a session that has written files on Vercel, copy and verify those changes on Upstash. Disable each migrated Vercel schedule before resuming its Box replacement, and retain both providers' state until the rollback period ends.

After that period, remove resources used only by the migrated workloads. Retain anything still needed by applications or jobs on Upstash Box:

- Remove unused Box calls and data, plus paused schedules replaced by Vercel.
  
- Delete unused keep-alive boxes, which Upstash bills for as long as they exist. Delete unneeded paused boxes and snapshots to stop their storage charges; deleting a box preserves its snapshots.
  
- Remove the SDK and revoke its API key only after every dependent application and job has migrated.
  

## What doesn't map from Upstash Box

These features need a different design on Vercel. Run the examples from the linked project directory with the latest Vercel and Sandbox CLIs.

### Built-in coding agents

Vercel Sandbox has no equivalent to the `agent` option, `box.agent.run()`, or `box.agent.stream()`. On Box, the platform runs Claude Code, Codex, OpenCode, or Cursor for each prompt and returns the result. On Vercel, your application starts the agent in a sandbox. Choose a replacement based on how you run the agent:

| On Upstash Box                                                | On Vercel Sandbox                                                                                                                                               |
| ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| An agent you prompt from your terminal                        | `sandbox create claude`, `sandbox create codex`, `sandbox create opencode`, or `sandbox create pi`, with Sandbox CLI 4.8.0 or later                             |
| `box.agent.run()` or `box.agent.stream()` in application code | AI SDK's [`HarnessAgent`](https://ai-sdk.dev/docs/ai-sdk-harnesses/harness-agent) with a harness adapter and a Vercel Sandbox session                           |
| Agent sessions that must survive a failed request             | [`durable-harness`](https://vercel.com/docs/agent-harnesses), which runs Claude Code or Codex in a sandbox for each session. `durable-harness` is experimental. |
| A custom agent set with `Agent.Custom`                        | Your agent's command, started with `runCommand()`                                                                                                               |

#### Run an agent from your terminal

The Sandbox CLI starts the agent in a new sandbox using the default image, which has the agents preinstalled:

```bash
sandbox create claude
```

The agent runs inside the sandbox, with its interactive interface in your local terminal. The CLI doesn't upload local project files automatically, and your Vercel login authenticates Sandbox access only. Sign in through the agent's own authentication flow or pass its API key with `--env`. Stop the sandbox after exiting the agent to end the running session.

#### Call an agent from application code

`HarnessAgent` provides one interface for [coding agents](https://vercel.com/docs/sandbox/ecosystem) such as Claude Code or Codex. Install the AI SDK harness packages and Vercel Sandbox adapter:

**pnpm**

```bash
pnpm add ai \
  @ai-sdk/harness \
  @ai-sdk/harness-claude-code \
  @ai-sdk/sandbox-vercel \
  @vercel/sandbox
```

**npm**

```bash
npm install ai \
  @ai-sdk/harness \
  @ai-sdk/harness-claude-code \
  @ai-sdk/sandbox-vercel \
  @vercel/sandbox
```

**yarn**

```bash
yarn add ai \
  @ai-sdk/harness \
  @ai-sdk/harness-claude-code \
  @ai-sdk/sandbox-vercel \
  @vercel/sandbox
```

**bun**

```bash
bun add ai \
  @ai-sdk/harness \
  @ai-sdk/harness-claude-code \
  @ai-sdk/sandbox-vercel \
  @vercel/sandbox
```

This Box call sends a prompt to Claude Code and prints the result:

```javascript
import { Agent, Box } from '@upstash/box';

const box = await Box.create({
  runtime: 'node',
  agent: {
    harness: Agent.ClaudeCode,
    model: 'anthropic/claude-sonnet-4-5',
    apiKey: process.env.ANTHROPIC_API_KEY,
  },
});

const run = await box.agent.run({
  prompt: 'Create a hello.txt file that contains a short greeting.',
});
console.log(run.result);
```

The Vercel version runs the same prompt through `HarnessAgent`. Box agents use your own provider key. Here, the Claude Code adapter uses the project's OIDC token to send model calls through [AI Gateway](https://vercel.com/docs/ai-gateway), so no Anthropic API key is needed:

```javascript
import { HarnessAgent } from '@ai-sdk/harness/agent';
import { createClaudeCode } from '@ai-sdk/harness-claude-code';
import { createVercelNetworkSandboxSession } from '@ai-sdk/sandbox-vercel';

const agent = new HarnessAgent({
  harness: createClaudeCode({ auth: 'ai-gateway' }),
  instructions: 'You are a careful coding assistant.',
});

const sandboxSession = await createVercelNetworkSandboxSession({
  image: 'vercel/sandbox/universal:latest',
  ports: [3000],
  template: await agent.getSandboxTemplate(),
});

try {
  const session = await agent.createSession({ sandboxSession });

  try {
    const result = await agent.generate({
      session,
      prompt: 'Create a hello.txt file that contains a short greeting.',
    });
    console.log(result.text);
  } finally {
    await session.destroy();
  }
} finally {
  await sandboxSession.destroy();
}
```

`getSandboxTemplate()` prepares the harness dependencies, and the exposed port connects your application to the harness bridge. Save the script as `run-agent.mjs` in the linked project, then run `node` with `--env-file=.env.local` and the script filename. It prints the agent's final message, then closes both sessions. For follow-up prompts, reuse the harness session as Box reuses its agent session, and destroy both sessions when the conversation ends.

| Box agent API        | Application change                                                                                      |
| -------------------- | ------------------------------------------------------------------------------------------------------- |
| `run.result`         | Read `result.text`.                                                                                     |
| `box.agent.stream()` | Call `agent.stream()` and read `text-delta` parts from `result.stream`.                                 |
| `responseSchema`     | Set `output` on `HarnessAgent` to `Output.object()` with its `schema` option, and read `result.output`. |
| Run-result `webhook` | Send the request from your application when the run finishes.                                           |

Pass skills through `HarnessAgent`'s `skills` setting as objects with a `name`, `description`, and `content`. Configure MCP servers through the harness adapter's `mcpServers` option, such as on `createClaudeCode()`. The agent's `tools` setting instead takes AI SDK tools executed by your application. The [triage application guide](https://vercel.com/kb/guide/sandboxed-coding-agent-with-harnessagent) develops this integration into a complete application.

### Box schedules

Vercel Sandbox has no equivalent to `box.schedule.exec()` or `box.schedule.agent()`. Run the work from a scheduled function that resumes a named sandbox. [Vercel Schedules](https://vercel.com/docs/schedules), which are in beta, invoke a private Vercel Function on a cron expression. If your application runs elsewhere, call the Sandbox SDK from its existing scheduler.

This Box schedule appends the date to a log file every hour:

```javascript
await box.schedule.exec({
  cron: '0 * * * *',
  command: ['bash', '-c', 'date >> /workspace/home/cron.log'],
});
```

On Vercel, install `@vercel/schedules`:

**pnpm**

```bash
pnpm i @vercel/schedules
```

**npm**

```bash
npm i @vercel/schedules
```

**yarn**

```bash
yarn add @vercel/schedules
```

**bun**

```bash
bun add @vercel/schedules
```

Save this function as `api/hourly.ts`. It resumes a named sandbox, runs the command, and stops the sandbox to save `cron.log` for the next run. Scheduled runs can arrive more than once, so make the command safe to repeat. To replace `box.schedule.agent()`, run the agent from the same function:

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

export const POST = handleSchedule(async () => {
  const sandbox = await Sandbox.getOrCreate({ name: 'scheduled-worker' });

  try {
    const result = await sandbox.runCommand({
      cmd: 'bash',
      args: ['-c', 'date >> cron.log'],
      timeoutMs: 60_000,
    });
    if (result.exitCode !== 0) {
      throw new Error(
        (await result.stderr()) ||
          `Scheduled command exited with ${result.exitCode}`,
      );
    }
  } finally {
    await sandbox.stop();
  }
});
```

Declare the schedule in `vercel.json`. Both providers use 5-field cron expressions in UTC by default; set `timezone` to use another timezone on Vercel:

```json
{
  "$schema": "https://openapi.vercel.sh/vercel.json",
  "functions": {
    "api/hourly.ts": {
      "experimentalTriggers": [{ "type": "schedule/v1beta" }]
    }
  },
  "schedules": {
    "hourly": {
      "schedule": "0 * * * *",
      "function": "api/hourly"
    }
  }
}
```

For jobs that exceed the function's maximum duration, follow the [long-running task pattern](https://vercel.com/docs/sandbox/examples/execute-long-running-tasks). Start the command with `detached: true`, set a session `timeout` that covers the job, and remove the `sandbox.stop()` call so the session ends at that timeout.

#### Test and activate the schedule

1. Test the function in a Preview deployment with test data. New Preview schedules start inactive, so enable the test schedule explicitly.
   
2. Before deploying to Production with `vercel deploy --prod`, pause the corresponding Box schedule and wait for its active run to finish. The Production deployment activates the Vercel schedule. Check its execution history after the first run, and keep the Box schedule paused throughout the rollback period.
   
3. If you roll back, disable the Vercel schedule before resuming the Box schedule and reconcile any writes completed on Vercel.
   

### Managed browser

Vercel Sandbox has no managed browser and no equivalent to `box.browser`. Choose a replacement based on what drives the browser:

- Install a browser in a custom image or snapshot when your code will drive it inside the sandbox through a Chrome DevTools Protocol (CDP) client.
  
- Connect your agent to a hosted cloud browser using the [browser agent guide](https://vercel.com/kb/guide/build-a-browser-agent).
  
- Use Vercel Labs' [screen-relay](https://vercel.com/docs/sandbox/examples/desktop-streaming) with Sandbox CLI 4.12.0 or later when a person or agent needs a Linux desktop with browser controls.
  

These commands start the desktop. The resulting viewer link contains a token that grants desktop viewing and control:

```bash
sandbox create --name desktop --timeout 30m -p 8080 \
  --image vercel-labs/screen-relay/sandbox-desktop:0.1.3
sandbox exec desktop -- screen-relay up -d --public $(sandbox domain desktop 8080)
```

Box's AI-powered tab methods, which are `tab.extract()`, `tab.observe()`, and `tab.act()`, have no equivalent. Call a model from your application for those steps. Keep browser workloads on Upstash Box until you replace their `box.browser` calls.

### Idle auto-pause and keep-alive boxes

Vercel Sandbox has no idle timeout and no keep-alive mode. Set a session timeout as an upper bound and stop the sandbox when work ends. For an interactive agent, track activity in your application and have a background worker stop inactive sessions after checking that no jobs are running.

While a session is still running, extend its deadline with the [Sandbox CLI](https://vercel.com/docs/sandbox/sdk/cli#sandbox-extend):

```bash
sandbox extend session-123 10m
```

Replace `session-123` with your sandbox's name. Extending adds time to the current session; it doesn't reset an idle timer or change the default timeout for later sessions. Use `extendTimeout()` and `stop()` from your application.

Keep-alive boxes run until you delete them. Vercel sessions last up to 45 minutes on Hobby or 24 hours on Pro and Enterprise, and Vercel Sandbox isn't designed to run continuously. For a service that must answer at any time, have your backend resume the sandbox, restart its server, and wait for a successful health check before sending traffic. Keep workloads that need an always-on process on a keep-alive box, or host that process outside the sandbox.

### Init commands and readiness checks

Box runs `initCommand` on creation and resume. Restoring a Box snapshot runs an init command only if you pass one to `Box.fromSnapshot()`. When a request wakes a paused box, the proxy holds it while the box resumes, then waits up to 30 more seconds for the port to open. If it stays closed, the request returns HTTP 503 with `Retry-After: 5`.

Vercel Sandbox has no `initCommand` and doesn't hold requests while a port opens. Start the process with a detached `runCommand()` after creation and each resume, as the [process restart example](#restart-processes-after-a-resume) shows. Keep dependencies in an image or snapshot to avoid installing them during startup.

#### Check that your service is ready

Sandbox creation waits until commands can run, but your server may still be starting. Save this Node.js helper as `wait-for-http.mjs` and use it to check a health URL that covers the service and its dependencies before forwarding traffic:

```javascript
import { setTimeout as delay } from 'node:timers/promises';

export async function waitForHttp(url, headers = {}) {
  for (let attempt = 0; attempt < 20; attempt++) {
    try {
      const response = await fetch(url, {
        headers,
        redirect: 'error',
        signal: AbortSignal.timeout(2_000),
      });
      const ready = response.ok;
      await response.body?.cancel();
      if (ready) return;
    } catch {
      // Retry while the service is starting.
    }
    await delay(500);
  }
  throw new Error('Service did not become ready');
}
```

The helper retries startup failures and throws if the service stays unavailable. The authenticated service below uses it with an authorization header. Run the check again after restarting a service on resume.

### Authenticated public URLs

Vercel port URLs are public. To replace Box's `bearerToken` option, check a per-sandbox bearer token in your server and send requests only from your trusted backend. The token authenticates outside callers, but code running inside the sandbox can still read it or change the server.

Save `server.mjs` and `call-protected-service.mjs` beside the [readiness helper](#init-commands-and-readiness-checks). Run the caller locally or on your backend. It creates a token, uploads the server to a sandbox, and sends an authenticated request before stopping it:

**server.mjs**

```javascript
import { createServer } from 'node:http';
import { timingSafeEqual } from 'node:crypto';

const token = process.env.SERVICE_TOKEN;
if (!token) throw new Error('SERVICE_TOKEN is required');
const expected = Buffer.from('Bearer ' + token);

createServer((request, response) => {
  const actual = Buffer.from(request.headers.authorization ?? '');
  if (
    actual.length !== expected.length ||
    !timingSafeEqual(actual, expected)
  ) {
    response.writeHead(401).end('Unauthorized');
    return;
  }
  response.writeHead(200, { 'Content-Type': 'application/json' });
  response.end(JSON.stringify({ ok: true }));
}).listen(3000, '0.0.0.0');
```

**call-protected-service.mjs**

```javascript
import { randomBytes } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { Sandbox } from '@vercel/sandbox';
import { waitForHttp } from './wait-for-http.mjs';

const token = randomBytes(32).toString('hex');
const sandbox = await Sandbox.create({
  ports: [3000],
  timeout: 5 * 60 * 1000,
  persistent: false,
});

try {
  await sandbox.writeFiles([{
    path: 'server.mjs',
    content: await readFile(new URL('./server.mjs', import.meta.url)),
  }]);
  await sandbox.runCommand({
    cmd: 'node',
    args: ['server.mjs'],
    env: { SERVICE_TOKEN: token },
    detached: true,
  });

  const url = sandbox.domain(3000);
  const headers = { Authorization: 'Bearer ' + token };
  await waitForHttp(url, headers);
  const response = await fetch(url, {
    headers,
    redirect: 'error',
    signal: AbortSignal.timeout(5_000),
  });
  if (!response.ok) throw new Error('Service request failed');
  console.log(await response.text());
} finally {
  await sandbox.stop();
}
```

Run the caller from that directory with the credentials saved in step 2:

```bash
node --env-file=.env.local call-protected-service.mjs
```

The caller prints `{"ok":true}` after a successful request, and the server returns HTTP 401 for missing or incorrect tokens. Your backend must authorize each user before calling the sandbox. Authenticated requests resume paused boxes, but a stopped Vercel sandbox returns HTTP 410. Have the backend resume it and restart the server, then wait for a successful health check before loading its URL.

Browsers cannot add this authorization header to a page load or iframe, so serve previews through an authenticated proxy that adds the token. Serve untrusted preview HTML from a separate origin that does not receive your application's session cookies, and restrict iframe permissions to those the preview needs.

### Other SDK features

These Box SDK features have a different interface on Vercel, or none:

| Box feature                             | On Vercel Sandbox                                                                                                                                                                                                                                                       |
| --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `box.exec.session()` live sessions      | `stdin: true` with `detached: true` in `runCommand()`, then `command.writeStdin()` and `command.kill()`. For a terminal, use `sandbox.openInteractive()` in the TypeScript SDK, which returns a WebSocket URL and token, or `box.open_interactive()` in the Python SDK. |
| SSH to a box                            | `sandbox connect` in the Sandbox CLI                                                                                                                                                                                                                                    |
| `box.exec.code()`                       | No equivalent. Write the code to a file and run it with `runCommand()`.                                                                                                                                                                                                 |
| `files.upload()` and `files.download()` | `writeFiles()` and `downloadFile()` in the TypeScript SDK, or `sandbox copy` in the Sandbox CLI, which copies directories with `--recursive`                                                                                                                            |
| `box.logs()` and `box.listRuns()`       | `box.query_commands()` in the Python SDK. The TypeScript SDK has no list call, so store each `cmdId`.                                                                                                                                                                   |
| `run.cost`                              | No per-command cost. `sandbox.stop()` returns the session's active CPU time and network transfer.                                                                                                                                                                       |
| Run and schedule webhooks               | [Sandbox lifecycle webhooks](https://vercel.com/docs/sandbox/lifecycle-webhooks) for session start, expiry warning, and stop events, on Pro and Enterprise. Send run results from your application.                                                                     |
| Read-only API keys                      | No equivalent. Keep Vercel credentials in your backend and expose read-only operations through it.                                                                                                                                                                      |
| `Box.setEnv()` account-level variables  | No equivalent. Pass shared values through `env` from your application.                                                                                                                                                                                                  |

## Troubleshooting

Use these checks to diagnose changes in workload behavior after migration.

| What you observe                                                                                                               | What to check                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| ------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Authentication fails locally after it worked earlier                                                                           | The development OIDC token expires after 12 hours. Run `vercel env pull` again.                                                                                                                                                                                                                                                                                                                                                                |
| `Sandbox.create()` returns `image_not_ready`                                                                                   | Vercel Container Registry is still preparing the image. Retry after the repository details page shows Ready, and confirm the image targets `linux/amd64`.                                                                                                                                                                                                                                                                                      |
| A command that was one string on Box fails to start, or pipes, redirection, and `$VARIABLES` reach the program as literal text | `runCommand()` doesn't use a shell. Pass the binary and an argument array, or wrap the command in `bash -c`.                                                                                                                                                                                                                                                                                                                                   |
| A sandbox stops in the middle of a task                                                                                        | A session ends 5 minutes after it starts by default, and Vercel Sandbox has no idle timeout. Set `timeout`, or call `extendTimeout()` while work continues.                                                                                                                                                                                                                                                                                    |
| A command or file write fails with a permission error                                                                          | Commands run as the image's default user, not as Box's `boxuser`. Write under `/vercel`, or pass `sudo: true`.                                                                                                                                                                                                                                                                                                                                 |
| Files or scripts aren't found under `/workspace/home`                                                                          | Managed images use `/vercel` as the home and working directory. Update absolute paths, or use relative paths.                                                                                                                                                                                                                                                                                                                                  |
| A command can't find the directory that `box.cd()` selected                                                                    | Vercel Sandbox has no working directory tracked in the SDK. Pass `cwd` to each command.                                                                                                                                                                                                                                                                                                                                                        |
| Files from a `git` source aren't in the working directory                                                                      | The `git` source clones the repository into a directory named after it. Pass that directory as `cwd`.                                                                                                                                                                                                                                                                                                                                          |
| Python output is `None`, or prints as `b'...'`                                                                                 | Pass `capture_output=True` to `run_command()`, then call `.decode()` on `stdout`.                                                                                                                                                                                                                                                                                                                                                              |
| A Python command runs far longer than its limit                                                                                | Box's Python SDK takes `timeout` options in milliseconds. Vercel's `kill_after` and `execution_time_limit` take seconds, so divide a value copied from a Box `timeout` by 1,000. Box's `ttl` is already in seconds, so pass it to `execution_time_limit` unchanged.                                                                                                                                                                            |
| Requests to a sandbox URL return HTTP 410                                                                                      | The sandbox is stopped, and HTTP requests don't resume it. Run a command to resume the sandbox, then restart your server.                                                                                                                                                                                                                                                                                                                      |
| A server that an `initCommand` started isn't running after a resume                                                            | Vercel restores files, not processes. Start the server in `onCreate` and `onResume`, as shown in step 6.                                                                                                                                                                                                                                                                                                                                       |
| The first call to a stopped sandbox fails with `snapshot_not_found`                                                            | Check whether the saved snapshot still exists. If it has expired, create a replacement sandbox and restore files from a backup. Changing retention cannot recover a deleted snapshot; configure it for future snapshots. Python's `get_or_create_sandbox()` and TypeScript's `getOrCreate()` with `resume: true` can recreate the workspace instead. Check `created` in Python or initialize it in `onCreate` in TypeScript before continuing. |
| Creation fails with `snapshot_region_mismatch` or `drive_region_mismatch`                                                      | Create the sandbox in the same region as its snapshot or Drive.                                                                                                                                                                                                                                                                                                                                                                                |
| A header that `attachHeaders` added is missing from requests                                                                   | Check that the domain has a `transform` rule in the policy's `allow` object, and that any `match` conditions cover the request.                                                                                                                                                                                                                                                                                                                |
| Requests to a domain that Box allowed are blocked                                                                              | A Vercel allow list blocks every destination that it doesn't name. Add the domain to the allow list. For plain HTTP requests, switch to HTTPS or allow the IP range.                                                                                                                                                                                                                                                                           |
| A long, quiet command loses its connection                                                                                     | Connections close after 340 seconds without data, and the command keeps running. Follow [Execute long-running tasks](https://vercel.com/docs/sandbox/examples/execute-long-running-tasks).                                                                                                                                                                                                                                                     |

## What to build with Vercel Sandbox

Use these patterns when adapting the workloads you moved from Upstash Box.

### AI code interpreter

With a code interpreter, a model can write Python or SQL, run it against a user's file, and return the result. Create one sandbox for each request with `persistent: false`, a short `timeout`, and `networkPolicy: 'deny-all'`. Upload the data with `writeFiles()`, then run the model's script with `runCommand()`.

[Add Python execution to a TypeScript agent](https://vercel.com/kb/guide/python-ai-sdk-vercel-sandbox), or read about [code interpreter design](https://vercel.com/i/code-interpreter).

### Coding agents that work on a repository

Coding agents use a Linux workspace to clone a repository, edit files, run checks, and return a branch or draft pull request. Clone a private repository with a `git` source, and install private packages with `credentials: { npm: true }`. With the Sandbox CLI, `sandbox create claude` or `sandbox create codex` starts a supported agent in a sandbox from your terminal.

Use [eve Software Factory](https://vercel.com/templates/eve/eve-software-factory) to turn issues into reviewed draft pull requests.

### App builders with live previews

An app builder gives each project a sandbox with a dev-server URL that your product loads in an iframe. Open the named sandbox with `Sandbox.getOrCreate()`, expose port 3000, and start the server as a detached command.

On later visits, have your backend resume the sandbox and restart the server before loading its preview URL. Extend the session while the user is active; requests to a stopped sandbox's URL do not resume it.

Build a [v0-style app builder](https://vercel.com/kb/guide/v0-clone-openai-agents-vercel-sandbox) with the OpenAI Agents API.

### Agents with persistent, shared workspaces

Long-running agents can keep files between conversations and share reference material with a team. Give each user or task a named sandbox, and keep team files on a Drive that each session mounts as a read-only snapshot.

The [eve with Vercel Drives template](https://vercel.com/templates/eve/eve-vercel-drives-starter) connects an agent in Slack or a terminal to shared team files. It saves new documents through a separate sandbox with write access. Follow the [eve and Drives setup](https://vercel.com/kb/guide/vercel-drives-eve-agent) to configure it.

### Customer code in a multi-tenant product

Use one sandbox per execution to run code written by your customers, third-party developers, or their agents. Start each job from a snapshot that holds its dependencies, and set `networkPolicy` to `'deny-all'` or an allow list. Broker credentials at the Sandbox firewall so customer code never holds them.

See [Notion Workers](https://vercel.com/customers/notion-workers-vercel-sandbox) for a production example of running untrusted code, or [add isolated Python execution](https://vercel.com/kb/guide/python-and-vercel-sandbox) to your own app.

## Next steps

- Configure [session timeouts and persistent files](https://vercel.com/docs/sandbox/concepts/persistent-sandboxes)
  
- Restrict egress and broker credentials with the [Sandbox firewall](https://vercel.com/docs/sandbox/concepts/firewall)
  
- Build custom images with [Vercel Container Registry](https://vercel.com/docs/container-registry)
  
- Mount persistent storage with [Drives](https://vercel.com/docs/sandbox/concepts/drives)
  
- Run agent evals with [Harbor and Terminal-Bench](https://vercel.com/docs/sandbox/ecosystem/harbor)
  
- Estimate your bill with [Sandbox pricing and quotas](https://vercel.com/docs/sandbox/pricing)
  
- Compare [Vercel Sandbox and Upstash Box](https://vercel.com/kb/guide/vercel-sandbox-vs-upstash-box) for your workload
  

## Frequently asked questions

### Can I move Upstash Box files or snapshots to Vercel Sandbox directly?

No. Archive the files in a box, or in a box created from the snapshot, and download the archive. Use `sandbox copy` to transfer the archive to Vercel, then extract it into the sandbox's workspace. Running processes don't transfer.

### Can my application stay on its current host after I migrate to Vercel Sandbox?

Yes. The Vercel Sandbox SDKs work from any backend with an access token, a team ID, and a project ID. Applications deployed on Vercel authenticate with the project's OIDC token instead.

### Can I keep some workloads on Upstash Box and move the rest to Vercel Sandbox?

Yes. The `@upstash/box` and Vercel Sandbox SDKs are independent, so one application can call both. For example, move code execution to Vercel Sandbox, and keep always-on services on keep-alive boxes.

### Do I need a custom image to replace an Upstash Box runtime?

Not for Node.js or Python, which Vercel's managed images include. For Go, Ruby, or Rust, install the toolchain and save it in a snapshot, or build a custom image into Vercel Container Registry with `vercel vcr build`. Build a custom image if you need to preserve a version that the managed images don't provide.

### Can I migrate Upstash Box Python code without switching to TypeScript?

Yes. The `vercel-sandbox` package supports Python 3.11 or later with asynchronous and synchronous APIs. Some names differ from Upstash's Python SDK, for example `run_command()` instead of `exec.command()`.

### Does Vercel Sandbox pause idle sandboxes the way Upstash Box does?

No. Vercel sessions end at their timeout or when your code calls `stop()`. While work continues, call `extendTimeout()` or Python's `extend_execution_time_limit()`. Persistent sandboxes save their files in either case.

### Does Vercel Sandbox resume a stopped sandbox automatically?

Yes, for SDK operations. A command or file operation resumes a stopped persistent sandbox without any lifecycle setting. HTTP requests to a port URL don't resume it, so they return HTTP 410 until your code resumes the sandbox.

### Do processes keep running when a Vercel sandbox stops and resumes?

No. Vercel Sandbox restores files, not processes, and it has no `initCommand` to restart them. In the TypeScript SDK, restart servers and background jobs in the `onResume` hook, which runs each time a session resumes. In Python, check that the required processes are running after lookup and start them if needed.

### Is there a Vercel Sandbox equivalent to box.agent.run() on Upstash Box?

Not in the Sandbox SDK. Run the coding agent in a sandbox from your application, for example with AI SDK's `HarnessAgent`, or start one from your terminal with `sandbox create claude`.

### Do commands run as the same user in Vercel Sandbox as they do on Upstash Box?

Box runs commands as `boxuser` in `/workspace/home`, while Vercel managed images use `ubuntu` or `arch` in `/vercel` with passwordless sudo. For root access, pass `sudo: true` to `runCommand()`, or `sudo=True` to `run_command()`.

## Related Resources

- [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.

## More Vercel Sandbox guides

- [Migrate from Freestyle VMs to Vercel Sandbox](/kb/guide/migrate-from-freestyle-vms-to-vercel-sandbox): Move Freestyle VM code to Vercel Sandbox in TypeScript, from snapshots and pauses to lifecycle fields, firewall rules, credential brokering, and a staged cutover.
- [Migrate from Cloudflare Sandbox to Vercel Sandbox](/kb/guide/migrate-from-cloudflare-sandbox-to-vercel-sandbox): Move Cloudflare Sandbox code to Vercel Sandbox in TypeScript or Python, from images and snapshots to Drives, network policies, preview ports, and a staged cutover.
- [Run research agents, data analysis, and evals on Vercel Sandbox](/kb/guide/sandbox-research-workloads): Give a research agent a Python execution tool, analyze datasets, fork parallel trials from one baseline, restrict network access, and resume a workspace across sessions.

## 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>
```
