---
title: Migrate from Fly.io Sprites to Vercel Sandbox
description: Migrate from Fly.io Sprites to Vercel Sandbox in TypeScript or Python, including images, persistent files, public ports, network policies, and a staged cutover.
keywords: ["Vercel Sandbox","Fly.io Sprites","migrate from Fly.io Sprites","AI agent sandbox","sandbox migration","untrusted code execution"]
url: "https://vercel.com/kb/guide/migrate-from-fly-io-sprites-to-vercel-sandbox"
published: 2026-12-02
last_updated: 2026-12-02
authors: Ben Sabic
related_resources:
  - title: "Vercel Sandbox vs Fly.io Sprites"
    url: "/kb/guide/vercel-sandbox-vs-fly-io-sprites"
    description: "Compare Vercel Sandbox and Fly.io Sprites as AI agent sandboxes, including isolation, persistence, network controls, SDKs, and idle behavior."
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-fly-io-sprites-to-vercel-sandbox"
---

To move sandbox workloads from [Fly.io Sprites](https://fly.io/sprites/) 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 environment setup, session lifecycle, inbound URLs, and network rules to preserve the behavior your application needs.

Both products preserve files by default, with different session lifecycles. Sprites pause about 30 seconds after activity stops and wake on a command or HTTP request. When a persistent Vercel sandbox stops, it saves its files so your application can resume it by name; your application must restart its processes. Review the [migration limitations](#what-doesn%27t-map-from-fly.io-sprites) before starting, especially if your application relies on HTTP-triggered wake, Services, private Sprite URLs, or Connectors.

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

To export files from existing Sprites, keep the [Sprites CLI](https://docs.fly.io/sprites/cli/authentication) signed in to the Fly.io organization that owns them.

## Migrate with your agent

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

### Agent prompt

```txt
Migrate this codebase from Fly.io Sprites to Vercel Sandbox.

1. Read and follow the migration guide using the Vercel CLI: `npx vercel@latest kb inspect migrate-from-fly-io-sprites-to-vercel-sandbox`.
2. Inventory Sprites imports, `sprite` CLI calls, and REST calls, including Sprite creation, commands, files, checkpoints, Services, tasks, Sprite URLs, network policies, Connectors, and tokens. Read Services, network policies, URL settings, and labels from the live Sprites without changing them. Preserve the application's language and authorization checks.
3. Identify features that need a different design, including HTTP-triggered wake, idle pauses, processes that resume after a warm pause, Services, private Sprite URLs, live checkpoints, Connectors, and `sprite proxy`. 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 Sprites path available until I approve cutover.
5. Port one call site at a time. Check units, paths, users, output types, 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 Drive mounts, and reconcile changes if we roll back. Do not destroy Sprites, delete checkpoints, or revoke tokens.
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 Fly.io Sprites features map to Vercel Sandbox

Map the Fly.io organization to a Vercel project and use named persistent sandboxes for sessions that save files between runs. HTTP-triggered wake and warm pauses need a [different approach](#what-doesn%27t-map-from-fly.io-sprites). Check how those differences affect your workload in the [Sprites and Vercel Sandbox comparison](https://vercel.com/kb/guide/vercel-sandbox-vs-fly-io-sprites).

You can keep using Python or TypeScript. The mappings use JavaScript SDK and `sprite` CLI names for Sprites and TypeScript names for Vercel.

### Projects, images, and compute

Choose the Vercel project, image, and resources for your workload.

| Fly.io Sprites                                                          | Vercel Sandbox                                                                                                                             | What you change                                                                                                          |
| ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ |
| Fly.io organization that owns each Sprite                               | Vercel project                                                                                                                             | Each sandbox belongs to the project that issued its credentials.                                                         |
| Organization API token passed to `new SpritesClient(token)`             | [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.                                                           |
| One base image for every Sprite, with extra tools installed on its disk | [Managed image](https://vercel.com/docs/sandbox/concepts/images), or a custom OCI image in Vercel Container Registry                       | Put setup commands in a Dockerfile. Vercel Sandbox doesn't run an image's `ENTRYPOINT` or `CMD`.                         |
| 8 vCPUs for every Sprite, with platform-managed memory                  | `resources.vcpus`, with 2 GB of memory per vCPU                                                                                            | Sandboxes default to 2 vCPUs. Size for peak use, because a Vercel sandbox has a fixed size.                              |
| 100 GB persistent disk for every Sprite                                 | 64 GB local disk that a snapshot saves on stop, plus [Drives](https://vercel.com/docs/sandbox/concepts/drives)                             | Move datasets and shared caches that exceed the local disk to a Drive.                                                   |
| No documented region option at creation                                 | `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 the `sprite` user in `/home/sprite`                     | Commands run as the image's default user, which is `ubuntu` or `arch` on managed images, in `/vercel`                                      | Update hardcoded paths. Pass `sudo: true` to `runCommand()` for commands that need root.                                 |
| Coding agent CLIs preinstalled on every Sprite                          | `sandbox create claude` or `sandbox create codex` in the Sandbox CLI, which start an agent from the default image                          | The default image includes coding agents. Install any other agent in a custom image.                                     |
| SDKs for JavaScript, Python, Go, and Elixir                             | TypeScript SDK, Python SDK, Sandbox CLI, and Vercel REST API                                                                               | Call the Vercel REST API from Go or Elixir applications.                                                                 |

### Lifecycle and state

A named persistent sandbox replaces a Sprite that pauses when idle. Your application ends each session and resumes the sandbox by name.

| Fly.io Sprites                                                                               | Vercel Sandbox                                                                                            | What you change                                                                                                   |
| -------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| Automatic pause about 30 seconds after activity stops                                        | `timeout` in the TypeScript SDK, or `execution_time_limit` in the Python SDK                              | Vercel Sandbox has no idle timeout. Set a session timeout as an upper bound, and stop the sandbox from your code. |
| No time limit on a Sprite                                                                    | 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()`.                        |
| Wake on a command, or on an HTTP request to the Sprite URL                                   | Resume on an SDK or CLI operation that needs a running VM, such as `runCommand()`                         | Resume the sandbox from your backend before you send traffic to its URL.                                          |
| Processes that continue after a warm pause                                                   | No equivalent                                                                                             | After each resume, restart processes, for example with the TypeScript SDK's `onResume` hook.                      |
| [Services](https://docs.fly.io/sprites/concepts/services) that start again after a cold wake | `onCreate` and `onResume` hooks that start detached commands                                              | Move each Service's command into a startup function.                                                              |
| Tasks that keep a Sprite awake during background work                                        | `extendTimeout()`                                                                                         | Remove the heartbeat. A session runs until its timeout or until your code calls `stop()`.                         |
| Filesystem that syncs continuously to object storage                                         | Automatic snapshot on stop, or a manual `sandbox.snapshot()`                                              | Stop the sandbox to save its files. Each stop saves a snapshot that counts toward Snapshot Storage.               |
| `client.sprite(name)` and `client.getSprite(name)`                                           | `Sandbox.get({ name })`                                                                                   | Look up sandboxes by name. The next command resumes a stopped sandbox.                                            |
| `sprite.createCheckpoint()` and `sprite checkpoint create`, which leave the Sprite running   | `sandbox.snapshot()`                                                                                      | A manual snapshot stops the session.                                                                              |
| `sprite.restoreCheckpoint()` and `sprite restore`, which roll the Sprite back in place       | `sandbox.update({ currentSnapshotId })`, or a new sandbox from `source: { type: 'snapshot', snapshotId }` | Point the sandbox at the earlier snapshot. Its next session resumes from that snapshot under the same name.       |
| Last five checkpoints mounted read-only at `/.sprite/checkpoints/`                           | No equivalent                                                                                             | Read earlier files from a sandbox created from that snapshot, or from a read-only Drive snapshot.                 |
| `sprite.delete()` and `sprite destroy`                                                       | `sandbox.delete()`                                                                                        | Pass `persistent: false` for disposable sandboxes.                                                                |
| Labels                                                                                       | Up to five `tags`                                                                                         | Reduce the label set, or put extra metadata in the sandbox name.                                                  |

### Networking and secrets

The firewall's `networkPolicy` option replaces the Sprites network policy, and public port URLs replace the Sprite URL.

| Fly.io Sprites                                                                                        | Vercel Sandbox                                                                        | What you change                                                                                                          |
| ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| Sprite URL, which routes to port 8080 or to one Service's `httpPort`                                  | `ports` and `sandbox.domain(port)`                                                    | List up to 15 ports at creation. Each port has its own URL.                                                              |
| Private Sprite URL, which requires a Fly.io login or a bearer token                                   | No equivalent                                                                         | Anyone with a port's URL can reach it. Authenticate callers in the server that runs inside the sandbox.                  |
| `sprite proxy` and `proxyPort()`, which forward TCP ports to your machine                             | No equivalent                                                                         | Expose HTTP and WebSocket servers through `ports`.                                                                       |
| No network policy, which leaves egress unrestricted                                                   | `networkPolicy: 'allow-all'`, the default                                             | No change. Both products allow outbound access by default.                                                               |
| A single deny rule for `*`                                                                            | `networkPolicy: 'deny-all'`                                                           | `deny-all` also blocks DNS.                                                                                              |
| Allow rules for named domains, with or without a deny rule for `*`                                    | `networkPolicy: { allow: [...] }`                                                     | On Vercel, `*.example.com` doesn't match `example.com`. List the apex domain separately.                                 |
| `{ include: 'defaults' }`                                                                             | No equivalent                                                                         | List each registry and API hostname that your workload needs.                                                            |
| `updateNetworkPolicy()`, which replaces the rule set                                                  | `sandbox.update({ networkPolicy })`                                                   | Each update replaces the whole policy.                                                                                   |
| `env` option on commands and Services                                                                 | `env`, at creation or for each command                                                | Read the values in your application and pass them in.                                                                    |
| [Connectors](https://docs.fly.io/sprites/concepts/connectors), which code calls through a gateway URL | [Brokering rules](https://vercel.com/docs/sandbox/concepts/firewall) with `transform` | Call the provider's own hostname. Rules match on path, method, query, and headers, and work together with an allow list. |
| Managed OpenRouter Connector                                                                          | [AI Gateway](https://vercel.com/docs/ai-gateway)                                      | Call hosted models through AI Gateway with your own API key.                                                             |

## Steps

### 1\. Find where your application uses Sprites

Search for Sprites SDK imports, `sprite` CLI calls, REST calls, and tokens, then trace aliases through your code. Match the results to the steps below and identify features that need a replacement.

```bash
commands='exec|x|console|create|list|ls|use|info|file|proxy|url|api'
commands+='|auth|sessions|attach|checkpoints?|restore|config|destroy'
prefix='sprite +(--?[a-z-]+( +[^ -][^ ]*)? +)*'

grep -rlIE \
  -e '@fly/sprites|SpritesClient|(from|import) sprites' \
  -e 'sprites-(py|go|ex|js)|\{:sprites,' \
  -e 'Sprites\.(new|create|sprite|cmd|spawn|stream|destroy)\(' \
  -e 'sprites\.(dev|app)([^[:alnum:]_]|$)|mcp\.fly\.io' \
  -e 'SPRITES?_(API_)?(TOKEN|URL)|sprite-env|/\.sprite/' \
  -e "${prefix}(${commands})( |$)" \
  --exclude-dir=node_modules --exclude-dir=.venv \
  --exclude-dir=venv --exclude-dir=.git .
```

The search covers shell scripts and CI configuration as well as application code, because the `sprite` CLI and the REST API at `api.sprites.dev` can create and control Sprites without an SDK. If you use Sprites through an agent framework, also search for that integration's package name.

Configuration can also live on the Sprite, outside your repository. Read each Sprite's Services, network policy, URL settings, labels, and checkpoints before migrating:

```bash
sprite info -s my-sprite
sprite exec -s my-sprite -- sprite-env services list
sprite exec -s my-sprite -- cat /.sprite/policy/network.json
sprite checkpoint list -s my-sprite
```

`sprite info` prints the Sprite URL and labels. Record each Service's definition for step 6, and carry any network policy rules into step 9. An empty `rules` list means that the Sprite has no policy. Match these findings to the migration steps below:

| In your code                                                                                                                 | Go to                                                                           |
| ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| Setup commands that install packages on a new Sprite with `apt`, `pip`, or `npm`                                             | [Step 4](#4.-move-your-sprite-environment-to-a-vercel-image)                    |
| `createSprite()`, `execFile()`, `spawn()`, or `sprite.filesystem()`, and Python's `create_sprite()`, `run()`, or `command()` | [Step 5](#5.-replace-sprite-creation,-commands,-and-file-operations)            |
| `client.sprite(name)`, `createCheckpoint()`, `restoreCheckpoint()`, `createService()`, or `sprite-env services`              | [Step 6](#6.-replace-idle-pauses-and-checkpoints-with-named-sandboxes)          |
| Workspaces, caches, or databases that live on a Sprite's disk                                                                | [Step 7](#7.-move-sprite-files-to-a-sandbox-or-drive)                           |
| `sprite.url`, `updateURLSettings()`, `httpPort`, or `sprite config update --url-auth`                                        | [Step 8](#8.-replace-the-sprite-url-with-public-ports)                          |
| `updateNetworkPolicy()`, `/policy/network`, `env` options, or `api.sprites.dev/v1/gateway`                                   | [Step 9](#9.-replace-the-network-policy,-environment-variables,-and-connectors) |
| HTTP-triggered wake, tasks on `/.sprite/api.sock`, `/.sprite/checkpoints/`, `sprite proxy`, or private Sprite URLs           | [What doesn't map from Fly.io Sprites](#what-doesn%27t-map-from-fly.io-sprites) |

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

For local runs, load `.env.local` with Node.js's `--env-file=.env.local` option or Python's `python-dotenv`. Refresh development OIDC tokens every 12 hours with `vercel env pull`; Vercel manages tokens for deployed applications.

For a backend hosted elsewhere, create a [Vercel access token](https://vercel.com/docs/accounts/access-tokens#create-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 credentials = {
  token: process.env.VERCEL_TOKEN,
  teamId: process.env.VERCEL_TEAM_ID,
  projectId: process.env.VERCEL_PROJECT_ID,
};

const sandbox = await Sandbox.create({ ...credentials });
```

The TypeScript SDK doesn't read these variables on its own. Pass all three fields to every static call, including `Sandbox.get()`, `Sandbox.getOrCreate()`, `Sandbox.fork()`, and `Sandbox.list()`. Methods on a returned sandbox reuse its credentials. The later samples omit these fields because they assume an OIDC token.

Without an OIDC token, the Python SDK reads these variables automatically from the environment of each Python process.

Keep your Sprites token until the migrated workloads pass verification. Retain tokens used by workloads remaining on Sprites.

### 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 `@fly/sprites` or `sprites-py` installed until no workloads use it.

### 4\. Move your Sprite environment to a Vercel image

Every Sprite starts from the same base image, and the tools you add live on its persistent disk. On Vercel, choose a [managed image](https://vercel.com/docs/sandbox/concepts/images) or build a custom image in Vercel Container Registry. Choose based on how your application prepares a Sprite:

| Sprite setup                                                                                     | Vercel replacement                                                                                                                                                                                    |
| ------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| The base image's Node.js or Python, with no extra system packages                                | 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. |
| Setup commands that run `apt-get install`, `pip install`, or `npm install -g` on each new Sprite | A Dockerfile with the matching `RUN` instructions, built into Vercel Container Registry                                                                                                               |
| Another preinstalled runtime, such as Go, Rust, or Ruby                                          | A Dockerfile that installs the runtime, built into Vercel Container Registry                                                                                                                          |
| A pool of prepared Sprites that you reset to a baseline checkpoint between jobs                  | A custom image, or a [snapshot that new sandboxes start from](#start-many-sandboxes-from-one-snapshot)                                                                                                |

Runtime versions can differ between the Sprites base image and a Vercel managed image. Check the versions your code depends on before you choose an image:

```bash
sprite exec -s my-sprite -- python --version
sprite exec -s my-sprite -- node --version
```

If a managed image fits, continue to [sandbox creation](#5.-replace-sprite-creation,-commands,-and-file-operations). Custom images require `linux/amd64`; registry limits are 15 GB per image and 2 GB per compressed layer. Install Docker and write your Sprite setup commands 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")
```

Vercel Sandbox doesn't run `ENTRYPOINT` or `CMD`, so start required processes with `runCommand()` after creation. Custom images use the Dockerfile's `WORKDIR`, or `/` if unset; managed images use `/vercel` and Sprites `/home/sprite`.

The Sprites base image and Vercel's default `vercel/sandbox/universal` image include different runtimes, tools, and coding agents. Other managed images include fewer tools, so add any missing dependencies to a custom image.

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

Route sandbox operations through one application module, replacing Sprites client, command, and file calls with the corresponding Vercel methods. `Sandbox.create()` takes project credentials without a client object. Add the Vercel calls beside the Sprites calls and use a flag to select the provider for each new agent session. Keep the Sprites path until step 10.

#### TypeScript SDK calls

| Task                          | Fly.io Sprites                                                | Vercel Sandbox                                                                                     |
| ----------------------------- | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| Import                        | `import { SpritesClient } from '@fly/sprites'`                | `import { Sandbox } from '@vercel/sandbox'`                                                        |
| Create a client               | `new SpritesClient(token)`                                    | No client object                                                                                   |
| Create a sandbox              | `client.createSprite(name)`                                   | `Sandbox.create(params)`                                                                           |
| Set the lifetime              | No option. A Sprite pauses when idle.                         | `timeout`, in milliseconds                                                                         |
| Set resources                 | No documented option. Every Sprite has 8 vCPUs.               | `resources: { vcpus }`                                                                             |
| Run a command                 | `sprite.execFile('python', ['main.py'])`                      | `sandbox.runCommand('python', ['main.py'])`                                                        |
| Read output                   | `result.stdout`                                               | `await result.stdout()`                                                                            |
| Get the exit code             | `result.exitCode`, or `ExecError` on a non-zero exit          | `result.exitCode`                                                                                  |
| Stream a long command         | `sprite.spawn('python', ['main.py'])`                         | `sandbox.runCommand({ cmd, args, detached: true })`                                                |
| Write a file                  | `fs.writeFile(path, data)`                                    | `sandbox.fs.writeFile(path, data)`, or `sandbox.writeFiles([{ path, content }])` for several files |
| Read a file                   | `fs.readFile(path, 'utf8')`                                   | `sandbox.fs.readFile(path, 'utf8')`, or `sandbox.readFileToBuffer({ path })` for bytes             |
| List, create, or remove paths | `fs.readdir()`, `fs.mkdir()`, and `fs.rm()`                   | `sandbox.fs.readdir()`, `sandbox.fs.mkdir()`, and `sandbox.fs.rm()`                                |
| Find a sandbox                | `client.sprite(name)` or `client.getSprite(name)`             | `Sandbox.get({ name })`                                                                            |
| List sandboxes                | `client.listAllSprites(prefix)`, which filters by name prefix | `Sandbox.list({ namePrefix, sortBy: 'name' })`                                                     |
| End a sandbox                 | `sprite.delete()`                                             | `sandbox.stop()` or `sandbox.delete()`                                                             |

`listAllSprites()` returns Sprite handles in an array. `Sandbox.list()` returns a paginated result of metadata records. Iterate it with `for await`, or call its `toArray()` method to collect every page, then use `Sandbox.get({ name: record.name })` when you need a handle.

If your application passes extra creation options, check the Sprite's actual resource use, region, environment variables, and installed runtimes before choosing the Vercel configuration. The Sprites `runtime` option selects `default` or `dev`; it does not identify the language runtime to install.

On Sprites, a script creates a client from an organization token, creates a named Sprite, and deletes the Sprite when the job ends:

```javascript
import { SpritesClient } from '@fly/sprites';

const token = process.env.SPRITES_TOKEN;
if (!token) throw new Error('SPRITES_TOKEN is required');
const client = new SpritesClient(token);
const sprite = await client.createSprite('run-main');

try {
  const fs = sprite.filesystem('/home/sprite');
  await fs.writeFile('main.py', 'print(21 * 2)');

  const result = await sprite.execFile('python', ['main.py'], {
    cwd: '/home/sprite',
    env: { PYTHONUNBUFFERED: '1' },
    timeout: 60_000,
  });
  console.log(result.stdout);
  console.log('exit code', result.exitCode);
} finally {
  await sprite.delete();
}
```

> **Warning:**
>
> `sprite.delete()` permanently deletes the Sprite, its files, and its checkpoints. Give the sample a name that no existing Sprite in your organization uses.

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. Every Sprite has 8 vCPUs and platform-managed memory, so check peak CPU and memory use before choosing the Vercel size for your workload. The 10-minute `timeout` sets an upper bound on the session, which a Sprite doesn't have. `persistent: false` keeps this example's behavior of discarding files when the job ends.

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                          | Fly.io Sprites                                                 | Vercel Sandbox                                                          |
| ----------------------------- | -------------------------------------------------------------- | ----------------------------------------------------------------------- |
| Import                        | `from sprites import SpritesClient`                            | `from vercel import sandbox`                                            |
| Create a client               | `SpritesClient(token=token)`                                   | No client object                                                        |
| Create a sandbox              | `client.create_sprite(name)`                                   | `sandbox.create_sandbox()`                                              |
| Set the lifetime              | No option. A Sprite pauses when idle.                          | `execution_time_limit`, in seconds or as a `timedelta`                  |
| Set resources                 | No documented option. Every Sprite has 8 vCPUs.                | `resources=SandboxResources(vcpus=2, memory=4096)`                      |
| Run a command                 | `sprite.run("python", "main.py")`                              | `box.run_command("python", ["main.py"])`                                |
| Read output                   | `result.stdout.decode()`, with `capture_output=True`           | `result.stdout.decode()`, with `capture_output=True`                    |
| Get the exit code             | `result.returncode`                                            | `result.returncode`                                                     |
| Write a file                  | `(fs / path).write_text(text)`                                 | `box.fs.write_text(path, text)`                                         |
| Read a file                   | `(fs / path).read_text()`                                      | `box.fs.read_text(path)`                                                |
| List, create, or remove paths | `listdir()`, `mkdir()`, and `unlink()` or `rmtree()` on a path | `box.fs.listdir()`, `box.fs.mkdir()`, and `box.fs.remove()`             |
| Find a sandbox                | `client.sprite(name)` or `client.get_sprite(name)`             | `sandbox.get_sandbox(name=name)`                                        |
| List sandboxes                | `client.list_all_sprites(prefix)`                              | `sandbox.query_sandboxes(query=SandboxQueryByName(name_prefix=prefix))` |
| End a sandbox                 | `sprite.destroy()`                                             | `box.stop()` or `box.destroy()`                                         |

Python's `query_sandboxes()` returns an async iterator rather than a list.

The Sprites Python SDK performs the same operations with its synchronous client:

```python
import os

from sprites import SpritesClient

with SpritesClient(token=os.environ["SPRITES_TOKEN"]) as client:
    sprite = client.create_sprite("run-main")

    try:
        fs = sprite.filesystem("/home/sprite")
        (fs / "main.py").write_text("print(21 * 2)")

        result = sprite.run(
            "python",
            "main.py",
            capture_output=True,
            timeout=60,
            cwd="/home/sprite",
            env={"PYTHONUNBUFFERED": "1"},
        )
        print(result.stdout.decode(), end="")
        print("exit code", result.returncode)
    finally:
        sprite.destroy()
```

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, matching `sprite.destroy()`. To keep files instead, set `persistent=True` and `destroy=False` in `create_sandbox()` so the context manager stops and saves the sandbox. 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

- Check timeout units when porting each call. Sprites JavaScript uses milliseconds, while Sprites Python uses seconds. Vercel TypeScript uses milliseconds for `timeout`, `timeoutMs`, and `extendTimeout()`. Vercel Python accepts seconds or a `timedelta` for `execution_time_limit` and `kill_after`.
  
- Replace `sprite.exec('ls -la')`, which splits on whitespace, with a binary and argument array. Neither product starts a shell automatically; keep `bash -c` for pipes, redirection, and variable expansion.
  
- Preserve failure handling and output decoding. Sprites JavaScript rejects a non-zero exit with `ExecError`; Vercel returns a result whose `exitCode` you must check. Both Python SDKs return a result unless `check=True`. In JavaScript, replace the `stdout` property with `await result.stdout()`. Vercel Python streams output locally unless `capture_output=True`, which captures bytes.
  
- Sprites run as `sprite` in `/home/sprite`; Vercel managed images use `ubuntu` or `arch` in `/vercel`. Update paths accordingly and pass `sudo: true` or `sudo=True` for root commands; these users have passwordless sudo.
  
- End Vercel sessions with `stop()` instead of waiting for an idle pause. Persistent sandboxes save a snapshot on each stop, which counts toward Snapshot Storage. Use `persistent: false` or `persistent=False` for one-off jobs whose files can be discarded.
  

#### Background commands and streamed output

Use a detached command in place of `sprite.spawn()` 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()` replaces `sprite.command()` and 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()
```

A Sprite stays awake while a command writes output and pauses after activity stops. On Vercel, wait for the 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 idle pauses and checkpoints with named sandboxes

Use a named persistent sandbox across agent sessions. Call `stop()` when work ends, then retrieve the sandbox by name for the next session.

#### Reconnect to a sandbox by name

On Sprites, your application stores the Sprite's name. The Sprite pauses after the session goes idle, and the next command wakes it. The excerpt assumes that `client` is your `SpritesClient` and that the Sprite already exists.

```javascript
// During an agent session
const sprite = client.sprite(`session-${sessionId}`);
const fs = sprite.filesystem('/home/sprite');
await fs.writeFile('notes.txt', 'draft');
// No call ends the session. The Sprite pauses when idle.

// Next agent session
const resumed = client.sprite(`session-${sessionId}`);
const result = await resumed.execFile('cat', ['/home/sprite/notes.txt']);
console.log(result.stdout);
```

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`. Your application still stores a name for each agent session, but now calls `stop()` instead of waiting for an idle pause. The name is unique within its project and stays unchanged across resumes, even though each resume starts a new session with its own timeout.

#### Set snapshot retention and handle missing state

Sprites keep files until deletion, while Vercel lets you configure snapshot retention:

| What you need to control                | Vercel setting                                                                                                                                                                                              |
| --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Expiration after last use               | The default is 30 days. Change it with TypeScript's `snapshotExpiration` in milliseconds or Python's `snapshot_expiration` in seconds.                                                                      |
| Snapshots kept until deletion           | Set the expiration value to `0` to disable expiry.                                                                                                                                                          |
| Snapshots left after deleting a sandbox | Deletion preserves snapshots by default. Enable `deleteOrphanSnapshots` in `sandbox.delete()` or `delete_orphan_snapshots` in Python's `box.destroy()` to remove only snapshots that no other sandbox uses. |

Python's `get_or_create_sandbox()` can replace a sandbox if its saved snapshot is missing. For an existing migrated workspace, use `get_sandbox()` when replacement would hide lost state. Set retention for the expected gap between sessions and keep a recoverable backup.

#### Restart processes after a resume

Restart the processes your application needs after each Vercel resume. On Sprites, processes survive a warm pause, while Services restart after a cold wake:

```bash
sprite exec -s my-sprite -- sprite-env services create web \
  --cmd python3 --args "-m,http.server,8000" --http-port 8000
```

To create the same Service with JavaScript, call `sprite.createService()` with `web` as the name. In its options object, set `cmd` to `python3`, `args` to `['-m', 'http.server', '8000']`, and `httpPort` to `8000`.

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 a new sandbox's server, while `getOrCreate()` with `resume: true` resumes a stopped sandbox and waits for `onResume`. These hooks run only when a session starts, so check processes from your application if you relied on Services restarting them after a crash. Before sending traffic, check readiness because detached commands 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.

#### Replace checkpoints with snapshots

A checkpoint captures a Sprite's filesystem while the Sprite keeps running, and a restore rolls the same Sprite back in place:

```bash
sprite checkpoint create -s my-sprite --comment "before upgrade"
sprite restore -s my-sprite v3
```

On Vercel, `sandbox.snapshot()` saves the filesystem and stops the session. To roll the same sandbox back, point it at the earlier snapshot. Its next session resumes from that snapshot under the same name:

```javascript
// Save a restore point from a running sandbox. This call stops the session.
const snapshot = await sandbox.snapshot();

// Later, roll the same sandbox back to the restore point
await sandbox.stop();
await sandbox.update({ currentSnapshotId: snapshot.snapshotId });
// The next command starts a session from that snapshot
```

Stop a running session before the update, because each stop saves a new snapshot and makes it the current one. In Python, pass `current_snapshot_id` to `box.update()`. To keep the current state and work on the earlier one in parallel, create a new sandbox from the snapshot:

```javascript
const restored = await Sandbox.create({
  name: `session-${sessionId}-restored`,
  source: { type: 'snapshot', snapshotId: snapshot.snapshotId },
});
```

Save each `snapshotId` needed for a later restore. Sprites use sequential IDs such as `v3` and create automatic checkpoints in the background; Vercel saves persistent state when a session stops. Take a manual snapshot between tasks before a change you may need to undo, then restart your processes.

#### Start many sandboxes from one snapshot

To start many sandboxes from one prepared environment, 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.

### 7\. Move Sprite files to a sandbox or Drive

Vercel Sandbox can't read a Sprite's disk or its checkpoints. Export the files you need, then import them into a persistent sandbox or a Drive.

#### Copy a workspace into a persistent sandbox

Before the final export, stop the processes that write to the workspace and keep writes paused until you have imported and verified the files. For a database, use its backup procedure if you cannot stop its writers.

This example exports `/home/sprite/app` rather than the home directory, whose `.claude` and `.codex` configuration can refer to `sprite-env` and the Connector gateway. It excludes `.env` files, `node_modules`, and `.venv`; add exclusions for other credential files and pass secrets through `env` as described in step 9. Run both commands together because files in `/tmp` may not survive a pause:

```bash
sprite exec -s my-sprite -- tar -czf /tmp/workspace.tgz \
  --exclude=node_modules --exclude=.venv \
  --exclude=.env --exclude='.env.*' -C /home/sprite/app .
sprite file pull -s my-sprite /tmp/workspace.tgz ./workspace.tgz
```

Inspect the downloaded archive to confirm that it contains application files and omits credentials and dependencies you plan to rebuild. Rebuild system packages and image dependencies in step 4, and reinstall dependencies on Vercel because a Python virtual environment records absolute paths under `/home/sprite`. For a transfer that needs to resume, Fly.io documents [`rsync`](https://docs.fly.io/sprites/sprite-maintenance) [over](https://docs.fly.io/sprites/sprite-maintenance) [`sprite exec`](https://docs.fly.io/sprites/sprite-maintenance).

#### Import the archive into Vercel

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

**pnpm**

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

**npm**

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

**yarn**

```bash
yarn global add sandbox
```

**bun**

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

Use a new destination name and the settings your application expects for each import. Set image and environment values before creation; the JavaScript SDK's `sandbox.update()` cannot change them. `Sandbox.getOrCreate()` ignores creation settings for existing names.

| Setting                          | Configure before import                                                                                                                                  |
| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Image and working directory      | The commands use the default managed image and `/vercel`. For a custom image, add `--image agent-runtime:latest` and extract into its working directory. |
| Environment variables            | Supply application values with `--env` instead of copying credential files.                                                                              |
| Resources, region, and retention | Set `--vcpus`, `--region`, and `--snapshot-expiration` to match the application's requirements.                                                          |
| Preview ports                    | Add `--publish-port 8080` to `sandbox create` for a preview server, replacing 8080 with its port.                                                        |

Run the import from the linked project directory, or use `--project` and `--scope` to select its destination project and team:

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

After extraction, update scripts and configuration that refer to `/home/sprite` and repeat the [repository search](#1.-find-where-your-application-uses-sprites) for remaining Sprites dependencies. To expose port 8080 on an existing import, run `sandbox config ports session-123 -p 8080`. This replaces the port list, so include every required port.

#### Move large or shared data to a Drive

Use a [Drive](https://vercel.com/docs/sandbox/concepts/drives) for data that exceeds a sandbox's 64 GB local disk or that several sandboxes read. It outlives the sandbox and mounts as a directory. Create it with `Drive` from `@vercel/sandbox`, or the Python SDK's Drive functions. Measure your data first, because the size limit is fixed at creation:

```bash
sprite exec -s my-sprite -- du -sh /home/sprite/cache
```

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, 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},
)
```

Each Drive allows one writable mount. Other sandboxes can use `drive.snapshot()` for a read-only view at attachment time; mount a new snapshot to read later writes. Drives default to `iad1`, with region and maximum size fixed at creation. Mount up to four Drives per sandbox at non-overlapping absolute paths.

Before the final export, stop the processes that write to the directory on the Sprite. Archive the directory and download the archive:

```bash
sprite exec -s my-sprite -- tar -czf /tmp/cache.tgz -C /home/sprite/cache .
sprite file pull -s my-sprite /tmp/cache.tgz ./cache.tgz
```

If you ran the SDK mount example, await `sandbox.stop()` in TypeScript or `box.stop()` in Python to release its writable Drive mount before importing. Verify the archive, then copy it into a sandbox that mounts the Drive and extract into `/cache`. Use a new import sandbox name and replace `iad1` with the Drive's region:

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

The `--non-persistent` flag discards the import sandbox's own files on stop. The files in `/cache` stay on the Drive. The archive passes through the import sandbox's local disk, so split an export that is larger than the free space there.

### 8\. Replace the Sprite URL with public ports

The `ports` option and `sandbox.domain()` replace the Sprite URL. A Sprite has one URL, which routes to port 8080 or to the Service that sets an HTTP port. This excerpt creates a Sprite with a public URL and starts a server:

```javascript
const sprite = await client.createSprite('preview', {
  urlSettings: { auth: 'public' },
});

sprite.spawn('python', ['-m', 'http.server', '8080']);
console.log(sprite.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: [8080] });

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

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

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

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

Vercel port URLs are public, so [authenticate callers in your server](#authenticated-inbound-access) if you relied on a Sprite URL's default authentication. Requests to a stopped sandbox return [HTTP 410](https://vercel.com/docs/errors/sandbox_stopped) without waking it. Before sending traffic, your backend must [resume it](#6.-replace-idle-pauses-and-checkpoints-with-named-sandboxes), restart its server, and check readiness.

Each of the sandbox's exposed ports has its own URL, with up to 15 ports per sandbox. Read them with `sandbox.domain(port)` and replace any Sprite URLs saved by your application or users. To change exposed ports, pass the complete desired list to `sandbox.update({ ports })`.

### 9\. Replace the network policy, environment variables, and Connectors

#### Map Sprites policy rules to a Vercel network policy

Use `networkPolicy` to replace the rules that your application sets with `updateNetworkPolicy()` or the `/policy/network` endpoint:

| Sprites network policy rules                                                                            | Vercel `networkPolicy`                                        |
| ------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- |
| No rules                                                                                                | `'allow-all'`, the default                                    |
| `{ domain: '*', action: 'deny' }`                                                                       | `'deny-all'`                                                  |
| Allow rules for `api.openai.com`, `github.com`, and `*.github.com`, with or without a deny rule for `*` | `{ allow: ['api.openai.com', 'github.com', '*.github.com'] }` |
| `{ include: 'defaults' }`                                                                               | An allow list that names each registry and API host           |

On Sprites, a policy that allows three hosts and denies the rest looks like this:

```javascript
await sprite.updateNetworkPolicy({
  rules: [
    { domain: 'api.openai.com', action: 'allow' },
    { domain: 'github.com', action: 'allow' },
    { domain: '*.github.com', action: 'allow' },
    { domain: '*', action: 'deny' },
  ],
});
```

Rule order doesn't matter on Sprites, because the most specific rule wins. An exact host beats a subdomain wildcard, which beats `*`. If your policy allows `*.example.com` and denies one subdomain, list the allowed subdomains on Vercel in place of the wildcard.

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', '*.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 policies list domains to allow, so replace a Sprites policy that denies selected domains and allows the rest with an allow list for the hosts your workload calls. Include `github.com` separately when your code calls the apex domain; `*.github.com` covers only subdomains. Sprites enforce domain policy through DNS, while Vercel matches the TLS hostname. Allow plain HTTP by IP range.

#### Pass environment variables

Sprites take environment variables for each command or Service. The JavaScript SDK also accepts `environment` in `createSprite()`, but Python's `create_sprite()` has no creation-time environment argument. 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. If your application wrote an environment file to the Sprite's disk, pass those values through `env` instead of copying the file.

#### Broker credentials with firewall rules

Code in the sandbox can read every value in its environment. To keep a credential outside the sandbox, replace a Sprites Connector with a brokering rule, which adds the header after the request leaves the sandbox.

Within a Sprite, call the Connector gateway without an `Authorization` header:

```text
https://api.sprites.dev/v1/gateway/<provider>/<connection_id>/<path>
```

On Vercel, the firewall adds the credential to requests for the provider's hostname:

**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']}"
                                )
                            }
                        )
                    ]
                )
            ],
            "*": [],
        }
    ),
)
```

Replace each Connector gateway URL with the provider's hostname. The gateway accepts calls only from a running Sprite. For a Custom API Connector, use its base URL and retain the path that followed the connection ID.

Your application supplies the credential that Fly.io stored in the organization. Load it from the application's environment at sandbox creation or update. For OAuth, complete the flow in your application and replace the policy with `sandbox.update()` when the token changes. Brokering rules set request headers; call APIs that require secrets in query parameters or URL paths from your backend.

Keep the allow list and credential scope aligned when configuring the rule:

- Remove `'*'` to block domains that the policy doesn't name.
  
- Use `match` to limit credentials by path, method, query string, or headers. The query matcher is `queryString` in TypeScript and `query` in Python.
  
- Matching alone doesn't reject other requests to an allowed domain. Finish its rule list with a `response` rule whose `statusCode` is `403` to block them.
  

### 10\. Verify and cut over

#### Validate workload behavior and resource use

Run both providers side by side before changing traffic:

- Run a representative workload on each provider and compare its output, exit codes, and written files.
  
- Check that the migrated network policy permits required services and blocks the destinations your source policy blocked.
  
- 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 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.
  
- Confirm that each execution path stops the sandbox when its work ends. Sprites pause when idle; Vercel sessions otherwise continue until their timeout.
  

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.

#### Move session state and switch traffic

Before moving state, plan replication between providers if shared data must remain writable during cutover. Otherwise, stop writes during the final export and import.

1. Record which provider owns each existing session and keep its requests on that provider while you migrate its state.
   
2. Pause writes to the Sprites being moved. Export and verify the files, then import them before routing those sessions to Vercel.
   
3. Switch the flag for new sessions and monitor output and errors. Keep existing Sprites sessions on Sprites until they finish or their state has been imported.
   

#### Keep a rollback path until cleanup

If you roll back, send new sessions to Sprites. Before moving a session that has written files on Vercel back to a Sprite, copy and verify those changes. Retain both providers' state until the rollback period ends.

After the rollback period, destroy only the Sprites that migrated workloads no longer need. Destroying a Sprite permanently deletes its files and checkpoints. Remove the package and revoke its token only after confirming that no other application or job uses them.

## What doesn't map from Fly.io Sprites

These Sprites 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.

### Warm pauses that keep memory

Vercel snapshots preserve files without process memory. Sprites retain memory during a warm pause and continue their processes on wake, but a cold wake drops memory. You can't choose which pause a Sprite takes, so code that already recovers from a cold wake needs the same recovery after each Vercel resume.

Save progress that must survive a stop to a file, Drive, or database. On resume, start the process again and have it load that progress. The [process restart example](#restart-processes-after-a-resume) shows how to attach startup logic to the sandbox lifecycle.

### Sprites that stay active with no time limit

Vercel sessions end at their timeout, up to 45 minutes on Hobby or 24 hours on Pro and Enterprise, while Fly.io sets no time limit on an active Sprite. Persistent sandboxes preserve files between sessions, so save progress to files, run long tasks as detached commands, and restart them in `onResume`.

Remove the task registration on `/.sprite/api.sock` that keeps a Sprite awake during background work. Vercel sessions run until their timeout; set `timeout` for the job and call `extendTimeout()` while work continues. On Pro and Enterprise, [lifecycle webhooks](https://vercel.com/docs/sandbox/lifecycle-webhooks) notify your backend at session start, near timeout, and on stop. Use the expiry warning to save progress or extend the session within its limit.

### Idle pauses and wake on HTTP requests

A Sprite pauses about 30 seconds after activity stops, and a request to its URL wakes it. Vercel has no idle timeout or wake on HTTP requests, so track activity in your application, extend sessions while work continues, and call `stop()` when work ends. For an interactive agent, 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.

Vercel SDK operations that need a running sandbox, such as `runCommand()`, resume a stopped persistent sandbox. Requests to its port URL return HTTP 410 while it is stopped. For a preview, have your backend resume the sandbox, restart its server, and wait for a successful health check before loading the sandbox URL, as shown in [Resume a sandbox before sending traffic](#resume-a-sandbox-before-sending-traffic).

### Services that start after a wake

Sprites Services restart after a cold wake or process crash and start on requests to their HTTP port. Vercel restores files, so install dependencies in an image or snapshot and start services with a detached `runCommand()` after creation and each resume, preserving their `needs` order.

Detached commands don't restart after a process exits. If you relied on crash restarts, run a supervisor in the sandbox or monitor the process from your backend. Read detached output with `command.logs()`; the files under `/.sprite/logs/services/` are specific to Sprites.

#### Check that your service is ready

Sandbox creation waits until commands can run, but your server may still be starting. Before sending traffic, check an endpoint that reports whether 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.

#### Resume a sandbox before sending traffic

Requests to a Sprite URL wake it. On Vercel, create and configure the sandbox during provisioning or file import, then call this helper from the route that handles the user's request. Save it beside the readiness helper:

```javascript
import { Sandbox } from '@vercel/sandbox';
import { waitForHttp } from './wait-for-http.mjs';

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

