---
title: Migrate from Modal Sandboxes to Vercel Sandbox
description: Migrate from Modal Sandboxes to Vercel Sandbox in TypeScript or Python, including images, persistent files, network policies, and a staged cutover.
keywords: ["Vercel Sandbox","Modal Sandboxes","migrate from Modal","AI agent sandbox","sandbox migration","untrusted code execution"]
url: "https://vercel.com/kb/guide/migrate-from-modal-sandboxes-to-vercel-sandbox"
published: 2026-11-30
last_updated: 2026-11-30
authors: Ben Sabic
related_resources:
  - title: "Vercel Sandbox vs Modal Sandboxes"
    url: "/kb/guide/vercel-sandbox-vs-modal-sandboxes"
    description: "Compare Vercel Sandbox and Modal Sandboxes as AI agent sandboxes, including isolation, persistence, network controls, GPUs, SDKs, and deployment regions."
install_vercel_plugin: npx plugins add vercel/vercel-plugin
search_with_vercel_cli: npx vercel@latest kb search "<query>"
read_with_vercel_cli: "npx vercel@latest kb inspect migrate-from-modal-sandboxes-to-vercel-sandbox"
---

To move sandbox workloads from [Modal Sandboxes](https://modal.com/docs/guide/sandboxes) to [Vercel Sandbox](https://vercel.com/docs/sandbox), update your application's sandbox calls to use Vercel's TypeScript or Python SDK. The migration also involves adapting image setup, file persistence, and network rules to preserve the behavior your application needs.

On Modal, retaining root filesystem changes requires a snapshot or beta [Exit Snapshots](https://modal.com/docs/guide/sandbox-exit-snapshots). Vercel preserves files by default when a persistent sandbox stops, so your application can resume it by name. Your application must restart its processes after resuming. Review the [migration limitations](#what-doesn%27t-map-from-modal-sandboxes) before starting, especially if your application also relies on GPUs, idle timeouts, or memory snapshots.

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

### Agent prompt

```txt
Migrate this codebase from Modal Sandboxes to Vercel Sandbox.

1. Read and follow the migration guide using the Vercel CLI: `npx vercel@latest kb inspect migrate-from-modal-sandboxes-to-vercel-sandbox`.
2. Inventory Modal imports and call sites, including images, commands, files, snapshots, Volumes, tunnels, secrets, network rules, and resource settings. Preserve the application's language and authorization checks.
3. Identify features that need a different design, including GPUs, resource bursting, idle timeouts, readiness checks, memory or directory snapshots, Sidecars, authenticated ingress, and bucket mounts. 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 Modal path available until I approve cutover.
5. Port one call site at a time. Check units, paths, users, file-argument order, 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 Modal data or 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 Modal Sandboxes features map to Vercel Sandbox

Modal Apps map to Vercel projects, and Drives provide persistent storage in place of Modal Volumes. Other features, such as GPUs and memory snapshots, require a [different approach](#what-doesn%27t-map-from-modal-sandboxes). Before migrating, [compare Vercel Sandbox and Modal Sandboxes](https://vercel.com/kb/guide/vercel-sandbox-vs-modal-sandboxes) for your workload.

You can keep using Python or TypeScript. The mappings use Python parameter names for Modal and TypeScript names for Vercel.

### Projects, images, and compute

Replace the Modal App with a Vercel project and select an image.

| Modal Sandboxes                                                                                         | Vercel Sandbox                                                                                                                             | What you change                                                                                                              |
| ------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- |
| App from `modal.App.lookup()` or `modal.apps.fromName()`                                                | Vercel project                                                                                                                             | Remove the App lookup. Each sandbox belongs to the project that issued its credentials.                                      |
| API token in `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET`                                                  | [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.                                                               |
| [Modal Image](https://modal.com/docs/guide/images) built in code, from a Dockerfile, or from a registry | [Managed image](https://vercel.com/docs/sandbox/concepts/images), or a custom OCI image in Vercel Container Registry                       | Build custom images from a Dockerfile. Vercel Sandbox doesn't run an image's `ENTRYPOINT` or `CMD`.                          |
| Entrypoint command passed to `Sandbox.create()`                                                         | `runCommand()` with `detached: true`                                                                                                       | Start the process after creation. Stop the sandbox when the command ends if it should keep the Modal entrypoint's lifecycle. |
| `cpu` in physical cores and `memory` in MiB, with bursting                                              | `resources.vcpus`, with 2 GB of memory per vCPU                                                                                            | Modal's `cpu=1` equals 2 vCPUs. Size for peak use, because a Vercel sandbox has a fixed size.                                |
| `gpu`                                                                                                   | No equivalent                                                                                                                              | Call hosted models over the network, for example through [AI Gateway](https://vercel.com/docs/ai-gateway).                   |
| `region` or `regions`, with broad values such as `us` or narrow values such as `us-west`                | `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.     |
| Commands run as root                                                                                    | 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 tracking that a Modal application does in its own code.

| Modal Sandboxes                                                                                   | Vercel Sandbox                                                                         | What you change                                                                                                                                                     |
| ------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `timeout` and `idle_timeout`                                                                      | `timeout` in the TypeScript SDK, or `execution_time_limit` in the Python SDK           | Convert the units. Vercel Sandbox has no idle timeout, so stop the sandbox from your code.                                                                          |
| Lifetime of up to 24 hours for each Sandbox                                                       | 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()`.                                                                          |
| `sb.terminate()`, which discards root filesystem changes unless Exit Snapshots are enabled        | `sandbox.stop()`, which saves the filesystem, or `sandbox.delete()`                    | Pass `persistent: false` for disposable sandboxes.                                                                                                                  |
| `sb.snapshot_filesystem()` or opt-in Exit Snapshots, which produce an Image for later restoration | Automatic snapshot on stop, or a manual `sandbox.snapshot()`                           | Reconnect by sandbox name. Store a snapshot ID only to seed new sandboxes.                                                                                          |
| `Sandbox.from_name()` and `Sandbox.from_id()`                                                     | `Sandbox.get({ name })`                                                                | Look up sandboxes by name. The next command resumes a stopped sandbox.                                                                                              |
| Several Sandboxes created from one snapshot Image                                                 | `source: { type: 'snapshot', snapshotId }`, or `Sandbox.fork()`                        | A fork starts from the source sandbox's latest saved snapshot.                                                                                                      |
| Memory snapshots, in alpha                                                                        | No equivalent                                                                          | After each resume, restart processes, for example with the TypeScript SDK's `onResume` hook.                                                                        |
| [Volumes](https://modal.com/docs/guide/sandbox-files)                                             | [Drives](https://vercel.com/docs/sandbox/concepts/drives), up to four for each sandbox | Each Drive allows one writable mount at a time. The sandbox's region must match the Drive's region.                                                                 |
| Cloud Bucket Mounts                                                                               | No equivalent                                                                          | Copy files for jobs that use a fixed input set, or configure a FUSE client when a mounted bucket is required. See [bucket migration options](#cloud-bucket-mounts). |
| Up to 10 tags                                                                                     | Up to five `tags`                                                                      | Reduce the tag set, or put extra metadata in the sandbox name.                                                                                                      |

### Networking and secrets

The firewall's `networkPolicy` option replaces Modal's separate network parameters, and public port URLs replace tunnels.

| Modal Sandboxes                             | Vercel Sandbox                                                                                          | What you change                                                                                                          |
| ------------------------------------------- | ------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `encrypted_ports` and `sb.tunnels()`        | `ports` and `sandbox.domain(port)`                                                                      | List up to 15 ports at creation. Anyone with a port's URL can reach it.                                                  |
| Connect Tokens and `inbound_cidr_allowlist` | No equivalent                                                                                           | Authenticate callers in the server that runs inside the sandbox.                                                         |
| `block_network`                             | `networkPolicy: 'deny-all'`                                                                             | `deny-all` also blocks DNS.                                                                                              |
| `outbound_domain_allowlist`                 | `networkPolicy: { allow: [...] }`                                                                       | On Vercel, `*.example.com` doesn't match `example.com`. List the apex domain separately.                                 |
| `outbound_cidr_allowlist`                   | `networkPolicy: { subnets: { allow: [...] } }`                                                          | Denied CIDR ranges take precedence over allowed domains and ranges.                                                      |
| Runtime policy updates, in alpha            | `sandbox.update({ networkPolicy })`                                                                     | Each update replaces the whole policy.                                                                                   |
| `secrets` with `modal.Secret`               | `env`, at creation or for each command                                                                  | Read the values in your application and pass them in.                                                                    |
| Outbound Policy header replacement, in beta | [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.                                   |
| Proxies with static IPs, in beta            | [Secure Compute](https://vercel.com/docs/sandbox/concepts/secure-compute) network, set with `networkId` | Secure Compute is an additional Enterprise purchase.                                                                     |
| Sidecars, in beta                           | No equivalent                                                                                           | Use a separate sandbox when the component requires its own isolation. See the Sidecar limitations below for other cases. |

## Steps

### 1\. Find where your application uses Modal Sandboxes

Search for Modal imports and call sites, then trace aliases through your code. Match the results to the steps below and identify features that need a replacement.

```bash
grep -rnE \
  "ModalClient|modal[.(]|['\"]modal['\"]|(from|import) modal" \
  --include="*.py" --include="*.ts" --include="*.tsx" \
  --include="*.js" --include="*.mjs" \
  --exclude-dir=node_modules --exclude-dir=.venv \
  --exclude-dir=venv .
```

Match what you find to the steps that follow:

| In your code                                                                              | Go to                                                                             |
| ----------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| `modal.Image` builder calls, `from_registry()`, or `dockerfileCommands()`                 | [Step 4](#4.-move-your-modal-image-to-a-vercel-image)                             |
| `Sandbox.create()`, `exec()`, or `sb.filesystem`                                          | [Step 5](#5.-replace-sandbox-creation,-commands,-and-file-operations)             |
| `snapshot_filesystem()`, `Image.from_id()`, or `Sandbox.from_name()`                      | [Step 6](#6.-replace-snapshot-tracking-with-named-sandboxes)                      |
| `modal.Volume` or the `volumes` parameter                                                 | [Step 7](#7.-move-volumes-to-drives)                                              |
| `encrypted_ports` or `sb.tunnels()`                                                       | [Step 8](#8.-replace-tunnels-with-public-ports)                                   |
| `block_network`, an outbound allowlist, `modal.Secret`, or an Outbound Policy             | [Step 9](#9.-replace-modal-network-parameters,-secrets,-and-the-outbound-policy)  |
| `gpu`, `idle_timeout`, memory snapshots, Sidecars, Connect Tokens, or Cloud Bucket Mounts | [What doesn't map from Modal Sandboxes](#what-doesn%27t-map-from-modal-sandboxes) |

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

The development OIDC token expires after 12 hours. Run `vercel env pull` again to refresh it. Applications deployed on Vercel receive automatically managed tokens.

Load `.env.local` for local runs. Node.js uses `--env-file=.env.local`, and the Python sample loads it with `python-dotenv`.

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 Modal credentials until the migrated workloads pass verification. Retain credentials used by workloads remaining on Modal.

### 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 `modal` package until no workloads use it.

### 4\. Move your Modal Image to a Vercel image

Replace your Modal 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:

| Modal Image                                                                  | Vercel replacement                                                                                                                                                                                                                                  |
| ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `debian_slim()`, or a stock registry image such as `python:3.13-slim`        | A managed image such as `vercel/sandbox/python:3.14` or `vercel/sandbox/node:24`. With no `image`, a sandbox uses `vercel/sandbox/universal`, which includes current Node.js LTS and Python versions. To stay on Python 3.13, build a custom image. |
| Builder calls such as `pip_install()`, `apt_install()`, and `run_commands()` | A Dockerfile with the matching `RUN` instructions, built into Vercel Container Registry                                                                                                                                                             |
| `from_dockerfile()` or `dockerfileCommands()`                                | The same Dockerfile instructions, built into Vercel Container Registry                                                                                                                                                                              |
| A named Image from `Image.from_name()`                                       | A repository and tag in Vercel Container Registry                                                                                                                                                                                                   |

If a managed image meets your needs, continue to [sandbox creation](#5.-replace-sandbox-creation,-commands,-and-file-operations). For a custom image, install Docker and put the Modal build steps in a Dockerfile:

```docker
FROM python:3.13-slim
RUN apt-get update && apt-get install -y git
RUN pip install pandas
WORKDIR /workspace
```

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

Check these differences from Modal Images:

- **Architecture**: A custom image must target `linux/amd64`.
  
- **Startup commands**: Vercel Sandbox doesn't run an image's `ENTRYPOINT` or `CMD`. Start those processes with `runCommand()` after creation.
  
- **Working directory**: A custom image uses its Dockerfile `WORKDIR`, or `/` when none is set. Managed images use `/vercel`.
  
- **Size:** The registry allows 15 GB per image and 2 GB per compressed layer.
  

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 sandbox creation, commands, and file operations

Replace Modal's creation, command, and file calls with the corresponding Vercel methods. `Sandbox.create()` uses project credentials and an image reference instead of App and Image objects.

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

#### TypeScript SDK calls

| Task                          | Modal Sandboxes                                          | Vercel Sandbox                                                                         |
| ----------------------------- | -------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| Import                        | `import { ModalClient } from 'modal'`                    | `import { Sandbox } from '@vercel/sandbox'`                                            |
| Create a client               | `new ModalClient()` and `modal.apps.fromName()`          | No client or App object                                                                |
| Create a sandbox              | `modal.sandboxes.create(app, image, params)`             | `Sandbox.create(params)`                                                               |
| Set the lifetime              | `timeoutMs`                                              | `timeout`, in milliseconds                                                             |
| Set resources                 | `cpu` and `memoryMiB`                                    | `resources: { vcpus }`                                                                 |
| Run a command                 | `sb.exec(['python', 'main.py'])`                         | `sandbox.runCommand('python', ['main.py'])`                                            |
| Read output                   | `await p.stdout.readText()`                              | `await result.stdout()`                                                                |
| Get the exit code             | `await p.wait()`                                         | `result.exitCode`                                                                      |
| Write a file                  | `sb.filesystem.writeText(data, path)`                    | `sandbox.writeFiles([{ path, content }])`                                              |
| Read a file                   | `sb.filesystem.readText(path)`                           | `sandbox.fs.readFile(path, 'utf8')`, or `sandbox.readFileToBuffer({ path })` for bytes |
| List, create, or remove paths | `listFiles()`, `makeDirectory()`, and `remove()`         | `sandbox.fs.readdir()`, `sandbox.fs.mkdir()`, and `sandbox.fs.rm()`                    |
| Find a sandbox                | `modal.sandboxes.fromName(appName, name)`                | `Sandbox.get({ name })`                                                                |
| List sandboxes                | `modal.sandboxes.list({ tags })`, which matches all tags | `Sandbox.list({ tags })`, which filters on one tag                                     |
| End a sandbox                 | `sb.terminate()`                                         | `sandbox.stop()` or `sandbox.delete()`                                                 |

On Modal, a script looks up an App, defines an Image, and passes both to `create()`:

```javascript
import { ModalClient } from 'modal';

const modal = new ModalClient();
const app = await modal.apps.fromName('agent-sandboxes', {
  createIfMissing: true,
});
const image = modal.images.fromRegistry('python:3.13-slim');

const sb = await modal.sandboxes.create(app, image, {
  timeoutMs: 10 * 60 * 1000,
  cpu: 1,
  memoryMiB: 4096,
  env: { PYTHONUNBUFFERED: '1' },
});

try {
  await sb.filesystem.writeText('print(21 * 2)', '/tmp/main.py');

  const p = await sb.exec(['python', '/tmp/main.py'], { timeoutMs: 60_000 });
  console.log(await p.stdout.readText());
  console.log('exit code', await p.wait());
} finally {
  await sb.terminate();
}
```

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

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

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

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

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

The Vercel script uses the default image and a fixed 2-vCPU size. Modal's `cpu: 1` requests one physical core, equivalent to 2 vCPUs, while `memoryMiB: 4096` requests at least 4 GiB and can burst above it. Check peak CPU and memory use before choosing the Vercel size for your workload. `persistent: false` keeps this example's behavior of discarding files when the sandbox stops.

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

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

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

#### Python SDK calls

| Task                          | Modal Sandboxes                                    | Vercel Sandbox                                              |
| ----------------------------- | -------------------------------------------------- | ----------------------------------------------------------- |
| Import                        | `import modal`                                     | `from vercel import sandbox`                                |
| Create a sandbox              | `modal.Sandbox.create(app=app, image=image)`       | `sandbox.create_sandbox()`                                  |
| Set the lifetime              | `timeout`, in seconds                              | `execution_time_limit`, in seconds or as a `timedelta`      |
| Set resources                 | `cpu` and `memory`                                 | `resources=SandboxResources(vcpus=2, memory=4096)`          |
| Run a command                 | `sb.exec("python", "main.py")`                     | `box.run_command("python", ["main.py"])`                    |
| Read output                   | `p.stdout.read()`                                  | `result.stdout.decode()`, with `capture_output=True`        |
| Get the exit code             | `p.wait()` or `p.returncode`                       | `result.returncode`                                         |
| Write a file                  | `sb.filesystem.write_text(data, path)`             | `box.fs.write_text(path, text)`                             |
| Read a file                   | `sb.filesystem.read_text(path)`                    | `box.fs.read_text(path)`                                    |
| List, create, or remove paths | `list_files()`, `make_directory()`, and `remove()` | `box.fs.listdir()`, `box.fs.mkdir()`, and `box.fs.remove()` |
| Find a sandbox                | `modal.Sandbox.from_name(app_name, name)`          | `sandbox.get_sandbox(name=name)`                            |
| List sandboxes                | `modal.Sandbox.list(tags=tags)`                    | `sandbox.query_sandboxes()`                                 |
| End a sandbox                 | `sb.terminate()`                                   | `box.stop()` or `box.destroy()`                             |

Modal's synchronous Python client performs the same operations:

```python
import modal

app = modal.App.lookup("agent-sandboxes", create_if_missing=True)
image = modal.Image.debian_slim(python_version="3.13")

sb = modal.Sandbox.create(
    app=app,
    image=image,
    timeout=10 * 60,
    cpu=1,
    memory=4096,
    env={"PYTHONUNBUFFERED": "1"},
)

try:
    sb.filesystem.write_text("print(21 * 2)", "/tmp/main.py")

    p = sb.exec("python", "/tmp/main.py", timeout=60)
    print(p.stdout.read(), end="")
    print("exit code", p.wait())
finally:
    sb.terminate()
```

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

```python
import asyncio

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


load_dotenv(".env.local")


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

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


asyncio.run(main())
```

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

```bash
python sandbox_example.py
```

The script prints `42` and `exit code 0`. Its `async with` block stops and destroys the sandbox on exit, which matches `sb.terminate()`.

To preserve files, set `persistent=True` and `destroy=False` in `create_sandbox()` so the context manager stops and saves the sandbox on exit. Alternatively, 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

- **Time units**: Modal's Python SDK takes seconds, and its JavaScript SDK takes milliseconds in `timeoutMs`. Vercel's TypeScript SDK takes milliseconds in `timeout`, `timeoutMs`, and `extendTimeout()`. Vercel's Python SDK takes seconds or a `timedelta` in `execution_time_limit` and `kill_after`.
  
- **Command arguments:** Pass the binary first and its arguments as an array. Vercel does not start a shell, so retain `bash -c` where your command needs pipes, redirection, or variable expansion.
  
- **Write argument order**: Modal's `write_text()` takes the content first and the path second. Vercel's `box.fs.write_text()` takes the path first.
  
- **Paths**: Modal's `sb.filesystem` requires absolute paths. On Vercel managed images, relative paths resolve from `/vercel`.
  
- **User**: Modal runs commands as root. Vercel managed images run commands as `ubuntu` or `arch` with passwordless sudo, so pass `sudo: true` or `sudo=True` for commands that need root.
  
- **Output**: Modal's Python `exec()` returns text by default. Vercel's Python `run_command()` streams output to your local stdout unless you pass `capture_output=True`, and captured output is `bytes`.
  
- **Persistence**: Vercel sandboxes are persistent by default, and each stop saves a snapshot that counts toward Snapshot Storage. Pass `persistent: false` or `persistent=False` for one-off sandboxes.
  

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

Modal stops its Sandbox when the entrypoint 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.

Connections close after 340 seconds without data while the command keeps running. Use the [long-running task pattern](https://vercel.com/docs/sandbox/examples/execute-long-running-tasks) for longer, quiet jobs.

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

Use a named persistent sandbox in place of saving and tracking a Modal filesystem snapshot for each agent session.

#### Reconnect to a sandbox by name

For manual snapshots on Modal, your application saves an Image before terminating the Sandbox and restores that Image into a new Sandbox. The excerpt assumes that `snapshot_store` is your application's persistent mapping of session IDs to Image IDs, and that `app`, `sb`, and `session_id` identify the current session.

```python
# End of an agent session
image = sb.snapshot_filesystem()
snapshot_store[session_id] = image.object_id
sb.terminate()

# Next agent session
image = modal.Image.from_id(snapshot_store[session_id])
sb = modal.Sandbox.create(app=app, image=image)
```

For Modal's beta Exit Snapshots, call `sb._experimental_get_exit_snapshot()` after the Sandbox exits to retrieve the Image. Then [export its files to Vercel](#copy-files-from-existing-modal-snapshots).

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}` });
await sandbox.writeFiles([
  { path: 'notes.txt', content: Buffer.from('draft') },
]);
await sandbox.stop();

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

