---
title: Migrate from Cloudflare Sandbox to Vercel Sandbox
description: 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.
keywords: ["Vercel Sandbox","Cloudflare Sandbox","migrate from Cloudflare","AI agent sandbox","sandbox migration","Durable Objects"]
url: "https://vercel.com/kb/guide/migrate-from-cloudflare-sandbox-to-vercel-sandbox"
published: 2026-12-01
last_updated: 2026-12-01
authors: Ben Sabic
related_resources:
  - title: "Vercel Sandbox vs Cloudflare Sandbox"
    url: "/kb/guide/vercel-sandbox-vs-cloudflare-sandbox"
    description: "Compare Vercel Sandbox and Cloudflare Sandbox as AI agent sandboxes, including isolation, persistence, network controls, SDKs, and deployment options."
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-cloudflare-sandbox-to-vercel-sandbox"
---

To move sandbox workloads from [Cloudflare Sandbox](https://developers.cloudflare.com/sandbox/) to [Vercel Sandbox](https://vercel.com/docs/sandbox), replace the container calls in your Durable Object with SDK calls from a Node.js or Python backend. The migration also involves adapting image setup, file persistence, egress rules, and preview routing to preserve the behavior your application needs.

On Cloudflare, a stopped instance loses its disk, so files survive only in a snapshot your code took, a directory backup in R2, or a mounted bucket. Vercel preserves files when a persistent sandbox stops, but your application must restart its processes when it resumes the sandbox by name. Review the [migration limitations](#what-doesn%27t-map-from-cloudflare-sandbox) before starting, especially if your application also relies on fractional-vCPU instances, inactivity timeouts, or state in Durable Object storage.

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 Cloudflare Sandbox is used and prepare the migration:

### Agent prompt

```txt
Migrate this codebase from Cloudflare Sandbox to Vercel Sandbox.

1. Read and follow the migration guide using the Vercel CLI: `npx vercel@latest kb inspect migrate-from-cloudflare-sandbox-to-vercel-sandbox`.
2. Inventory Cloudflare Sandbox usage, including Durable Object classes that call `ctx.container`, the Worker routes that reach them, `@cloudflare/sandbox` imports, Sandbox SDK 0.x calls such as `getSandbox()`, Wrangler container settings, images, commands, files, snapshots, R2 backups and mounts, preview routes, outbound handlers, secrets, and instance sizes. Preserve the application's authorization checks.
3. Identify features that need a different design, including fractional-vCPU instances, inactivity timeouts, keep-alive alarms, outbound handlers that run custom code, preview authentication in the Worker, raw TCP, state in Durable Object storage, and mounted R2 buckets. 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 Cloudflare path available until I approve cutover.
5. Port one call site at a time. Check units, paths, users, shell use, environment variables, network defaults, 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, release writable mounts, and reconcile changes if we roll back. Do not delete Cloudflare data, Workers, or Durable Object classes, and do not revoke credentials.
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 Cloudflare Sandbox features map to Vercel Sandbox

Move container calls from your Durable Object class into a backend that authenticates to a Vercel project. Drives can replace R2 directory backups and bucket mounts, while fractional-vCPU instances and inactivity timeouts require a [different approach](#what-doesn%27t-map-from-cloudflare-sandbox). For the workload tradeoffs behind these changes, [compare Vercel Sandbox and Cloudflare Sandbox](https://vercel.com/kb/guide/vercel-sandbox-vs-cloudflare-sandbox).

The mappings use the names from Cloudflare's [Sandbox SDK 1.0](https://developers.cloudflare.com/sandbox/sdk/migrate/changes-in-1-0/), where your Durable Object controls the container through the [Durable Object Container API](https://developers.cloudflare.com/containers/api/durable-object-container/) on `this.ctx.container`, and TypeScript names for Vercel. [Step 5](#5.-replace-container-calls-with-vercel-sandbox-sdk-calls) also lists the Sandbox SDK 0.x calls, such as `getSandbox()` and `sandbox.exec()`. Cloudflare [ends bug and security fixes for Sandbox SDK 0.x](https://developers.cloudflare.com/sandbox/sdk/migrate/) on December 31, 2026, and you can migrate from either version without moving to 1.0 first.

### Projects, images, and compute

Replace the Durable Object class and its container configuration with a Vercel project, and select an image.

| Cloudflare Sandbox                                                                                                                                                             | Vercel Sandbox                                                                                                                             | What you change                                                                                                                                                    |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Durable Object class with a `containers` entry in your Wrangler configuration                                                                                                  | Vercel project                                                                                                                             | Move the container calls out of the class. Each sandbox belongs to the project that issued its credentials.                                                        |
| Durable Object binding, reached through Worker routes that you write                                                                                                           | [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. Keep the checks that authenticate your own callers.                                                 |
| Managed `cloudflare/debian-trixie` image, or a Dockerfile listed under `images`                                                                                                | [Managed image](https://vercel.com/docs/sandbox/concepts/images), or a custom OCI image in Vercel Container Registry                       | Build custom images from the same Dockerfile. Vercel Sandbox doesn't run an image's `ENTRYPOINT` or `CMD`.                                                         |
| `entrypoint` passed to `start()`                                                                                                                                               | `runCommand()` with `detached: true`                                                                                                       | Start the process after creation. Remove `sleep infinity` entrypoints, because a Vercel sandbox runs until its session ends.                                       |
| `instance` in `start()`, from `lite` (1/16 vCPU, 256 MiB) to `standard-4` (4 vCPUs, 12 GiB), or a [custom size](https://developers.cloudflare.com/containers/platform/limits/) | `resources.vcpus`, with 2 GB of memory per vCPU                                                                                            | The smallest Vercel sandbox has 1 vCPU and 2 GB. Choose a size that covers both CPU and memory. See [instance sizes](#fractional-vcpu-and-memory-heavy-instances). |
| Disk set by the instance type, from 2 GB to 20 GB                                                                                                                              | 64 GB of local disk                                                                                                                        | No setting to port. Use a [Drive](https://vercel.com/docs/sandbox/concepts/drives) for data larger than the local disk.                                            |
| Placement chosen by Cloudflare, with an optional `jurisdiction` on the Durable Object namespace                                                                                | `region`, with one of [19 region IDs](https://vercel.com/docs/sandbox/concepts/regions) such as `iad1`                                     | Choose the region for each sandbox, or set a project default. Snapshots and Drives stay in the region that created them.                                           |
| In a deployed container, every process has [root's Linux capabilities](https://developers.cloudflare.com/sandbox/concepts/security/)                                           | Commands run as the image's default user, which is `ubuntu` or `arch` on managed images                                                    | Pass `sudo: true` to `runCommand()` for commands that need root.                                                                                                   |

### Lifecycle and state

Vercel sandboxes are persistent by default, which replaces the snapshot IDs and backup records that a Cloudflare application keeps in Durable Object storage.

| Cloudflare Sandbox                                                                                                       | Vercel Sandbox                                                                    | What you change                                                                                                                                                                                 |
| ------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`setInactivityTimeout()`](https://developers.cloudflare.com/sandbox/concepts/lifetime/), in milliseconds, up to 6 hours | `timeout` in the TypeScript SDK, or `execution_time_limit` in the Python SDK      | Vercel Sandbox has no inactivity timeout, so stop the sandbox from your code.                                                                                                                   |
| No fixed maximum runtime while the Durable Object stays active                                                           | Session of up to 45 minutes on Hobby, or 24 hours on Pro and Enterprise           | A persistent sandbox spans many sessions. Extend a running session with `extendTimeout()`.                                                                                                      |
| Durable Object alarm that keeps an instance running during long work                                                     | No equivalent needed                                                              | Work inside a Vercel sandbox continues until the session timeout. Remove the alarm and set a timeout that covers the job.                                                                       |
| `destroy()`, which discards the disk                                                                                     | `sandbox.stop()`, which saves the filesystem, or `sandbox.delete()`               | Pass `persistent: false` for disposable sandboxes.                                                                                                                                              |
| `snapshotContainer()`, in public beta, with the snapshot `id` kept in Durable Object storage                             | Automatic snapshot on stop, or a manual `sandbox.snapshot()`                      | Reconnect by sandbox name. Store a snapshot ID only to seed new sandboxes.                                                                                                                      |
| `env.MY_CONTAINER.getByName(name)`                                                                                       | `Sandbox.get({ name })` or `Sandbox.getOrCreate({ name })`                        | Look up sandboxes by name. The next command resumes a stopped sandbox.                                                                                                                          |
| Several instances started with one `containerSnapshot`                                                                   | `source: { type: 'snapshot', snapshotId }`, or `Sandbox.fork()`                   | A fork starts from the source sandbox's latest saved snapshot.                                                                                                                                  |
| Entrypoint that runs again when an instance starts from a snapshot                                                       | No equivalent                                                                     | After each resume, restart processes, for example with the TypeScript SDK's `onResume` hook.                                                                                                    |
| [`DirectoryBackup`](https://developers.cloudflare.com/sandbox/files/) archives in R2                                     | Persistent sandbox, or a [Drive](https://vercel.com/docs/sandbox/concepts/drives) | A named sandbox keeps its own workspace. Use a Drive for files that several sandboxes share.                                                                                                    |
| `S3Mount` for an R2 bucket or another S3-compatible bucket                                                               | No equivalent for mounting a bucket                                               | Move the files to a [Drive](https://vercel.com/docs/sandbox/concepts/drives) when sandboxes are their only readers and writers. Otherwise, see [bucket migration options](#mounted-r2-buckets). |
| Session records, share tokens, and alarms in Durable Object storage                                                      | No equivalent                                                                     | Keep this state in your application's database. See [state in Durable Object storage](#state-in-durable-object-storage).                                                                        |
| Up to 10 `labels`                                                                                                        | Up to five `tags`                                                                 | Reduce the label set, or put extra metadata in the sandbox name.                                                                                                                                |

### Networking and secrets

Replace `enableInternet` and handlers that allow hosts or add credentials with a firewall `networkPolicy`, then move Worker preview routes to public port URLs.

| Cloudflare Sandbox                                                                                                                                                            | Vercel Sandbox                                                                                          | What you change                                                                                                 |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `getTcpPort(port).fetch(request)` behind a [Worker route](https://developers.cloudflare.com/sandbox/previews/)                                                                | `ports` and `sandbox.domain(port)`                                                                      | List up to 15 ports at creation. Anyone with a port's URL can reach it.                                         |
| Preview authentication and share tokens in your Worker                                                                                                                        | No equivalent                                                                                           | Authenticate callers in the server that runs inside the sandbox.                                                |
| `enableInternet: false` with no intercepts, the 1.0 default                                                                                                                   | `networkPolicy: 'deny-all'`                                                                             | Vercel's default is `allow-all`, so set the policy at creation. `deny-all` also blocks DNS.                     |
| `enableInternet: true`                                                                                                                                                        | `networkPolicy: 'allow-all'`, the default                                                               | No change.                                                                                                      |
| `interceptOutboundHttps()` for a hostname, with an [outbound handler](https://developers.cloudflare.com/containers/configuration/outbound-traffic/) that forwards the request | `networkPolicy: { allow: [...] }`                                                                       | A Vercel wildcard replaces a whole DNS label, so rewrite patterns such as `api*.example.com`.                   |
| `interceptOutboundHttp()` for a hostname, an IP address, or a CIDR range                                                                                                      | `networkPolicy: { subnets: { allow: [...] } }`                                                          | Vercel can't filter plain HTTP by domain. Move the client to HTTPS, or allow the address range.                 |
| Registering a target again to replace its handler                                                                                                                             | `sandbox.update({ networkPolicy })`                                                                     | Each update replaces the whole policy, so an update can also remove a domain.                                   |
| Handler that adds a credential from the Worker's `env`                                                                                                                        | [Brokering rules](https://vercel.com/docs/sandbox/concepts/firewall) with `transform`                   | Rules match on path, method, query, and headers, and work together with an allow list.                          |
| Handler that runs other code, such as rewriting requests or reading a binding                                                                                                 | Forwarding rules with `forwardURL`                                                                      | Move the code to a proxy that you run. See [outbound handlers that run code](#outbound-handlers-that-run-code). |
| Worker secrets passed through `env` in `start()` or `exec()`                                                                                                                  | `env`, at creation or for each command                                                                  | Read the values in your application and pass them in.                                                           |
| Per-container CA certificate that your entrypoint adds to the trust store                                                                                                     | Per-sandbox CA, added to the system certificates automatically                                          | Remove the entrypoint steps and environment variables that trust Cloudflare's CA.                               |
| Private services reached through Workers bindings in a handler                                                                                                                | [Secure Compute](https://vercel.com/docs/sandbox/concepts/secure-compute) network, set with `networkId` | Secure Compute is an additional Enterprise purchase.                                                            |

## Steps

### 1\. Find where your application uses Cloudflare Sandbox

Search for the container API, the `@cloudflare/sandbox` package, and Sandbox SDK 0.x calls, then trace aliases through your code:

```bash
grep -rnE \
  -e 'ctx\.container|@cloudflare/(sandbox|containers)' \
  -e 'cloudflare/sandbox|getSandbox|proxyToSandbox' \
  -e 'snapshotContainer|setInactivityTimeout|getTcpPort' \
  -e 'intercept(All)?Outbound|enableInternet' \
  -e 'DirectoryBackup|S3Mount|sandbox-shim|debian-trixie' \
  -e '\[\[containers\]\]|"containers"' \
  --include="*.ts" --include="*.tsx" \
  --include="*.js" --include="*.mjs" \
  --include="*.json" --include="*.jsonc" --include="*.toml" \
  --include="Dockerfile*" \
  --exclude-dir=node_modules --exclude-dir=.wrangler .
```

Match what you find to the steps that follow:

| In your code                                                                                                                                              | Go to                                                                                   |
| --------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| A `containers` entry or `images` in your Wrangler configuration, a `Dockerfile`, or `sandbox-shim`                                                        | [Step 4](#4.-move-your-container-image-to-a-vercel-image)                               |
| `container.start()`, `container.exec()`, `Files`, or Sandbox SDK 0.x calls such as `getSandbox()` and `sandbox.exec()`                                    | [Step 5](#5.-replace-container-calls-with-vercel-sandbox-sdk-calls)                     |
| `snapshotContainer()`, `containerSnapshot`, or `getByName()`                                                                                              | [Step 6](#6.-replace-snapshot-handles-with-named-sandboxes)                             |
| `DirectoryBackup`, `S3Mount`, or Sandbox SDK 0.x `createBackup()` and `mountBucket()`                                                                     | [Step 7](#7.-move-r2-backups-and-bucket-mounts-to-drives)                               |
| `getTcpPort()`, preview routes, or Sandbox SDK 0.x `exposePort()` and `proxyToSandbox()`                                                                  | [Step 8](#8.-replace-worker-preview-routes-with-public-ports)                           |
| `enableInternet`, `interceptOutboundHttp()`, `interceptOutboundHttps()`, `interceptAllOutboundHttp()`, or `env`                                           | [Step 9](#9.-replace-outbound-handlers-and-secrets-with-a-network-policy)               |
| A fractional `instance`, `setInactivityTimeout()`, a keep-alive alarm, a handler that runs custom code, preview authentication, or Durable Object storage | [What doesn't map from Cloudflare Sandbox](#what-doesn%27t-map-from-cloudflare-sandbox) |

### 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 your Worker, its Durable Object bindings, and its secrets until the migrated workloads pass verification. Retain any that workloads remaining on Cloudflare use.

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

**uv**

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

**pip**

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

Keep the `@cloudflare/sandbox` package and Wrangler until no workloads use them.

### 4\. Move your container image to a Vercel image

Replace your Cloudflare image with a Vercel [managed image](https://vercel.com/docs/sandbox/concepts/images) or a custom image in Vercel Container Registry. Choose based on the source image:

| Cloudflare image                                                     | Vercel replacement                                                                                                                                                    |
| -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `cloudflare/debian-trixie`, the managed Debian image with Node.js 24 | 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. |
| A `dockerfile` entry under `images` in your Wrangler configuration   | The same Dockerfile, built into Vercel Container Registry                                                                                                             |
| A digest-pinned image in Cloudflare's registry                       | The Dockerfile that produced it, built into Vercel Container Registry                                                                                                 |
| A Sandbox SDK 0.x image based on `docker.io/cloudflare/sandbox`      | A managed image, or your Dockerfile rebuilt on a standard base image such as `node:24-trixie-slim`                                                                    |

If a managed image meets your needs, continue to [sandbox creation](#5.-replace-container-calls-with-vercel-sandbox-sdk-calls).

#### Build a custom image

Install Docker and remove the Cloudflare-specific lines from your Dockerfile. For example, a Sandbox SDK 1.0 image that uses the `@cloudflare/sandbox` helpers includes the helper binary and a command to keep the container running:

```docker
FROM node:24-trixie-slim

COPY --from=docker.io/cloudflare/sandbox:1.0.1 \
  /usr/local/bin/sandbox-shim \
  /usr/local/bin/sandbox-shim

RUN apt-get update && apt-get install -y git python3
RUN mkdir /workspace
CMD ["sleep", "infinity"]
```

Vercel's SDK reads and writes files without a helper binary, and a sandbox stays running without a foreground process. Remove the `sandbox-shim` line and the `sleep infinity` command, then set the working directory:

```docker
FROM node:24-trixie-slim
RUN apt-get update && apt-get install -y git python3
WORKDIR /workspace
```

Also remove packages and startup scripts that only served Cloudflare features, such as `fuse3` and `s3fs` for `S3Mount`, or an entrypoint script that trusts Cloudflare's outbound CA certificate.

Both products require `linux/amd64` images. Vercel Container Registry allows 15 GB per image and 2 GB per compressed layer. 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")
```

When adapting startup code, account for the image settings that Vercel uses:

- Start processes with `runCommand()` after creation. Vercel Sandbox does not run an image's `ENTRYPOINT` or `CMD`, and `Sandbox.create()` has no `entrypoint` option.
  
- Choose the image when creating the sandbox. It stays with that sandbox, whereas each Cloudflare `start()` call can select an image by its name in your Wrangler configuration.
  
- Use the Dockerfile's `WORKDIR` for a custom image, or `/` if none is set. Managed images use `/vercel`.
  

#### Install additional packages

For an Ubuntu-based managed image, update the package index before installing packages with `apt-get` and `sudo`:

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

Installed packages remain across persistent sessions. Use the package manager supplied by your image when running Arch or a custom image.

### 5\. Replace container calls with Vercel Sandbox SDK calls

Replace `start()`, `exec()`, and the `Files` helper with the corresponding Vercel methods. `Sandbox.create()` uses project credentials and an image reference instead of a Durable Object binding and a Wrangler `images` entry.

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

#### Choose where the sandbox calls run

On Cloudflare, sandbox calls run inside a Durable Object that your application reaches through Worker routes. Move those calls to a backend that holds Vercel credentials, or keep the Worker as the entry point:

- Import the SDK in a Vercel Function, a server on another host, a queue worker, or a CI job. The TypeScript SDK runs on Node.js.
  
- If the Worker stays in place, forward sandbox requests to that backend with `fetch()`, or call the [Sandboxes endpoints in the Vercel REST API](https://vercel.com/docs/rest-api/sandboxes) with an access token stored as a Worker secret. The Durable Object can retain session records and locks without its container.
  

Preserve the checks your Worker runs before calling `getByName()`. Authenticate each caller and derive the sandbox name from that caller's identity, because knowing a sandbox's name does not establish permission to use it.

#### TypeScript SDK calls

The 0.x column follows Cloudflare's [API map](https://developers.cloudflare.com/sandbox/sdk/migrate/api-map/), which lists every SDK 0.x call.

| Task                          | Cloudflare Sandbox SDK 0.x                         | Cloudflare Sandbox SDK 1.0                                     | Vercel Sandbox                                                                         |
| ----------------------------- | -------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| Import                        | `import { getSandbox } from '@cloudflare/sandbox'` | `import { DurableObject } from 'cloudflare:workers'`           | `import { Sandbox } from '@vercel/sandbox'`                                            |
| Reach a sandbox               | `getSandbox(env.Sandbox, id)`                      | `env.MY_CONTAINER.getByName(id)`                               | `Sandbox.getOrCreate({ name })`                                                        |
| Start a sandbox               | Starts on the first call                           | `container.start({ image })`                                   | `Sandbox.create(params)`                                                               |
| Set the lifetime              | `sleepAfter`                                       | `container.setInactivityTimeout(ms)`                           | `timeout`, in milliseconds                                                             |
| Keep a sandbox running        | `keepAlive`                                        | Durable Object alarm                                           | `timeout` and `sandbox.extendTimeout(ms)`                                              |
| Set resources                 | `instance_type` in the Wrangler configuration      | `instance` in `start()`                                        | `resources: { vcpus }`                                                                 |
| Run a command                 | `sandbox.exec('python main.py')`                   | `container.exec(['python', 'main.py'])`                        | `sandbox.runCommand('python', ['main.py'])`                                            |
| Set a command timeout         | `timeout` option in `exec()`                       | GNU `timeout` wrapper                                          | `timeoutMs`                                                                            |
| Read output                   | `result.stdout`                                    | `(await process.output()).stdout`, decoded with `TextDecoder`  | `await result.stdout()`                                                                |
| Stream output                 | `sandbox.execStream(command)`                      | `process.stdout`                                               | `command.logs()` on a detached command                                                 |
| Get the exit code             | `result.exitCode`                                  | `(await process.output()).exitCode`                            | `result.exitCode`                                                                      |
| Write a file                  | `sandbox.writeFile(path, content)`                 | `files.writeFile(path, content)`                               | `sandbox.writeFiles([{ path, content }])`                                              |
| Read a file                   | `sandbox.readFile(path)`                           | `files.readFile(path)`, which returns a `Response`             | `sandbox.fs.readFile(path, 'utf8')`, or `sandbox.readFileToBuffer({ path })` for bytes |
| List, create, or remove paths | `listFiles()`, `mkdir()`, and `deleteFile()`       | `files.readDirectory()`, `files.mkdir()`, and `files.remove()` | `sandbox.fs.readdir()`, `sandbox.fs.mkdir()`, and `sandbox.fs.rm()`                    |
| Clone a repository            | `sandbox.gitCheckout(url)`                         | `container.exec(['git', 'clone', url])`                        | `source: { type: 'git', url }` in `Sandbox.create()`                                   |
| Start a background process    | `sandbox.startProcess(command)`                    | Your own pattern over `container.exec()`                       | `sandbox.runCommand({ cmd, args, detached: true })`                                    |
| Run code in an interpreter    | `sandbox.runCode(code)`                            | Your own pattern, such as an IPython kernel                    | `writeFiles()`, then `runCommand()`                                                    |
| List sandboxes                | Your own records                                   | Your own records                                               | `Sandbox.list({ tags })`, which filters on one tag                                     |
| End a sandbox                 | `sandbox.destroy()`                                | `container.destroy()`                                          | `sandbox.stop()` or `sandbox.delete()`                                                 |

On Cloudflare, the Durable Object starts the container, writes a file with `Files`, and runs a command. The Worker route reaches it through its binding:

```typescript
import { Files } from '@cloudflare/sandbox';
import { DurableObject } from 'cloudflare:workers';

export class MyContainer extends DurableObject<Env> {
  async run(code: string) {
    const container = this.ctx.container;
    if (!container) {
      throw new Error('No container is configured');
    }

    if (!container.running) {
      container.start({
        image: container.images.workspace,
        instance: 'standard-1',
        enableInternet: false,
      });
      await container.setInactivityTimeout(10 * 60 * 1000);
    }

    const files = new Files(container);
    await files.writeFile('/workspace/main.py', code);

    const process = await container.exec(['python3', 'main.py'], {
      cwd: '/workspace',
      env: { PYTHONUNBUFFERED: '1' },
    });
    const output = await process.output();
    return {
      stdout: new TextDecoder().decode(output.stdout),
      exitCode: output.exitCode,
    };
  }
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // Authenticate the caller before using sessionId.
    const { sessionId, code } = (await request.json()) as {
      sessionId: string;
      code: string;
    };
    const sandbox = env.MY_CONTAINER.getByName(sessionId);
    return Response.json(await sandbox.run(code));
  },
};
```

The Vercel script below runs the same Python code from Node.js. `networkPolicy: 'deny-all'` and `persistent: false` keep Cloudflare's behavior of blocking egress and discarding files when the sandbox stops:

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

const sandbox = await Sandbox.create({
  timeout: 10 * 60 * 1000,
  resources: { vcpus: 2 },
  env: { PYTHONUNBUFFERED: '1' },
  networkPolicy: 'deny-all',
  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 and a fixed 2-vCPU size. Cloudflare's `standard-1` type provides 1/2 vCPU and 4 GiB of memory, so 2 vCPUs is the smallest Vercel size with that much memory. Check peak CPU and memory use before choosing the size for your workload.

Save the script as `sandbox.mjs` and run it with the environment file loaded. The default image provides the `python` command used here; if you built the custom image in step 4, use `python3` instead.

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

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

In your application, the Durable Object's `run()` method becomes a function that looks up the session's sandbox by name. Step 6 covers how a named sandbox saves and resumes its files:

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

export async function run(sessionId, code) {
  const sandbox = await Sandbox.getOrCreate({
    name: `session-${sessionId}`,
    networkPolicy: 'deny-all',
  });

  await sandbox.writeFiles([
    { path: 'main.py', content: Buffer.from(code) },
  ]);
  const result = await sandbox.runCommand('python', ['main.py']);
  return {
    stdout: await result.stdout(),
    exitCode: result.exitCode,
  };
}
```

#### Python SDK calls

If you're moving the calls into a Python backend, use the `vercel-sandbox` package. These are the Python names for the same tasks:

| Task                          | Vercel Sandbox (Python)                                     |
| ----------------------------- | ----------------------------------------------------------- |
| Import                        | `from vercel import sandbox`                                |
| Create a sandbox              | `sandbox.create_sandbox()`                                  |
| Set the lifetime              | `execution_time_limit`, in seconds or as a `timedelta`      |
| Set resources                 | `resources=SandboxResources(vcpus=2, memory=4096)`          |
| Run a command                 | `box.run_command("python", ["main.py"])`                    |
| Read output                   | `result.stdout.decode()`, with `capture_output=True`        |
| Get the exit code             | `result.returncode`                                         |
| Write a file                  | `box.fs.write_text(path, text)`                             |
| Read a file                   | `box.fs.read_text(path)`                                    |
| List, create, or remove paths | `box.fs.listdir()`, `box.fs.mkdir()`, and `box.fs.remove()` |
| Find a sandbox                | `sandbox.get_sandbox(name=name)`                            |
| End a sandbox                 | `box.stop()` or `box.destroy()`                             |

Save `sandbox_example.py` in your linked project directory:

```python
import asyncio

from dotenv import load_dotenv
from vercel import sandbox
from vercel.sandbox import NetworkPolicy, 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"},
        network_policy=NetworkPolicy.deny_all(),
        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 sandbox on exit, matching `container.destroy()`. To keep files across sessions, set `persistent=True` and `destroy=False` when creating the sandbox so the context manager stops and saves it. You can also await `create_sandbox()` directly and call `stop()` when work ends.

For synchronous code, import `sync` from `vercel.sandbox` as `sandbox`. Remove `await` and use regular context managers.

#### Differences to check in every call

Vercel takes a binary and argument array, like `container.exec()`, and needs `bash -c` for pipes, redirection, or variable expansion. Sandbox SDK 0.x runs `sandbox.exec()` strings in a shell; split them into arguments or retain an explicit shell. Its shell session preserves `cd` and `export` between calls. On Vercel, set `cwd` and `env` per command or run dependent steps together in one shell.

Cloudflare's `process.output()` returns `ArrayBuffer` values that you decode with `TextDecoder`, while Vercel's `result.stdout()` returns a string. In Python, `run_command()` streams to your local stdout unless you pass `capture_output=True`; captured output is `bytes`.

#### Convert timeouts and time units

Cloudflare's `setInactivityTimeout()` and Vercel TypeScript's `timeout`, `timeoutMs`, and `extendTimeout()` all take milliseconds. Sandbox SDK 0.x instead accepts a string such as `"10m"` or a number of seconds for `sleepAfter`. Vercel's Python SDK takes seconds or a `timedelta` in `execution_time_limit` and `kill_after`.

Cloudflare's `container.exec()` has no timeout option. Replace a GNU `timeout` wrapper with `timeoutMs` in TypeScript or `kill_after` in Python.

#### Set the execution environment

Review the context each command runs in before porting its arguments:

- Cloudflare's `exec()` processes do not inherit variables from `start()` or the image, except `PATH`. On Vercel, environment variables set at sandbox creation apply to every command, and a command's own `env` overrides them.
  
- Cloudflare's `exec()` defaults to `/` unless you pass `cwd`; Sandbox SDK 0.x uses `/workspace`. Relative paths in Vercel managed images start at `/vercel`.
  
- Deployed Sandbox SDK 1.0 containers give every process root's Linux capabilities. Vercel managed images run as `ubuntu` or `arch` with passwordless sudo, so pass `sudo: true` in TypeScript or `sudo=True` in Python when a command needs root.
  

Vercel sandboxes also start with internet access and persist files by default. Set `networkPolicy` at creation as shown in step 9. For a one-off sandbox, pass `persistent: false` or `persistent=False` to avoid saving a snapshot on stop; saved snapshots count toward Snapshot Storage.

#### Background commands and streamed output

Use a detached command for streamed output or a long-running process. With `detached: true`, `runCommand()` returns when the command starts, and `command.logs()` streams its output:

```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()
```

Cloudflare stops an instance when its main process exits. If your application depends on that behavior, wait for the Vercel command and call `sandbox.stop()` in a `finally` block so cleanup also runs on failure. Keep persistent services running until your application ends their session.

On Cloudflare, a streamed response keeps the Durable Object active while the command runs. On Vercel, the command keeps running without an open connection, and connections close after 340 seconds without data. Use the [long-running task pattern](https://vercel.com/docs/sandbox/examples/execute-long-running-tasks) for longer, quiet jobs.

### 6\. Replace snapshot handles with named sandboxes

Use a named persistent sandbox in place of taking a snapshot and storing its ID for each agent session.

#### Reconnect to a sandbox by name

On Cloudflare, your Durable Object takes a snapshot before the instance stops, stores the snapshot's `id`, and passes it to the next `start()`. The excerpt runs inside the Durable Object class, where `container` is `this.ctx.container`:

```typescript
// End of an agent session
const snapshot = await container.snapshotContainer();
await this.ctx.storage.put('snapshotId', snapshot.id);
await container.destroy();

// Next agent session
const snapshotId = await this.ctx.storage.get<string>('snapshotId');
if (!snapshotId) {
  throw new Error('No snapshot for this session');
}
container.start({
  containerSnapshot: { id: snapshotId },
  entrypoint: ['sleep', 'infinity'],
  enableInternet: false,
});
```

Applications that use `DirectoryBackup`, or `createBackup()` in Sandbox SDK 0.x, store a backup record in the same way.

Give the Vercel sandbox a name derived from the agent session. Stopping it saves the files, and a later file or command operation resumes it from that snapshot:

**Vercel Sandbox (TypeScript)**

```javascript
// End of an agent session
const sandbox = await Sandbox.getOrCreate({
  name: `session-${sessionId}`,
  networkPolicy: 'deny-all',
});
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
from vercel.sandbox import NetworkPolicy

# End of an agent session
box, created = await sandbox.get_or_create_sandbox(
    name=f"session-{session_id}",
    network_policy=NetworkPolicy.deny_all(),
)
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"))
```

Both Vercel samples print `draft` by reopening the saved workspace under its sandbox name, which is unique within the project and cannot change. Store that name in place of a snapshot ID so later sessions can retrieve the workspace.

On each resume, the sandbox starts a new session with a new timeout. Creation options such as `networkPolicy` and `ports` apply only when `getOrCreate()` creates the sandbox; use `sandbox.update()` to change them on an existing sandbox.

#### Retain and recover saved files

Snapshots expire 30 days after last use by default. Set `snapshotExpiration` in milliseconds or Python's `snapshot_expiration` in seconds to change retention. Use `0` when files need indefinite retention.

For a workspace that must already exist, use `Sandbox.get()` or Python's `get_sandbox()`, then handle resume failures explicitly. TypeScript's `getOrCreate()` with `resume: true` replaces a sandbox whose saved snapshot is missing, and Python's `get_or_create_sandbox()` does so by default. Restore a verified backup before accepting more work after a resume failure.

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

#### Restart processes after a resume

On Cloudflare, an instance that starts from a snapshot runs its entrypoint again. Vercel Sandbox doesn't run an entrypoint, and resuming restores files only, so restart the processes your application needs. 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

To reuse a prepared environment, take a snapshot and pass its ID as `source`, as you would pass one snapshot `id` to several Cloudflare `start()` calls. Git sources clone into a directory named after the repository, so the setup command uses `your-repo` as its working directory.

`runCommand()` returns a result even for failed commands, so check `exitCode` before saving the prepared environment. For Python setup, pass `check=True` to `run_command()` to stop the sequence on failure.

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

const base = await Sandbox.create({
  name: 'base-environment',
  source: {
    type: 'git',
    url: 'https://github.com/your-org/your-repo.git',
    depth: 1,
  },
});

try {
  const install = await base.runCommand({
    cmd: 'npm',
    args: ['install'],
    cwd: 'your-repo',
  });
  if (install.exitCode !== 0) {
    throw new Error(
      `Dependency installation failed: ${await install.stderr()}`,
    );
  }

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

Calling `base.snapshot()` saves files and stops the session. To fork the sandbox's latest saved snapshot, use `Sandbox.fork()` and pass its name as `sourceSandbox`. Create new sandboxes where the 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()` for the base sandbox because `async with` destroys it and its unused snapshots on exit. Pass `snapshot.id` as the `snapshot_id` argument to `SnapshotSource` when creating another sandbox from it, or use `sandbox.fork_sandbox()` to fork by name.

#### Copy files from existing Cloudflare snapshots

Vercel Sandbox can't read a Cloudflare snapshot, and Cloudflare doesn't return its data to your Worker. Export the session files from a Cloudflare container and rebuild system packages and image dependencies as described in step 4. Pause the processes that write those files and keep writes paused through the final import and [verification in step 10](#10.-verify-and-cut-over).

The method below belongs in your Durable Object class and requires `tar`. It exports the running container's current filesystem, or starts an instance from the stored snapshot ID if the container is stopped. Confirm that this is the workspace version you intend to migrate. The archive needs free disk space, so exclude rebuildable directories such as `node_modules` if space is low. Export before the snapshot expires, 30 days after creation or its last restore.

```typescript
async exportDirectory(dir: string): Promise<ReadableStream> {
  const container = this.ctx.container;
  if (!container) {
    throw new Error('No container is configured');
  }

  if (!container.running) {
    const snapshotId = await this.ctx.storage.get<string>('snapshotId');
    if (!snapshotId) {
      throw new Error('No snapshot for this session');
    }
    container.start({
      containerSnapshot: { id: snapshotId },
      // Pass the entrypoint that your application passes to start().
      entrypoint: ['sleep', 'infinity'],
      enableInternet: false,
    });
    await container.setInactivityTimeout(10 * 60 * 1000);
  }

  const archive = await container.exec([
    'tar', '-czf', '/tmp/export.tgz', '-C', dir, '.',
  ]);
  const { exitCode, stderr } = await archive.output();
  if (exitCode !== 0) {
    throw new Error(new TextDecoder().decode(stderr));
  }

  const download = await container.exec(['cat', '/tmp/export.tgz'], {
    stderr: 'ignore',
  });
  return download.stdout!;
}
```

Call the method from a temporary Worker route that authenticates the caller, and return the stream as the response body. This excerpt exports `/workspace`:

```typescript
const sandbox = env.MY_CONTAINER.getByName(sessionId);
const archive = await sandbox.exportDirectory('/workspace');
return new Response(archive, {
  headers: { 'Content-Type': 'application/gzip' },
});
```

Download the archive from that route, then list its contents to confirm that the download is complete. Set `EXPORT_TOKEN` to the credential your route checks, and replace the hostname with your Worker's:

```bash
curl --fail --output workspace.tgz \
  -H "Authorization: Bearer $EXPORT_TOKEN" \
  "https://your-worker.example.com/export/session-123"
tar -tzf workspace.tgz > /dev/null
```

#### Export files from Sandbox SDK 0.x

Sandbox SDK 0.x has no container snapshots. If your application saves directories with `createBackup()`, restore the backup with `restoreBackup()` before exporting. Keep it until migration checks pass, accounting for its default expiration of 3 days. Run the same `tar` command through `sandbox.exec()` in a running sandbox and check its `exitCode` before reading the archive.

Return the archive as bytes through the authenticated Worker route. Choose the read mode for your SDK version and transport:

- With SDK 0.10.1 or later and `SANDBOX_TRANSPORT=rpc`, read `/tmp/export.tgz` with `sandbox.readFile()` and the option `encoding: 'none'`. Return the result's `content` stream as the response body.
  
- With another transport, request `encoding: 'base64'` and decode `content` to bytes before returning it.
  

#### Import the archive into Vercel Sandbox

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

Configure the destination sandbox when you create it. Later calls to `getOrCreate()` will not change its settings. Add the options your application needs to the command below, such as `--image agent-runtime:latest`, `--vcpus`, or `--network-policy deny-all`. For a custom image, extract into its working directory instead of `/vercel`.

Save the sequence as a Bash script and run it from the linked project directory, or select a project with `--project` and `--scope`. The initial `set -e` stops the import if a copy or extraction fails, so later commands cannot hide that failure. Keep the source archive until the imported files pass verification.

```bash
set -e

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

### 7\. Move R2 backups and bucket mounts to Drives

Use a [Drive](https://vercel.com/docs/sandbox/concepts/drives) for storage that outlives a sandbox and mounts as a directory. It can replace a `DirectoryBackup` archive or an `S3Mount` when sandboxes are the only readers and writers. If other systems use the same bucket, review the [mounted R2 bucket options](#mounted-r2-buckets) before moving its files.

With `DirectoryBackup`, your Durable Object backs up a directory to R2 before the instance stops and restores it into the next instance. Here, `container` is `this.ctx.container`:

```typescript
const backups = new DirectoryBackup(
  container,
  this.ctx.exports.DirectoryBackupGateway,
  { binding: 'BACKUPS', prefix: 'backups/' },
);

// Before the instance stops
const record = await backups.backup({ dir: '/cache' });
await this.ctx.storage.put('cacheBackup', record);

// In the next instance
await backups.restore(record);
```

#### Create and mount a Drive

The Python Sandbox SDK includes Drive operations. For JavaScript, install `@vercel/drives`:

**pnpm**

```bash
pnpm i @vercel/drives
```

**npm**

```bash
npm i @vercel/drives
```

**yarn**

```bash
yarn add @vercel/drives
```

**bun**

```bash
bun add @vercel/drives
```

Choose the Drive's region and measure your files before creating it; neither the region nor the maximum size can change later. New Drives default to `iad1`. Size defaults are 1 TB on Pro and Enterprise, or 1 GB on Hobby and Pro trials. Use `maxSize` in TypeScript or `max_size_bytes` in Python within your plan's [Drive limits](https://vercel.com/docs/drives/pricing#limits).

Create the Drive and mount it in a sandbox in the same region:

**Vercel Sandbox (TypeScript)**

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

const drive = await Drive.getOrCreate({
  name: 'workspace-cache',
  region: 'iad1',
});

const sandbox = await Sandbox.create({
  region: drive.region,
  mounts: { '/cache': drive },
});
```

**Vercel Sandbox (Python)**

```python
drive, created = await sandbox.get_or_create_drive(
    name="workspace-cache", region="iad1"
)

box = await sandbox.create_sandbox(
    region=drive.region,
    mounts={"/cache": drive},
)
```

Files written under the mount path are stored on the Drive, so remove the `backup()` and `restore()` calls and the backup records in Durable Object storage. Each sandbox can mount up to four Drives at non-overlapping absolute paths.

Each Drive permits one writable mount. For concurrent readers, mount `drive.snapshot()` to give them a read-only view of the files at that point in time. Attach a new snapshot whenever readers need to see later writes.

#### Export the R2 files

Before the final export, stop or pause writers and wait for any backups in progress. The export path depends on how the application stores its files:

- For a directory backup, call `restore(record)` in a running instance and download the directory with the `exportDirectory()` method from step 6. Pass the backup's directory, such as `/cache`.
  
- For a mounted bucket, download the objects through R2's S3-compatible API and archive them. The following commands use [rclone](https://developers.cloudflare.com/r2/examples/rclone/) with a remote named `r2` that authenticates with an R2 API token.
  

```bash
rclone copy r2:workspace-cache ./workspace-cache
tar -czf workspace.tgz -C ./workspace-cache .
```

#### Import the files into the Drive

If you ran the SDK mount example, call `sandbox.stop()` in TypeScript or `box.stop()` in Python to release its writable mount before importing. Verify the archive's contents and keep it until the imported files pass verification.

Save the sequence below as a Bash script and run it from the linked project directory. It copies the archive into a sandbox that mounts the Drive, extracts the files into `/cache`, and stops if a command fails:

```bash
set -e

sandbox create --name drive-import \
  --non-persistent --region iad1 --timeout 30m \
  --mount workspace-cache:/cache
sandbox copy ./workspace.tgz drive-import:/vercel/workspace.tgz
sandbox exec drive-import -- tar -xzf /vercel/workspace.tgz -C /cache
sandbox stop drive-import
```

The `--non-persistent` flag discards the import sandbox's own files on stop. The files in `/cache` stay on the Drive.

### 8\. Replace Worker preview routes with public ports

Vercel's [public ports](https://vercel.com/docs/sandbox/examples/expose-a-port) replace `getTcpPort()` and the Worker's preview route. Set `ports` at creation and read the URL with `sandbox.domain()`.

On Cloudflare, a method in your Durable Object class forwards each request to the server in the container:

```typescript
async fetch(request: Request): Promise<Response> {
  const container = this.ctx.container;
  if (!container) {
    throw new Error('No container is configured');
  }
  return container.getTcpPort(8000).fetch(request);
}
```

Your Worker routes each preview path, such as `/previews/<name>/`, to that sandbox:

```typescript
const url = new URL(request.url);
const sandbox = env.MY_CONTAINER.getByName(name);
return sandbox.fetch(
  new Request(`http://container${path}${url.search}`, request),
);
```

Vercel port URLs are public, so anyone with the URL can reach the server. Add caller authentication as shown in [authenticated previews](#authenticated-previews-and-raw-tcp) before using this pattern for protected content. 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)
```

Sandbox SDK 0.x's `exposePort()` and `proxyToSandbox()` map the same way. `sandbox.domain(port)` replaces the preview URL that `exposePort()` returns.

#### Update preview routing and sessions

Each port has its own URL. Remove the wildcard DNS record, Worker route, and path prefix that served previews once callers use those URLs. To change the exposed ports, pass the complete list as `ports` to `sandbox.update()`.

Requests to a stopped sandbox return HTTP 410 and do not resume it. Have your backend run a command to resume the sandbox, then restart the server as shown in step 6. Unlike requests through a Durable Object, preview requests do not extend a Vercel session; call `extendTimeout()` while the user is active.

Neither product waits for the server to listen, so replace the loop that retries `getTcpPort()` with a [readiness check](#check-that-your-service-is-ready). Clients also need to reconnect WebSockets when a connection closes, even if the sandbox is still running.

### 9\. Replace outbound handlers and secrets with a network policy

#### Map egress settings to a network policy

Sandbox SDK 1.0 containers default to no internet access. Vercel Sandbox defaults to `allow-all`, as Sandbox SDK 0.x does. Set `networkPolicy` in every creation call that should restrict egress, using the existing `enableInternet` setting and handlers as a starting point:

| Cloudflare setting                                                                                            | Vercel `networkPolicy`                          |
| ------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- |
| `enableInternet: false` with no intercepts                                                                    | `'deny-all'`                                    |
| `enableInternet: true` with no intercepts                                                                     | `'allow-all'`, the default                      |
| `interceptOutboundHttps()` for `api.openai.com` and `*.github.com`, with a handler that forwards each request | `{ allow: ['api.openai.com', '*.github.com'] }` |
| `interceptOutboundHttp()` for `203.0.113.0/24`                                                                | `{ subnets: { allow: ['203.0.113.0/24'] } }`    |
| Sandbox SDK 0.x `allowedHosts`                                                                                | `{ allow: [...] }`                              |

On Cloudflare, a forwarding handler and its intercepts look like this. In the excerpt, `container` is `this.ctx.container`:

```typescript
import { WorkerEntrypoint } from 'cloudflare:workers';

export class Egress extends WorkerEntrypoint<Env> {
  fetch(request: Request) {
    // Check the request's hostname here, then forward it.
    return fetch(request);
  }
}

// In the Durable Object, before start()
await container.interceptOutboundHttps('api.openai.com', this.ctx.exports.Egress);
await container.interceptOutboundHttps('*.github.com', this.ctx.exports.Egress);
container.start({
  image: container.images.workspace,
  enableInternet: false,
});
```

On Vercel, set the policy at creation or replace it with `update()`. 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'],
  },
});

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": ()}
    ),
)

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

#### Preserve hostname checks

Cloudflare globs match any sequence of characters. Vercel wildcards replace a whole DNS label, so rewrite patterns such as `api*.example.com`. The pattern `*.github.com` matches subdomains at any depth but excludes `github.com`; add the apex domain if the sandbox calls it.

Vercel domain allow lists match the TLS hostname without checking the `Host` header. Preserve a Cloudflare handler's hostname check with a `transform` rule that sets `Host` to the allowed domain. Plain HTTP has no TLS hostname, so move clients served by `interceptOutboundHttp()` to HTTPS or allow their address range.

#### Review address ranges and DNS

Cloudflare passes each HTTP request to an intercepted address range through your handler. Vercel traffic to a range in `subnets.allow` bypasses domain rules, credential brokering, and forwarding. Keep each range exact so this route grants only the access your application needs.

Cloudflare containers with `enableInternet: false` resolve only intercepted hostnames. On Vercel, a policy with allowed address ranges and no allowed domains can resolve any hostname. Add domain rules to restrict DNS resolution, or use `deny-all` to block it.

#### Change or revoke access

You cannot remove a Cloudflare intercept while the container runs, though you can replace its handler with one that denies requests. Vercel's `sandbox.update()` replaces the policy in full, allowing you to add or remove domains.

Vercel has no domain deny list. Reject a domain with a `response` rule whose `statusCode` is `403`, keeping a `'*'` entry for other domains. To block address ranges, add `subnets.deny` to a policy that also has an allow rule; a policy containing only `subnets.deny` blocks all traffic.

#### Pass secrets as environment variables

On Cloudflare, your Durable Object reads Worker secrets from `this.env` and passes them in `env` to `start()` or `exec()`. On Vercel, pass values from your application through `env` when creating the sandbox or running a command:

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

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

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.

#### Broker credentials with firewall rules

Code in the sandbox can read every value in its environment. To keep a credential outside the sandbox, replace the outbound handler with a brokering rule that adds the header after the request leaves. Brokering and forwarding rules are available on Hobby, Pro, and Enterprise within each plan's Sandbox usage quotas.

**Cloudflare Sandbox**

```typescript
export class ApiAuth extends WorkerEntrypoint<Env> {
  fetch(request: Request) {
    const url = new URL(request.url);
    if (url.protocol !== 'https:' || url.hostname !== 'api.example.com') {
      return new Response('Forbidden', { status: 403 });
    }
    const authed = new Request(url, request);
    authed.headers.set('Authorization', `Bearer ${this.env.API_TOKEN}`);
    return fetch(authed, { redirect: 'manual' });
  }
}

// In the Durable Object, before start()
await container.interceptOutboundHttps(
  'api.example.com',
  this.ctx.exports.ApiAuth,
);
```

**Vercel Sandbox (TypeScript)**

```javascript
const sandbox = await Sandbox.create({
  networkPolicy: {
    allow: {
      'api.example.com': [
        {
          transform: [
            {
              headers: {
                Host: 'api.example.com',
                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={
                                "Host": "api.example.com",
                                "Authorization": (
                                    f"Bearer {os.environ['API_TOKEN']}"
                                )
                            }
                        )
                    ]
                )
            ],
        }
    ),
)
```

Both Vercel policies set `Host` as well as `Authorization`, preserving the hostname check in the Cloudflare handler. They allow only `api.example.com`, matching this intercept with `enableInternet: false`. Add a `'*': []` entry only if your container starts with `enableInternet: true`.

To replace further request checks in the handler, add a `match` for the path, method, query string, or headers. The query matcher is `queryString` in TypeScript and `query` in Python. End the domain's rule list with a `response` rule whose `statusCode` is `403` so unmatched requests are rejected. Handlers that run other code need a [proxy behind a forwarding rule](#outbound-handlers-that-run-code).

#### Update trust stores and package access

The firewall adds its per-sandbox CA to the system certificates. Remove entrypoint steps that trust Cloudflare's CA and any `NODE_EXTRA_CA_CERTS` or `REQUESTS_CA_BUNDLE` value pointing to it. Docker containers running inside the sandbox must separately [trust its proxy CA](https://vercel.com/docs/sandbox/concepts/security#trust-the-proxy-ca-in-containers).

If your handler adds a registry token for package installs, set `credentials: { npm: true }` to use [managed npm credentials](https://vercel.com/docs/sandbox/concepts/credentials).

### 10\. Verify and cut over

#### Validate workload behavior and resource use

Run both providers side by side before moving sessions. Use representative workloads to check the behavior and resource needs of the Vercel implementation:

- Compare output, exit codes, and written files from both providers.
  
- Measure peak CPU and memory on Vercel, then set `vcpus` to cover the peak. Plan 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 rates 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. Include the Workers and Durable Objects usage that fronts each Cloudflare sandbox when comparing costs.
  

#### Move session state and switch traffic

If shared data must remain writable during cutover, plan replication between providers. Otherwise, pause 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. Pause writes to the session workspaces and buckets being moved. Take final snapshots or directory backups and wait for them to finish, then export, import, and verify the files before routing those sessions to Vercel.
   
3. Switch the flag for new sessions and monitor output and errors. Keep existing sessions on Cloudflare until they finish or you import their state.
   

#### Keep a rollback path until cleanup

To roll back, send new sessions to Cloudflare. Before moving a session that has written files on Vercel, copy those changes back and verify them. Retain both providers' state until the rollback period ends. Cloudflare snapshots expire 30 days after creation or their last restore, so export any you still need before then.

After the rollback period, remove only the call sites and data that migrated workloads no longer need. Keep images, R2 buckets, and Worker secrets used by workloads remaining on Cloudflare. Remove the `containers` entry, Durable Object class, preview routes, and wildcard DNS records only after confirming that no other Worker or application uses them.

## What doesn't map from Cloudflare Sandbox

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

### Fractional-vCPU and memory-heavy instances

Vercel sandboxes have 1 vCPU or an even number up to 32, with 2 GB of memory per vCPU. Cloudflare sets vCPU, memory, and disk separately, with sizes below one vCPU and types that pair a small CPU share with more memory. Choose a Vercel size that covers the larger of your CPU and memory needs and fits your plan.

| Cloudflare instance | vCPU | Memory  | Smallest Vercel size with that memory |
| ------------------- | ---- | ------- | ------------------------------------- |
| `lite`              | 1/16 | 256 MiB | 1 vCPU and 2 GB                       |
| `basic`             | 1/4  | 1 GiB   | 1 vCPU and 2 GB                       |
| `standard-1`        | 1/2  | 4 GiB   | 2 vCPUs and 4 GB                      |
| `standard-2`        | 1    | 6 GiB   | 4 vCPUs and 8 GB                      |
| `standard-3`        | 2    | 8 GiB   | 4 vCPUs and 8 GB                      |
| `standard-4`        | 4    | 12 GiB  | 6 vCPUs and 12 GB                     |

Vercel provisions 2,048 MB of memory for each vCPU, so these sizes match each type's provisioned memory, which a workload may not use in full. Measure peak CPU and memory in step 10 before you settle on a size. Sizes above 4 vCPUs require a Pro plan, and sizes above 8 vCPUs require an Enterprise plan.

Pass the size as `resources.vcpus`:

```javascript
const sandbox = await Sandbox.create({ resources: { vcpus: 1 } });
```

Vercel meters Active CPU and Provisioned Memory separately. For a workload that runs on a `lite` instance today, Vercel bills 2 GB of provisioned memory while the sandbox runs, and CPU time only while its code is active.

To run many small tasks that trust each other, give each task its own [Linux user](https://vercel.com/docs/sandbox/concepts/multi-agent) in one sandbox instead of one sandbox per task. The users share one microVM, so keep tasks that need their own kernel in separate sandboxes.

### Inactivity timeouts, keep-alive alarms, and readiness checks

#### Stop idle sessions and extend active work

Vercel Sandbox has no inactivity timeout, and requests do not extend a session. 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.

Remove the Durable Object alarm that keeps an instance running during a build or agent task. Work in a Vercel sandbox can continue until the session timeout without requests from your application. While a session is 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 does not reset an idle timer or change the default timeout for later sessions. Use `extendTimeout()` and `stop()` from your application.

Cloudflare has no fixed maximum runtime. Vercel sessions last up to 45 minutes on Hobby, or 24 hours on Pro and Enterprise. For longer work, save progress to files and continue in a new session of the same persistent sandbox.

#### Check that your service is ready

Sandbox creation waits for the environment to accept commands, but your server may still be starting. Replace the `getTcpPort()` retry loop with a readiness check for the service and its dependencies. Save the helper as `wait-for-http.mjs` and call it with the service's health URL 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.

### Outbound handlers that run code

Cloudflare's `WorkerEntrypoint` handlers can rewrite or record requests, read bindings such as KV and R2, and receive per-instance `props`. Move the checks and credential headers into Vercel's `networkPolicy` rules. For other request processing, run your code in a proxy behind a forwarding rule:

| Handler behavior                                              | On Vercel                                                                 |
| ------------------------------------------------------------- | ------------------------------------------------------------------------- |
| Allows requests to a hostname                                 | Domain allow list in `networkPolicy`                                      |
| Adds a credential header                                      | Brokering rule with `transform`                                           |
| Allows only some paths or methods                             | `match` on the rule, followed by a `response` rule with `statusCode: 403` |
| Uses a different credential for each instance through `props` | A `networkPolicy` built for each sandbox at creation                      |
| Changes access while a task runs                              | `sandbox.update({ networkPolicy })`                                       |
| Rewrites requests, records them, or reads a binding           | Forwarding rule with `forwardURL`, and a proxy that you run               |

To run your own code on each request, add a [forwarding rule](https://vercel.com/docs/sandbox/concepts/firewall#requests-proxying) for the domain. Code in the sandbox keeps calling the original hostname, and the firewall sends each request to your proxy:

```javascript
const sandbox = await Sandbox.create({
  networkPolicy: {
    allow: {
      'api.example.com': [
        { forwardURL: 'https://your-proxy.vercel.app/api' },
      ],
    },
  },
});
```

The proxy receives the original request with a `vercel-sandbox-oidc-token` header identifying the sandbox. The `defineSandboxProxy` helper from `@vercel/sandbox/proxy` verifies it and passes the sandbox's IDs and name to your handler. It runs in a Vercel Function or another server using the Fetch API:

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

const proxy = defineSandboxProxy(async (request, { sandboxName }) => {
  // Apply the logic from your outbound handler here.
  console.log(`${sandboxName}: ${request.method} ${request.url}`);
  return fetch(request);
});

export default {
  fetch: proxy,
};
```

#### Preserve proxy authorization and routing

By default, `defineSandboxProxy` accepts only sandboxes from the proxy's own Vercel project. If the proxy runs outside Vercel, it rejects every request until you supply an `allow` callback. The handler receives the sandbox's ID and name in place of `props`; use the name to look up per-sandbox settings in your own store.

Check the destination of requests that the rule does not forward. When a rule uses `match`, unmatched requests go directly to the destination. End the rule list with a `response` rule if those requests must be rejected.

Some handlers also need a change to where they run:

- For logic that uses Workers bindings such as KV or R2, point `forwardURL` at a Worker route that verifies the `vercel-sandbox-oidc-token` header.
  
- Forwarding requires HTTPS, so a handler serving plain HTTP requests for a hostname local to the container needs an HTTPS endpoint on Vercel.
  

### Authenticated previews and raw TCP

Vercel port URLs are public. To replace preview authentication in your Worker, 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](#check-that-your-service-is-ready). 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.

#### Retain share links and isolate browser previews

To keep expiring share links or a custom preview domain, retain a Worker or backend route that checks the share token and adds the sandbox's bearer token when forwarding requests. 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.

Vercel port URLs support HTTP and WebSockets. Raw TCP connections through Cloudflare's `getTcpPort()` and `connect()` need another service or protocol.

### State in Durable Object storage

Vercel Sandbox stores each sandbox's name and tags. Move other application state from the Durable Object to your database, keyed by sandbox name:

- Replace the snapshot IDs and backup records for persistent workspaces with their sandbox names.
  
- Move session records and share tokens into the database.
  
- Replace alarms with scheduled checks in a backend scheduler or worker.
  

Durable Objects also coordinate each sandbox's requests in one place. If two requests can reach the same Vercel sandbox at once, add a lock or queue around operations that must not overlap. When an agent built with Cloudflare's Agents SDK owns the container, move sandbox calls into its tools. The [Vercel Sandbox ecosystem](https://vercel.com/docs/sandbox/ecosystem) lists agent frameworks with built-in integrations.

### Mounted R2 buckets

Vercel Sandbox has no built-in replacement for `S3Mount`. When sandboxes are the only readers and writers, move the files to a Drive as shown in step 7. If other systems use the bucket, choose between copying fixed inputs for each job and running a Filesystem in Userspace (FUSE) client for jobs that need a mount. Check the client's file semantics against your application's requirements.

Unlike `S3Mount`, which keeps R2 credentials in the Worker, a FUSE client holds the R2 API token inside the sandbox. Limit that token to one bucket and use read-only access where possible.

#### Copy fixed inputs from R2

Download inputs to your local machine or a trusted worker with [rclone](https://developers.cloudflare.com/r2/examples/rclone/), then copy them into the sandbox. The commands assume an rclone remote named `r2`; replace `your-bucket` and the `inputs` prefix:

```bash
rclone copy r2:your-bucket/inputs ./migration-inputs

sandbox create --name bucket-reader --timeout 30m
sandbox copy --recursive ./migration-inputs \
  bucket-reader:/vercel/data
sandbox exec bucket-reader -- ls /vercel/data
sandbox stop bucket-reader
```

R2 credentials stay on the machine running the copy. This is a file transfer, so bucket updates won't appear automatically and sandbox writes won't upload to R2. Copy outputs back and upload them explicitly when needed. For datasets larger than the local disk, copy into a Drive mount instead. Hobby and Pro trial Drives are limited to 15 GB.

#### Share read-only files across sandboxes

To replace a read-only `S3Mount` across sandboxes, import the files into a Drive in step 7 and mount a [read-only Drive snapshot](https://vercel.com/docs/sandbox/concepts/drives#snapshots):

```bash
sandbox create --name reference-reader --region iad1 \
  --mount workspace-cache:/reference:snapshot
sandbox exec reference-reader -- ls /reference
sandbox stop reference-reader
```

Use the Drive's region if it differs from `iad1`. Each mount captures the files at attachment time, so create a new snapshot mount to read subsequent writes.

## Troubleshooting

Check these symptoms first when code ported from Cloudflare Sandbox behaves differently on Vercel Sandbox.

| 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 or file write fails with a permission error                                          | Commands run as the image's default user, without root's capabilities. Write under `/vercel`, or pass `sudo: true`.                                                                                                                                                                                                        |
| Pipes, redirection, or `$VARIABLES` reach the program as literal text                          | `runCommand()` doesn't use a shell. Wrap the command in `bash -c`. Check commands ported from Sandbox SDK 0.x's `sandbox.exec()`, which runs in a shell.                                                                                                                                                                   |
| A command fails because an earlier `cd` or `export` had no effect                              | Vercel commands share no shell state. Pass `cwd` and `env` to each `runCommand()`, or join the steps in one `bash -c` command.                                                                                                                                                                                             |
| A command can't find files it expects in `/workspace`                                          | Managed images use `/vercel` as the working directory and have no `/workspace` directory. Write under `/vercel`, or use a custom image that creates `/workspace`.                                                                                                                                                          |
| A sandbox or command times out much sooner than on Cloudflare                                  | Vercel's TypeScript SDK takes milliseconds. Multiply a numeric `sleepAfter` value from Sandbox SDK 0.x, which is in seconds, by 1,000.                                                                                                                                                                                     |
| The sandbox reaches hosts that it couldn't reach on Cloudflare                                 | Vercel's default policy is `allow-all`. Pass `networkPolicy` as `'deny-all'` or an allow list at creation.                                                                                                                                                                                                                 |
| A sandbox stops in the middle of a long job                                                    | Requests don't extend a Vercel session. Set a `timeout` that covers the job, or call `extendTimeout()` while it runs.                                                                                                                                                                                                      |
| Python output is `None`, or prints as `b'...'`                                                 | Pass `capture_output=True` to `run_command()`, then call `.decode()` on `stdout`.                                                                                                                                                                                                                                          |
| Requests to a sandbox URL return HTTP 410                                                      | The sandbox is stopped. Run a command to resume the sandbox, then restart your server.                                                                                                                                                                                                                                     |
| A server that ran before a stop isn't running after a resume                                   | Vercel restores files, not processes, and doesn't run an entrypoint. Start the server in `onCreate` and `onResume`, as shown in step 6.                                                                                                                                                                                    |
| Saved files are missing, or the first resume fails with `snapshot_not_found`                   | Check whether the snapshot expired or was deleted. `getOrCreate({ resume: true })` and Python's default `get_or_create_sandbox()` can create a replacement under the same name, so confirm that the expected files exist before continuing. Recover from an available backup and configure retention for future snapshots. |
| Creation fails with `snapshot_region_mismatch` or `drive_region_mismatch`                      | Create the sandbox in the same region as its snapshot or Drive.                                                                                                                                                                                                                                                            |
| Requests to an allowed domain's apex are blocked                                               | `*.example.com` doesn't match `example.com`. Add the apex domain to the allow list.                                                                                                                                                                                                                                        |
| A Docker container inside the sandbox fails TLS verification on a domain with a brokering rule | The container doesn't trust the sandbox's proxy CA. Follow [Trust the proxy CA in containers](https://vercel.com/docs/sandbox/concepts/security#trust-the-proxy-ca-in-containers).                                                                                                                                         |
| 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 Cloudflare.

### 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 Cloudflare Sandbox](https://vercel.com/kb/guide/vercel-sandbox-vs-cloudflare-sandbox) for your workload
  

## Frequently asked questions

### Can I move Cloudflare snapshots or R2 backups to Vercel Sandbox directly?

Not directly. Cloudflare doesn't return snapshot data to your Worker, so start an instance from the snapshot, archive the files, and download them through a Worker route. Files in an R2 bucket download through R2's S3-compatible API. Use `sandbox copy` to transfer the archive to Vercel, then extract it into the sandbox's workspace or a mounted Drive.

### Can my application stay on Cloudflare Workers after I migrate to Vercel Sandbox?

Yes. Sandbox control no longer needs a container on your Durable Object, so your Worker can forward sandbox requests to a backend that runs the Vercel Sandbox SDK, or call the Vercel REST API with an access token. Applications deployed on Vercel authenticate with the project's OIDC token instead.

### Do I need to move to Sandbox SDK 1.0 before I migrate to Vercel Sandbox?

No. Step 5 lists the Vercel Sandbox call for each main Sandbox SDK 0.x call, such as `getSandbox()`, `sandbox.exec()`, and `exposePort()`. Cloudflare ends bug and security fixes for Sandbox SDK 0.x on December 31, 2026, and deployed 0.x applications keep running after that date.

### Do I need to rebuild my Cloudflare images for Vercel Sandbox?

Custom images need their Dockerfile built into Vercel Container Registry with `vercel vcr build`. Remove the `sandbox-shim` line and any `sleep infinity` command first. You can replace Cloudflare's managed Debian image with a Vercel managed image when its runtime version and installed tools meet your workload's requirements.

### Does Vercel Sandbox block internet access by default like Sandbox SDK 1.0?

No. A Vercel sandbox starts with the `allow-all` policy. Pass `networkPolicy: 'deny-all'` or an allow list to `Sandbox.create()` to keep the behavior of `enableInternet: false`, and change the policy later with `sandbox.update()`.

### Does Vercel Sandbox have an inactivity timeout like setInactivityTimeout()?

No. Vercel sessions end at their timeout or when your code calls `stop()`, and persistent sandboxes save files either way. Requests don't extend sessions, so extend ongoing work with `extendTimeout()` or Python's `extend_execution_time_limit()`.

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

No. Vercel Sandbox restores files, not processes, and doesn't run an image's entrypoint. 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.

### Do commands run as root in Vercel Sandbox like they do on Cloudflare?

No. Vercel managed images run commands as the `ubuntu` or `arch` user with passwordless sudo. Pass `sudo: true` to `runCommand()`, or `sudo=True` to `run_command()`, for commands that need root.

### Can I control Vercel Sandbox from Python?

Yes. Cloudflare's container API runs in a Worker, and Vercel provides SDKs for TypeScript and Python. The `vercel-sandbox` package supports Python 3.11 or later with asynchronous and synchronous APIs. The Python SDK uses different names, including `execution_time_limit` instead of TypeScript's `timeout`.

## Related Resources

- [Vercel Sandbox vs Cloudflare Sandbox](/kb/guide/vercel-sandbox-vs-cloudflare-sandbox): Compare Vercel Sandbox and Cloudflare Sandbox as AI agent sandboxes, including isolation, persistence, network controls, SDKs, and deployment options.

## 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 Upstash Box to Vercel Sandbox](/kb/guide/migrate-from-upstash-box-to-vercel-sandbox): Migrate from Upstash Box to Vercel Sandbox in TypeScript or Python, including runtimes, persistent files, network policies, agents, 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>
```