export async function resumeAndGetUrl(name) {
  const sandbox = await Sandbox.get({
    name,
    resume: true,
    onResume: startServer,
  });

  const url = sandbox.domain(8080);
  await waitForHttp(url);
  return url;
}
```

If the saved snapshot is missing, `Sandbox.get()` fails so your application can recover from a backup. `getOrCreate()` with `resume: true` would instead create a fresh sandbox. For a running session, `onResume` is skipped, but the helper still waits for a successful health check.

To give users a stable address, point a domain at your application and have a route look up the sandbox's current URL and proxy each request to it.

### Authenticated inbound access

Protect a public Vercel port URL by having the server check a per-sandbox bearer token sent by your trusted backend. This authenticates outside callers, but code inside the sandbox can still read that 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.

A private Sprite URL also accepts a Fly.io browser login. Browsers cannot add this authorization header to a page load or iframe, so serve previews through an authenticated proxy that adds the token.

### Checkpoints you can read inside the Sprite

Sprites mount their last five checkpoints read-only at `/.sprite/checkpoints/`, and code inside the Sprite can create and restore checkpoints with `sprite-env`. On Vercel, your application creates snapshots from outside the sandbox, and a manual snapshot stops the session. To retain the latest three snapshots saved when a sandbox stops, set `keepLastSnapshots` to `{ count: 3 }` at creation.

To read files from an earlier state, start a disposable sandbox from that snapshot. Replace `your_snapshot_id_here` with a `snapshotId` that your application stored:

```bash
sandbox create --name restore-check --non-persistent \
  --snapshot your_snapshot_id_here