**Vercel Sandbox (Python)**

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

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

Both Vercel samples print `draft`. After the migration, your application stores the sandbox name instead of a table of Image IDs. Check these behaviors:

- **Names**: A sandbox name is unique within its project and can't change.
  
- **Session timeout**: Each resume starts a new session with a new timeout.
  
- **Expiration:** 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` to disable expiry.
  
- **Cleanup:** Sandbox deletion preserves snapshots by default. To delete those no other sandbox uses, enable `deleteOrphanSnapshots` in `sandbox.delete()` or `delete_orphan_snapshots` in Python's `box.destroy()`.
  

#### Restart processes after a resume

Resuming restores files, 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 start many sandboxes from one prepared environment, as you would from one Modal snapshot Image, take a snapshot and pass its ID as the `source`:

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

const snapshot = await base.snapshot();

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

Calling `base.snapshot()` saves files and stops the session. Use `Sandbox.fork()` with a `sourceSandbox` name to fork that sandbox's latest snapshot.

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()` to create the base sandbox. Using `async with` destroys it and its unused snapshots on exit. To create new sandboxes from the snapshot, pass `snapshot.id` as `snapshot_id` to `SnapshotSource`, or use `sandbox.fork_sandbox()` to fork by name.

#### Copy files from existing Modal snapshots

Vercel Sandbox can't read a Modal snapshot Image, so restore the Image in Modal and archive the session files you need. This example uses your application's `app`, `snapshot_store`, and `session_id` and assumes those files live in `/workspace`. Set `source_dir` to your application's directory; rebuild system packages and image dependencies in step 4.

```python
image = modal.Image.from_id(snapshot_store[session_id])
sb = modal.Sandbox.create(app=app, image=image, timeout=30 * 60)
source_dir = "/workspace"

try:
    p = sb.exec("tar", "-czf", "/tmp/workspace.tgz", "-C", source_dir, ".")
    if p.wait() != 0:
        raise RuntimeError(p.stderr.read())
    sb.filesystem.copy_to_local("/tmp/workspace.tgz", "./workspace.tgz")
finally:
    sb.terminate()
```

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

Create the Vercel sandbox and extract the archive. Run these commands from the linked project, or select one with `--project` and `--scope`:

```bash
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 stop session-123
```

Each sandbox keeps the image it was created with. If your application uses a custom image, add `--image agent-runtime:latest` to `sandbox create`, and extract into that image's working directory instead of `/vercel`. Modal's file API reads files of up to 5 GB, so split larger archives.

### 7\. Move Volumes to Drives

Use a [Drive](https://vercel.com/docs/sandbox/concepts/drives) in place of a Modal Volume for storage that outlives a sandbox and mounts as a directory.

```python
vol = modal.Volume.from_name("workspace-cache", create_if_missing=True)
sb = modal.Sandbox.create(app=app, volumes={"/cache": vol})
```

Install `@vercel/drives` for JavaScript. Python includes Drive operations in its SDK:

**pnpm**

```bash
pnpm add @vercel/drives
```

**yarn**

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

**npm**

```bash
npm install @vercel/drives
```

**bun**

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

Measure your files before creating the Drive because its size limit cannot change later. Defaults are 1 TB on Pro and Enterprise, or 1 GB on Hobby and Pro trials. Set `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},
)
```

Check these differences from Volumes:

- **One writer:** Each Drive allows one writable mount. Concurrent readers can mount `drive.snapshot()` for a read-only view of the files at that point in time.
  
- **No reload call**: Remove `reload_volumes()`. Drive snapshots don't see later writes, so mount a new snapshot to read newer files.
  
- **Fixed region and size**: A Drive's region and maximum size can't change after creation, and new Drives default to `iad1`.
  
- **Mount limit:** Mount up to four Drives at non-overlapping absolute paths.
  

Before the final export, stop or pause the Volume's writers and wait for their commits. Using the existing Modal `app`, mount `workspace-cache` at `/cache`, archive its files, and download the archive:

```python
vol = modal.Volume.from_name("workspace-cache")
sb = modal.Sandbox.create(app=app, volumes={"/cache": vol}, timeout=30 * 60)

try:
    p = sb.exec("tar", "-czf", "/tmp/workspace.tgz", "-C", "/cache", ".")
    if p.wait() != 0:
        raise RuntimeError(p.stderr.read())
    sb.filesystem.copy_to_local("/tmp/workspace.tgz", "./workspace.tgz")
finally:
    sb.terminate()
```

If you ran the SDK mount example, await `sandbox.stop()` in TypeScript or `box.stop()` in Python. This releases its writable Drive mount before importing.

Verify the archive's contents, then copy it into a sandbox that mounts the Drive and extract the files into `/cache`:

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

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

### 8\. Replace tunnels with public ports

The `ports` option and `sandbox.domain()` replace Modal's `encryptedPorts` option, which is `encrypted_ports` in Python, and `sb.tunnels()`.

```javascript
const sb = await modal.sandboxes.create(app, image, {
  command: ['python', '-m', 'http.server', '8000'],
  encryptedPorts: [8000],
});

const tunnel = (await sb.tunnels())[8000];
console.log(tunnel.url);
```

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

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

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

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

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

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

Check these differences from tunnels:

- **Public URLs**: Anyone with a port's URL can reach the port. Authenticate callers in your server, because Vercel Sandbox has no equivalent to Connect Tokens.
  
- **Stopped sandboxes**: Requests to a stopped sandbox's URL return HTTP 410. Resume the sandbox with a command before you send traffic, then restart the server as shown in step 6.
  
- **Port changes:** `sandbox.update({ ports })` replaces the exposed port list.
  

### 9\. Replace Modal network parameters, Secrets, and the Outbound Policy

#### Map network parameters to a network policy

Use `networkPolicy` to replace Modal's network blocking and outbound allowlists:

| Modal parameter                                                | Vercel `networkPolicy`                                        |
| -------------------------------------------------------------- | ------------------------------------------------------------- |
| No network parameters                                          | `'allow-all'`, the default                                    |
| `block_network=True`                                           | `'deny-all'`                                                  |
| `outbound_domain_allowlist=["api.openai.com", "*.github.com"]` | `{ allow: ['api.openai.com', 'github.com', '*.github.com'] }` |
| `outbound_cidr_allowlist=["10.0.1.0/24"]`                      | `{ subnets: { allow: ['10.0.1.0/24'] } }`                     |

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', '*.github.com'],
  },
});

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