sandbox exec restore-check -- ls /vercel
sandbox stop restore-check
```

Share reference files through a [read-only Drive snapshot](https://vercel.com/docs/sandbox/concepts/drives#snapshots). Once step 7 has populated `workspace-cache`, mount a snapshot in another 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.

### Fixed 8 vCPUs and a 100 GB disk

Every Sprite has 8 vCPUs, platform-managed memory, and a 100 GB disk. Vercel sandboxes have 1 vCPU or an even number up to 32, with 2 GB of memory per vCPU. Choose a fixed Vercel size that covers peak use and fits your plan. Matching a Sprite's 8 vCPUs requires a Pro or Enterprise plan.

Update an existing sandbox's `resources.vcpus` setting with `sandbox.update()`, then stop and resume it to apply the new allocation.

#### Store files beyond the local disk

For files that exceed 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`. Its region and size limit are fixed at creation. Drives on Hobby and Pro trials have a 15 GB limit, so use external storage if that is too small.

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.

### Connectors and managed model access

The Connector gateway attaches credentials stored in your Fly.io organization. Use Vercel [firewall brokering rules](https://vercel.com/docs/sandbox/concepts/firewall#credentials-brokering) to add them to outbound 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, and the firewall adds it to requests for the named hostname without putting it in the sandbox's environment. When the provider uses OAuth, complete the flow in your application and store the token there, because brokering uses a credential that your application supplies.

The CLI policy allows only the named domain. Sprites Connectors deny access by default and grant it by Sprite name prefix, by labels, or to every Sprite; they can also allow or block provider paths. Each Vercel sandbox has its own policy, so add credentials only where needed and reproduce path restrictions with `match`. Configure path- or method-specific request matching in step 9.

#### Replace managed model access

Fly.io's managed OpenRouter Connector gives a Sprite model access without a separate OpenRouter account. On Vercel, call hosted models through [AI Gateway](https://vercel.com/docs/ai-gateway). Before running the text-generation request below 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). 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."}
    ]
  }'