**Vercel Sandbox (Python)**

```python
from vercel.sandbox import NetworkPolicy

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

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

Vercel's `*.github.com` rule covers subdomains only. Add `github.com` to preserve Modal's wildcard behavior, which includes the apex domain. Both products use the TLS hostname for domain matching; plain HTTP needs an IP-based rule.

#### Pass Secrets as environment variables

Modal Secrets inject environment variables. 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 Modal's Outbound Policy with a brokering rule, which adds the header after the request leaves the sandbox:

**Modal Sandboxes (Python)**

```python
import modal.experimental

policy = modal.experimental.OutboundPolicy().with_header_replacement(
    domain="api.example.com",
    secret=modal.Secret.from_name("api-token"),
    headers={"Authorization": "Bearer $API_TOKEN"},
)

sb = modal.Sandbox.create(app=app, _experimental_outbound_policy=policy)
```

**Vercel Sandbox (TypeScript)**

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

**Vercel Sandbox (Python)**

```python
import os

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

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

Check these differences from the Outbound Policy:

- **Allow lists**: Modal's Outbound Policy can't be combined with an allowlist. Vercel's `networkPolicy` combines brokering rules with an allow list. Remove the `'*'` entry to block every domain that the policy doesn't name.
  
- **Request matching:** Add a `match` on path, method, query string, or headers to limit which requests receive the credential. 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` to reject the rest.
  
- **Plans**: Brokering rules are available on Pro and Enterprise plans.
  

### 10\. Verify and cut over

Run both providers side by side before you remove Modal:

1. Run a representative workload on both providers, then compare the output, exit codes, and written files.
   
2. 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.
   
3. Check your concurrency and creation rate against the plan quotas. Hobby allows 10 concurrent sandboxes. Pro and Enterprise allow 10,000, with a vCPU allocation rate that starts at 150 vCPUs per minute and ramps to 5,000.
   
4. 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.
   
5. Record which provider owns each existing session and keep its requests on that provider while you migrate its state.
   
6. Pause writes to the session workspaces and Volumes being moved. Save final filesystem snapshots and wait for Volume commits before exporting. Import and verify the files before routing those sessions to Vercel.
   
7. Switch the flag for new sessions and monitor output and errors. Keep existing Modal sessions on Modal until they finish or their state has been imported.
   
8. If you roll back, send new sessions to Modal. Before moving a session that has written files on Vercel back to Modal, copy and verify those changes. Retain both providers' state until the rollback period ends.
   
9. After the rollback period, remove only the Modal call sites and data that migrated workloads no longer need. Keep Images, Volumes, and Secrets used by workloads remaining on Modal. Remove the package and revoke its credentials only after confirming that no other application or job uses them.
   

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

## What doesn't map from Modal Sandboxes

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

### GPUs

Vercel Sandbox provides CPU and memory. Keep training, custom CUDA code, and other jobs that require a local GPU on Modal or another GPU service. If you use the GPU to run inference with a supported model, move that call to [AI Gateway](https://vercel.com/docs/ai-gateway) and keep preprocessing or code execution in Vercel Sandbox.

For example, make this text-generation request from your application or terminal. Configure `AI_GATEWAY_API_KEY` using the [API key setup](https://vercel.com/docs/ai-gateway/getting-started#create-an-api-key) first. Running the request consumes AI Gateway credits:

```bash
curl --fail-with-body https://ai-gateway.vercel.sh/v1/chat/completions \
  -H "Authorization: Bearer $AI_GATEWAY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-6-astra",
    "messages": [
      {"role": "user", "content": "Summarize: The shipment arrives Friday."}
    ]
  }'
```

Choose a model that meets your workload's requirements. AI Gateway routes requests to hosted models; it doesn't execute arbitrary GPU code or move your trained weights from Modal.

### Resource bursting and disk size

Vercel sandboxes have 1 vCPU or an even number up to 32, with 2 GB of memory per vCPU. Modal treats `cpu` and `memory` as guaranteed minimums and permits bursting. Choose a fixed Vercel size that covers peak use and fits your plan.

For a worker that needs 4 vCPUs, 8 GB of memory, and more than the sandbox's 64 GB local disk, create a [Drive](https://vercel.com/docs/drives/cli-reference#vercel-drives-get-or-create) and mount it at `/data`. These commands create a 100 GiB Drive on a Pro or Enterprise plan and a sandbox in the same region:

```bash
vercel drives get-or-create migration-data \
  --region iad1 --max-size 100GiB

sandbox create --name migration-worker \
  --vcpus 4 --timeout 30m --region iad1 \
  --mount migration-data:/data
```

The Drive stores files separately from the sandbox's local disk. Write large datasets under `/data`, then stop the worker with `sandbox stop migration-worker` when work finishes. Only one sandbox can hold the Drive's writable mount at a time.

Modal's local disk quota is 512 GiB. Hobby and Pro trial Drives are limited to 15 GB, so use external storage when your plan's Drive capacity is too small. The Drive's region and size limit cannot change after creation.

### Idle timeouts and readiness probes

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

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

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

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

#### Check that your service is ready

Sandbox creation waits for the environment to accept commands, but your server may still be starting. Replace Modal's readiness probe with a health check that succeeds once the service and its dependencies are ready.

Save this Node.js helper as `wait-for-http.mjs`. Use it to check your 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.

### Memory and directory snapshots

Vercel snapshots preserve files, so Modal's alpha memory snapshots have no equivalent. Save progress that must survive a stop to a file, Drive, or database. On resume, start the process again and have it load that saved progress. Use the [process restart example](#restart-processes-after-a-resume) to attach startup logic to the sandbox lifecycle.

For Modal's directory snapshots, replace the `mount_image()` call with a [read-only Drive snapshot](https://vercel.com/docs/sandbox/concepts/drives#snapshots). After importing files into the `workspace-cache` Drive in step 7, mount them in a new sandbox:

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

### Sidecars

Modal's beta Sidecars run isolated containers on the Sandbox host. Use [firewall brokering rules](https://vercel.com/docs/sandbox/concepts/firewall#credentials-brokering) if your Sidecar adds credentials to outbound HTTP requests.

Set `SERVICE_AUTHORIZATION` in your trusted terminal environment to the complete header value, including the `Bearer` prefix if your service requires it. Replace `api.example.com` with the service's hostname, then create the sandbox:

```bash
sandbox create --name api-client \
  --request-header-from-env \
  'api.example.com:Authorization=SERVICE_AUTHORIZATION'