```

For sandboxed calls, broker the key with a firewall rule for `ai-gateway.vercel.sh`.

### Port forwarding, terminals, and the sprite CLI

`sprite proxy` forwards TCP ports from a Sprite to your machine, and `sprite exec` forwards a port that its command opens. Vercel port URLs support HTTP and WebSocket traffic; raw TCP and HTTP/2 tunnels need a different service or protocol. Reach a service through a port that you expose with `ports`, and replace `localhost` URLs in your scripts with the port's URL.

Replace `sprite console` with `sandbox connect` in the Sandbox CLI:

```bash
sandbox connect session-123
```

Replace `sprite` CLI commands in scripts and CI jobs with these commands:

| `sprite` CLI                                                                  | Vercel replacement                                                                          |
| ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| `sprite create`                                                               | `sandbox create`                                                                            |
| `sprite list`                                                                 | `sandbox list --all`, which includes stopped sandboxes                                      |
| `sprite exec -- <command>`                                                    | `sandbox exec <name> -- <command>`                                                          |
| `sprite console`                                                              | `sandbox connect <name>`                                                                    |
| `sprite file push` and `sprite file pull`                                     | `sandbox copy`                                                                              |
| `sprite checkpoint create`                                                    | `sandbox snapshot <name> --stop`, which saves files and stops the running session           |
| `sprite restore <version>`                                                    | `sandbox config current-snapshot <name> <snapshot_id>`, which the next session resumes from |
| `sprite destroy`                                                              | `sandbox remove <name>`                                                                     |
| `sprite proxy`                                                                | No equivalent. Expose a port with `--publish-port`.                                         |
| `sprite config update --url-auth public` or `sprite url update --auth public` | No equivalent. Port URLs are public.                                                        |

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

| Sprites feature                                                  | On Vercel Sandbox                                                                                             |
| ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| Detachable sessions from `createSession()` and `attachSession()` | A detached command. Store its `cmdId` and look it up with `sandbox.getCommand()`.                             |
| TTY sessions with `tty: true`                                    | `sandbox.openInteractive()`, which returns a WebSocket URL and token                                          |
| `stdin` on `spawn()`                                             | `stdin: true` with `detached: true` in `runCommand()`, then `command.writeStdin()` and `command.closeStdin()` |
| Resources policy with a memory limit                             | A fixed size set with `resources.vcpus`                                                                       |
| Go and Elixir SDKs, and the Sprites REST API                     | The [Sandboxes endpoints](https://vercel.com/docs/rest-api/sandboxes) in the Vercel REST API                  |

### Preinstalled coding agents and the hosted MCP server

Both Sprites and Vercel's default image include coding agent CLIs. The Sandbox CLI starts an agent in a new sandbox with `sandbox create`, accepting `codex`, `opencode`, and `pi` alongside the Claude Code command below. Install agents missing from the default image in a custom image:

```bash
sandbox create claude
```

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

Fly.io's hosted MCP server lets a coding agent create and manage Sprites. For a coding agent on your machine, the [Vercel plugin](https://vercel.com/docs/agent-resources/vercel-plugin) includes the [offload-to-sandbox](https://skills.sh/vercel/vercel-plugin/offload-to-sandbox) skill. The skill moves heavy builds, long test suites, and parallel tasks into their own sandboxes, then collects the results and cleans up.

## Troubleshooting

| 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 can't find files that it found on the Sprite                    | Managed images use `/vercel` as the working directory, and a Sprite uses `/home/sprite`. Update absolute paths, or pass `cwd`.                                                                                                              |
| A command or file write fails with a permission error                     | Commands run as the image's default user. Write under `/vercel`, or pass `sudo: true`.                                                                                                                                                      |
| A tool or runtime from the Sprites base image isn't found                 | Vercel's managed images include a different set of tools. Install the tool in a custom image, as shown in step 4.                                                                                                                           |
| Pipes, redirection, or `$VARIABLES` reach the program as literal text     | `runCommand()` doesn't use a shell. Wrap the command in `bash -c`.                                                                                                                                                                          |
| A failed command no longer throws an error                                | `execFile()` rejects with `ExecError` on a non-zero exit. `runCommand()` returns the result, so check `exitCode`.                                                                                                                           |
| A sandbox stops after 5 minutes, in the middle of a task                  | A session ends after 5 minutes unless you set `timeout`. Set `timeout` to cover the task, or call `extendTimeout()` while work continues.                                                                                                   |
| A sandbox keeps running after its work ends                               | Vercel Sandbox has no idle pause. Call `stop()` when work ends, and set `timeout` as an upper bound.                                                                                                                                        |
| 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, and HTTP requests don't resume it. 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.                                                                                                                                    |
| Anyone can open a URL that was private on Sprites                         | Vercel port URLs are public. Check a per-sandbox token in your server, as shown under authenticated inbound access.                                                                                                                         |
| Sandboxed code that calls `api.sprites.dev/v1/gateway` fails              | A Connector's gateway accepts calls only from inside a Sprite. Call the provider's own hostname and add a brokering rule, as shown in step 9.                                                                                               |
| 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 Sprites.

### 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 Fly.io Sprites](https://vercel.com/kb/guide/vercel-sandbox-vs-fly-io-sprites) for your workload
  
- Expose a dev server with [public ports](https://vercel.com/docs/sandbox/examples/expose-a-port)
  
- Move [Fly.io applications to Vercel](https://vercel.com/kb/guide/migrate-fly-io-to-vercel) or [background workers to Vercel Daemons](https://vercel.com/kb/guide/migrate-fly-io-workers-to-vercel-daemons).
  

## Frequently asked questions

### Can I move a Sprite's disk or checkpoints to Vercel Sandbox directly?

No. Archive the files on the Sprite and download the archive with `sprite file pull`. 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 some workloads on Sprites and move the rest to Vercel Sandbox?

Yes. The Sprites and Vercel Sandbox SDKs are independent, so one application can call both. Keep a workload on Sprites while it still depends on HTTP-triggered wake or on processes that resume after a warm pause.

### Do I need a custom image to replace the Sprites base image?

Not always. A Vercel managed image can replace the Sprites base image when its runtime versions and installed tools meet your workload's requirements. Build a custom image in Vercel Container Registry with `vercel vcr build` if you need other runtimes, system packages, or tools.

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

Yes. The `vercel-sandbox` package supports Python 3.11 or later with asynchronous and synchronous APIs. Some names differ from the Sprites Python SDK, for example `run_command()` instead of `run()`.

### Does Vercel Sandbox pause idle sandboxes the way Sprites do?

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

### Does an HTTP request wake a stopped Vercel sandbox, as it wakes a Sprite?

No. Resume a stopped persistent sandbox with a command or file operation before loading its URL. Until it resumes, the port URL returns HTTP 410.

### Do processes keep running when a Vercel sandbox stops and resumes, as they do after a warm Sprite pause?

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.

### Can a Vercel sandbox URL require authentication, as a Sprite URL does by default?

Not at the platform level. Anyone with a Vercel port URL can reach the port. Check a per-sandbox token in the server that runs inside the sandbox, and send requests from your backend.

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

No. Sprites run commands as the `sprite` user in `/home/sprite`. Vercel managed images run commands as the `ubuntu` or `arch` user in `/vercel`. Each of these users has passwordless sudo. Pass `sudo: true` to `runCommand()`, or `sudo=True` to `run_command()`, for commands that need root.

## Related Resources

- [Vercel Sandbox vs Fly.io Sprites](/kb/guide/vercel-sandbox-vs-fly-io-sprites): Compare Vercel Sandbox and Fly.io Sprites as AI agent sandboxes, including isolation, persistence, network controls, SDKs, and idle behavior.

## More Vercel Sandbox guides

- [Migrate from Daytona to Vercel Sandbox](/kb/guide/migrate-from-daytona-to-vercel-sandbox): Migrate from Daytona to Vercel Sandbox in TypeScript or Python, including images, persistent files, network policies, and a staged cutover.
- [Migrate from Railway Sandboxes to Vercel Sandbox](/kb/guide/migrate-from-railway-sandboxes-to-vercel-sandbox): Migrate Railway Sandboxes to Vercel Sandbox, adapting templates, checkpoints, timeouts, and networking with a staged cutover.
- [Vercel Sandbox vs Daytona](/kb/guide/vercel-sandbox-vs-daytona): Compare Vercel Sandbox and Daytona as AI agent sandboxes, including isolation, persistence, network controls, SDKs, and deployment regions.

## Reference Architecture

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

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

[Browse all stacks](/kb/architecture)

## Build with prompts

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

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

## Search guides from your terminal

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

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

# Show the latest guides
npx vercel@latest kb

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