```

The CLI reads the secret from your local environment. The firewall adds it to requests for that hostname without putting it in the sandbox's environment. This policy allows only the named domain. For path- or method-specific access, configure [request matching](#broker-credentials-with-firewall-rules) in step 9.

Use a managed service or a second sandbox for a database or tool server that needs separate isolation. Authenticate requests between sandboxes; they communicate over the network and don't share localhost or a filesystem.

Docker containers and [Linux users](https://vercel.com/docs/sandbox/concepts/multi-agent) within one sandbox can separate cooperating processes. They share the sandbox's isolation boundary and don't provide the same separation as Modal Sidecars.

### Authenticated inbound access

Vercel port URLs are public. To replace Modal Connect Tokens, check a per-sandbox bearer token in your server and send requests only from your trusted backend. This authenticates outside callers. Code inside the sandbox can read the token 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}`. Missing or incorrect tokens return HTTP 401. Your backend must authorize each user's access before calling the sandbox.

Application-level token checks don't reproduce Modal's inbound IP allowlist. Vercel port URLs support HTTP and WebSocket traffic; raw TCP and HTTP/2 tunnels need a different service or protocol.

### Cloud Bucket Mounts

Vercel Sandbox has no built-in replacement for `CloudBucketMount`. Copy objects into the sandbox when a job can work from a fixed set of files. If it needs a mounted bucket, configure a Filesystem in Userspace (FUSE) client for the provider and check that its file semantics fit your application.

For S3, install and authenticate the [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) on your local machine or trusted worker. Replace `your-bucket` and the `inputs/` prefix below. Download the inputs there, then copy them into a sandbox:

```bash
aws s3 sync s3://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
```

AWS 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 S3. Copy outputs back and upload them explicitly when needed. For datasets larger than the local disk, copy into a Drive mount instead.

## Troubleshooting

Each symptom in this table traces to a behavior that differs between Modal Sandboxes and 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 instead of root. 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`.                                                                                                                                                                          |
| A sandbox or command times out much sooner than on Modal                  | Vercel's TypeScript SDK takes milliseconds. Multiply each value copied from Modal's Python SDK by 1,000.                                                                                                                                    |
| 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. Start the server in `onCreate` and `onResume`, as shown in step 6.                                                                                                                                    |
| The first call to a stopped sandbox fails with `snapshot_not_found`       | Check whether the snapshot is still available. If it has expired, create a replacement sandbox and restore files from an available backup. Configure retention for future snapshots; extending retention cannot recover a deleted snapshot. |
| 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                          | On Vercel, `*.example.com` doesn't match `example.com`. Add the apex domain to the allow list.                                                                                                                                              |
| 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 Modal.

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

Deploy the [Open Agents](https://vercel.com/templates/next.js/open-agents) template for a background coding agent, or the [eve Software Factory](https://vercel.com/templates/eve/eve-software-factory) template 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 with OpenAI Agents](https://vercel.com/kb/guide/v0-clone-openai-agents-vercel-sandbox) or deploy the [Vibe Coding Platform](https://vercel.com/templates/next.js/vibe-coding-platform) template.

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

## Frequently asked questions

### Can I move Modal snapshots or Volumes to Vercel Sandbox directly?

No. Export the files from a Modal Sandbox created from the snapshot or with the Volume mounted. Use `sandbox copy` to transfer the archive to Vercel, then extract it into the sandbox's workspace or mounted Drive.

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

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

### Can I keep GPU workloads on Modal and move the rest to Vercel Sandbox?

Yes. The `modal` and Vercel Sandbox SDKs are independent, so one application can call both. Move CPU-only Sandboxes to Vercel Sandbox, and keep the Sandboxes that set `gpu` on Modal.

### Do I need to rebuild my Modal Images for Vercel Sandbox?

Custom Images need a Dockerfile built into Vercel Container Registry with `vercel vcr build`. You can replace a stock Python or Node.js image with a Vercel managed image when its runtime version and installed tools meet your workload's requirements. Build a custom image if you need to preserve a version that the managed images don't provide.

### Can I migrate Modal Python code without switching to TypeScript?

Yes. The `vercel-sandbox` package supports Python 3.11 or later with asynchronous and synchronous APIs. The Python SDK's names differ from the TypeScript SDK's names, for example `execution_time_limit` instead of `timeout`.

### Does Vercel Sandbox have an idle timeout like Modal's idle_timeout?

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

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

No. Vercel Sandbox restores files, not processes. 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 Modal?

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.

## Related Resources

- [Vercel Sandbox vs Modal Sandboxes](/kb/guide/vercel-sandbox-vs-modal-sandboxes): Compare Vercel Sandbox and Modal Sandboxes as AI agent sandboxes, including isolation, persistence, network controls, GPUs, SDKs, and deployment regions.

## More Vercel Sandbox guides

- [Vercel Sandbox vs E2B](/kb/guide/vercel-sandbox-vs-e2b): Compare Vercel Sandbox and E2B as AI agent sandboxes, including isolation, persistence, network controls, SDKs, and deployment regions.
- [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.
- [Vercel Sandbox vs Modal Sandboxes](/kb/guide/vercel-sandbox-vs-modal-sandboxes): Compare Vercel Sandbox and Modal Sandboxes as AI agent sandboxes, including isolation, persistence, network controls, GPUs, SDKs, and deployment regions.

## Reference Architecture

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

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

[Browse all stacks](/kb/architecture)

## Build with prompts

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

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

## Search guides from your terminal

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

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

# Show the latest guides
npx vercel@latest kb

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