---
title: Migrate from Railway Sandboxes to Vercel Sandbox
description: Migrate Railway Sandboxes to Vercel Sandbox, adapting templates, checkpoints, timeouts, and networking with a staged cutover.
keywords: ["Vercel Sandbox","Railway Sandboxes","migrate from Railway","AI agent sandbox","sandbox migration","untrusted code execution"]
url: "https://vercel.com/kb/guide/migrate-from-railway-sandboxes-to-vercel-sandbox"
published: 2026-12-02
last_updated: 2026-12-02
authors: Ben Sabic
related_resources:
  - title: "Vercel Sandbox vs Railway Sandboxes"
    url: "/kb/guide/vercel-sandbox-vs-railway-sandboxes"
    description: "Compare Vercel Sandbox and Railway Sandboxes as AI agent sandboxes, including isolation, persistence, network controls, SDKs, regions, and pricing."
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-railway-sandboxes-to-vercel-sandbox"
---

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

Railway deletes a sandbox's files when it destroys the sandbox, unless you capture a checkpoint or create a fork first. On Vercel, persistent sandboxes preserve files by default when they stop, but your application must restart processes when it resumes the workspace by name. Review the [migration limitations](#what-doesn%27t-map-from-railway-sandboxes) before starting, especially if your application also relies on private networking with Railway services, idle timeouts, or forks of a running sandbox.

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

## Prerequisites

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

## Migrate with your agent

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

### Agent prompt

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

1. Read and follow the migration guide using the Vercel CLI: `npx vercel@latest kb inspect migrate-from-railway-sandboxes-to-vercel-sandbox`.
2. Inventory imports of the `railway` package and its sandbox call sites, including templates, commands, files, checkpoints, forks, domains, variables, network modes, idle timeouts, and resource settings. Include `railway sandbox` CLI calls in scripts and direct calls to Railway's sandbox HTTP or GraphQL APIs. Preserve the application's authorization checks.
3. Identify features that need a different design, including private networking with Railway services, Railway variable references, idle timeouts and heartbeats, sandboxes with the idle timeout disabled, forks or checkpoints of a running sandbox, durable command sessions, SSH and port forwarding, fractional vCPUs, and sizes above the Vercel plan's limit. 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 Railway path available until I approve cutover.
5. Port one call site at a time. Check shell use, units, paths, users, cleanup, and persistence against the guide and the SDK reference: https://vercel.com/docs/sandbox/sdk/javascript
6. Plan how to stop writes, export and verify files, and reconcile changes if we roll back. Do not destroy Railway sandboxes, 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 Railway Sandboxes features map to Vercel Sandbox

Replace the Railway environment with a Vercel project and retain session files in a named persistent sandbox. Choose [replacements for private networking and idle timeouts](#what-doesn%27t-map-from-railway-sandboxes) using the [workload comparison](https://vercel.com/kb/guide/vercel-sandbox-vs-railway-sandboxes).

Railway's SDK is TypeScript, so the mappings use TypeScript names for both products. Vercel Sandbox also has a [Python SDK](https://vercel.com/docs/sandbox/sdk/python) for Python 3.11+.

### Projects, templates, and compute

| Railway Sandboxes                                                                                                       | Vercel Sandbox                                                                                                                                           | What you change                                                                                                          |
| ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| Railway environment, selected by the project token or `environmentId`                                                   | Vercel project                                                                                                                                           | Remove `environmentId`. Each sandbox belongs to the project that issued its credentials.                                 |
| Project token in `RAILWAY_TOKEN`, or an account or workspace token in `RAILWAY_API_TOKEN` with `RAILWAY_ENVIRONMENT_ID` | [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.                                                           |
| Standard Ubuntu-based image with git, Node.js, and coding agents                                                        | Default `vercel/sandbox/universal` [managed image](https://vercel.com/docs/sandbox/concepts/images) with Node.js 24, Python 3.14, git, and coding agents | Check that the runtime versions and tools your commands expect are present.                                              |
| Template from `Sandbox.template()` or `railway sandbox template build`                                                  | Custom OCI image in Vercel Container Registry, or a snapshot of a prepared sandbox                                                                       | Move the build steps into a Dockerfile or a setup script. Vercel Sandbox doesn't run an image's `ENTRYPOINT` or `CMD`.   |
| `resources: { cpu, memoryGB }`, set independently, with fractional `cpu`                                                | `resources: { vcpus }`, with 2 GB of memory per vCPU                                                                                                     | Choose 1 vCPU or an even number that covers both Railway values.                                                         |
| `region`, with one of four region IDs such as `us-west2`                                                                | `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. |
| `exec()`, which runs one command string in a login shell                                                                | `runCommand()`, which runs a binary with an argument array and no shell                                                                                  | Split each command, or wrap it in `bash -c` when it needs pipes, redirection, or variable expansion.                     |
| Files at absolute paths such as `/app`                                                                                  | Working directory `/vercel` on managed images, with commands run as the image's default user                                                             | Use relative paths or `/vercel`. Pass `sudo: true` to `runCommand()` for commands that need root.                        |

### Lifecycle and state

Vercel sandboxes are persistent by default, which replaces the checkpoints a Railway application captures before it destroys a sandbox.

| Railway Sandboxes                                                                             | Vercel Sandbox                                                          | What you change                                                                                                                                      |
| --------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `idleTimeoutMinutes`, which destroys the sandbox after 1 to 120 idle minutes on Hobby and Pro | `timeout`, in milliseconds, which stops the session at a fixed time     | Convert the units. Vercel Sandbox has no idle timeout, so extend or stop the session from your code.                                                 |
| `sandbox.heartbeat()`                                                                         | `sandbox.extendTimeout()`                                               | Extending adds time to the session. It doesn't reset an idle timer.                                                                                  |
| `idleTimeoutMinutes: 0`, which keeps the sandbox running until you destroy it                 | Session of up to 45 minutes on Hobby, or 24 hours on Pro and Enterprise | A persistent sandbox spans many sessions. Restart processes after each resume.                                                                       |
| `sandbox.destroy()`, which deletes the sandbox and its files                                  | `sandbox.stop()`, which saves the filesystem, or `sandbox.delete()`     | Pass `persistent: false` for disposable sandboxes.                                                                                                   |
| `sandbox.checkpoint(name)`, restored with `Sandbox.create(name)`                              | Automatic snapshot on stop, or a manual `sandbox.snapshot()`            | Reconnect by sandbox name. Store a snapshot ID only to seed new sandboxes.                                                                           |
| `Sandbox.connect(id)`                                                                         | `Sandbox.get({ name })`                                                 | Look up sandboxes by name. The next command resumes a stopped sandbox.                                                                               |
| Several sandboxes created from one checkpoint or template                                     | `source: { type: 'snapshot', snapshotId }`                              | Take one snapshot of a prepared sandbox and pass its ID as the `source`.                                                                             |
| `sandbox.fork()`, which copies a running sandbox's disk                                       | `Sandbox.fork({ sourceSandbox })`                                       | A fork starts from the source sandbox's current saved snapshot, so [stop or snapshot the source first](#forks-and-checkpoints-of-a-running-sandbox). |
| Durable `exec` sessions, reattached with `exec({ sessionName })`                              | Detached commands, retrieved with `sandbox.getCommand(cmdId)`           | [Command IDs work only within the session that started them](#durable-command-sessions).                                                             |
| Checkpoints kept until you delete them                                                        | Snapshots that expire 30 days after last use by default                 | Set `snapshotExpiration` to `0` to keep snapshots until you delete them.                                                                             |
| Sandboxes identified by ID only                                                               | `name`, plus up to five `tags`                                          | Derive the name from your session, user, or task ID.                                                                                                 |

### Networking and secrets

The `ports` option replaces Railway domains, and the firewall's `networkPolicy` option adds egress rules, which Railway's docs don't describe for sandboxes.

| Railway Sandboxes                                                    | Vercel Sandbox                                                                        | What you change                                                                                                                            |
| -------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `domains: [{ port }]` and `sandbox.domains`, in `PRIVATE` mode only  | `ports` and `sandbox.domain(port)`                                                    | List up to 15 ports at creation, or replace the list later with `sandbox.update({ ports })`. Anyone with a port's URL can reach it.        |
| `railway sandbox forward`                                            | No equivalent                                                                         | Publish the port and authenticate callers in the server that runs inside the sandbox.                                                      |
| `networkIsolation: "ISOLATED"`, the default                          | `networkPolicy: 'allow-all'`, the default                                             | No change. Both allow outbound internet access.                                                                                            |
| `networkIsolation: "PRIVATE"` to reach `*.railway.internal` services | No equivalent                                                                         | Reach the service through a public domain or a TCP Proxy. See the [private networking options](#private-networking-with-railway-services). |
| No documented egress allow list or deny list                         | `networkPolicy` with `'deny-all'`, domain allow lists, and CIDR rules                 | Optional. Restrict the hosts that sandboxed code can reach.                                                                                |
| `env`, at creation or for each `exec()`                              | `env`, at creation or for each command                                                | Keep the option name.                                                                                                                      |
| Variable references such as `${{Postgres.DATABASE_URL}}`             | No equivalent                                                                         | Read the values in your application and pass them in.                                                                                      |
| Secrets passed as environment variables                              | [Brokering rules](https://vercel.com/docs/sandbox/concepts/firewall) with `transform` | Optional. Rules add a credential after the request leaves the sandbox, and work together with an allow list.                               |

### CLI commands

Replace `railway sandbox` with [Sandbox CLI](https://vercel.com/docs/sandbox/sdk/cli) commands that take a sandbox name.

| Railway CLI                                                  | Sandbox CLI                                                      | What you change                                                                                    |
| ------------------------------------------------------------ | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| `railway sandbox create`                                     | `sandbox create --name <sandbox-name>`                           | Name each sandbox. Railway's CLI tracks an active sandbox instead.                                 |
| `--idle-timeout-minutes 30`                                  | `--timeout 30m`                                                  | The session stops at the timeout, whether or not the sandbox is idle.                              |
| `--variable KEY=VALUE`                                       | `--env KEY=VALUE`                                                | Resolve Railway variable references before you pass a value.                                       |
| `--private-network --domain 8080`                            | `--publish-port 8080`                                            | Print the port's URL with `sandbox domain <sandbox-name> 8080`.                                    |
| `--checkpoint <checkpoint-name>`                             | `--snapshot <snapshot-id>`                                       | Pass a snapshot ID, or reconnect to a named sandbox instead.                                       |
| `railway sandbox exec -- <command>`                          | `sandbox exec <sandbox-name> -- <command>`                       | Wrap pipelines in `bash -c`. The Sandbox CLI passes the command and its arguments without a shell. |
| `railway sandbox exec --detach`, reattached with `--session` | `sandbox exec --detach`, then `sandbox commands logs`            | Store the command ID that `--detach` prints.                                                       |
| `railway sandbox ssh`                                        | `sandbox connect <sandbox-name>`                                 | Remove the SSH key setup. `sandbox connect` opens an interactive shell without one.                |
| `railway sandbox forward 8080:3000`                          | No equivalent                                                    | Publish the port with `--publish-port 3000` at creation.                                           |
| `railway sandbox checkpoint create <checkpoint-name>`        | `sandbox snapshot <sandbox-name> --stop`                         | A snapshot stops the session. A persistent sandbox also saves its files on every stop.             |
| `railway sandbox fork`                                       | `sandbox fork <sandbox-name>`                                    | The fork starts from the source's latest snapshot.                                                 |
| `railway sandbox destroy`                                    | `sandbox stop <sandbox-name>` or `sandbox remove <sandbox-name>` | `stop` keeps a persistent sandbox's files. `remove` deletes the sandbox.                           |
| `railway sandbox list`                                       | `sandbox list`                                                   | Add `--all` to include stopped sandboxes.                                                          |

## Steps

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

Search for the `railway` package, `railway sandbox` CLI calls, and Railway tokens, then trace aliases through your code. Match the results to the steps below and identify features that need a replacement.

```bash
grep -rlE \
  -e "['\"]railway['\"]" \
  -e 'railway +(sandbox|sandboxes|sbx)([^a-zA-Z]|$)' \
  -e 'RAILWAY_(API_TOKEN|TOKEN|ENVIRONMENT_ID)' \
  -e 'backboard\.railway\.com|/http/exec' \
  --include="*.ts" --include="*.tsx" --include="*.mts" \
  --include="*.cts" --include="*.js" --include="*.jsx" \
  --include="*.mjs" --include="*.cjs" --include="*.json" \
  --include="*.sh" --include="*.yml" --include="*.yaml" \
  --include=".env*" --include="Makefile" --include="Dockerfile*" \
  --exclude="package-lock.json" \
  --exclude-dir=node_modules --exclude-dir=.git .
```

This search can match tokens used by other Railway deployment commands. Trace sandbox imports, CLI calls, and Railway GraphQL or [sandbox HTTP API](https://docs.railway.com/sandboxes/http-api) requests in the matching files. In migration notes, record environment variable names without their values, then use this table to find the relevant steps:

| In your code                                                                                                                                                                      | Go to                                                                                 |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| `Sandbox.template()`, `.withPackages()`, `.run()`, or `railway sandbox template build`                                                                                            | [Step 4](#4.-move-your-railway-template-to-a-vercel-image)                            |
| `Sandbox.create()`, `exec()`, `sandbox.files`, `resources`, or `region`                                                                                                           | [Step 5](#5.-replace-sandbox-creation,-commands,-and-file-operations)                 |
| `sandbox.checkpoint()`, `Sandbox.create("name")`, `Sandbox.connect()`, `fork()`, or `Sandbox.create(sandbox)`                                                                     | [Step 6](#6.-replace-checkpoints-with-named-sandboxes)                                |
| `idleTimeoutMinutes` or `sandbox.heartbeat()`                                                                                                                                     | [Step 7](#7.-replace-idle-timeouts-and-heartbeats-with-session-timeouts)              |
| `domains` or `sandbox.domains`                                                                                                                                                    | [Step 8](#8.-replace-railway-domains-with-public-ports)                               |
| `networkIsolation`, `env`, or `${{...}}` variable references                                                                                                                      | [Step 9](#9.-replace-railway-network-modes-and-variables)                             |
| `railway sandbox` commands in scripts                                                                                                                                             | [CLI commands](#cli-commands)                                                         |
| `*.railway.internal` addresses, `idleTimeoutMinutes: 0`, `exec({ sessionName })`, `handle.detach()`, `railway sandbox ssh`, `railway sandbox forward`, or fractional `cpu` values | [What doesn't map from Railway Sandboxes](#what-doesn%27t-map-from-railway-sandboxes) |

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

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

```bash
vercel link
```

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

```bash
vercel env pull
```

For local runs, load `.env.local` with Node.js's `--env-file=.env.local` option. Run `vercel env pull` again when the development OIDC token expires after 12 hours; deployed Vercel applications receive automatically managed tokens.

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.

> **Warning:**
>
> Keep Railway tokens until the migrated workloads pass verification. Retain tokens used by workloads remaining on Railway.

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

Keep the `railway` package until no workloads use it. Both packages export a class named `Sandbox`, so alias one import in any file that uses both providers, for example `import { Sandbox as RailwaySandbox } from 'railway'`.

For Python, install `vercel-sandbox` and use the [Python SDK reference](https://vercel.com/docs/sandbox/sdk/python).

### 4\. Move your Railway template to a Vercel image

Railway caches template builds on its standard image. Match the installed tools with a Vercel [managed image](https://vercel.com/docs/sandbox/concepts/images), custom image, or prepared snapshot:

| Railway base                                                                                   | Vercel replacement                                                                                                                                                                                   |
| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| The standard image with no template                                                            | The default `vercel/sandbox/universal` image, which includes Node.js 24, Python 3.14, git, and coding agents. To pin a Node.js major version, pass a managed image such as `vercel/sandbox/node:24`. |
| A template built with `.withPackages()` and `.run()`, or with `railway sandbox template build` | A Dockerfile with the matching `RUN` instructions, built into Vercel Container Registry                                                                                                              |
| A template or checkpoint that adds a few packages to the standard image                        | [A snapshot of a prepared sandbox](#start-many-sandboxes-from-one-snapshot), which keeps the default image's tools                                                                                   |
| `.workdir()`, which sets the directory for later build steps                                   | `WORKDIR` in the Dockerfile                                                                                                                                                                          |
| `.withEnv()` variables, which apply to build steps only                                        | `ARG` instructions in the Dockerfile, with values passed as `vercel vcr build docker . -- --build-arg KEY=value`                                                                                     |
| Docker commands in the sandbox                                                                 | A custom image or a prepared snapshot with a container engine installed, because Vercel's managed images don't include one                                                                           |

If a managed image meets your needs, [continue to sandbox creation](#5.-replace-sandbox-creation,-commands,-and-file-operations).

#### Build a custom image

Railway templates add tools to the standard image, so your Dockerfile must install every tool the workload needs, including any coding agent CLI. Install Docker and move the template's build steps into a Dockerfile. This Railway template installs two system packages and one global npm package:

```javascript
const template = Sandbox.template()
  .withPackages('ffmpeg', 'git')
  .run('npm install -g typescript');

const sandbox = await Sandbox.create(template);
```

The matching Dockerfile runs the same commands, and its `WORKDIR` sets `/app` as the directory where commands start:

```docker
FROM node:24
RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg git
RUN npm install -g typescript
WORKDIR /app
```

Custom images must target `linux/amd64`. The registry accepts images up to 15 GB, with no compressed layer above 2 GB. Build and push the image yourself, for example in CI, in place of Railway's first-use template build and cache. Log in, then build and push 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. Use the image's tag or digest when creating sandboxes. This example passes the repository and tag as `image`:

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

Vercel Sandbox skips `ENTRYPOINT` and `CMD`, so start the required processes with `runCommand()` after creation. Commands start in the Dockerfile's `WORKDIR`, or `/` if it has none; managed images use `/vercel`.

#### Install packages in a managed 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', 'ffmpeg'],
  sudo: true,
});
```

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

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

Route all sandbox operations through one application module, with a flag selecting Railway or Vercel for each new agent session. Add Vercel's creation, command, and file methods beside the Railway calls, retaining the Railway path until step 10. Credentials passed to `Sandbox.create()` select the sandbox's Vercel project.

#### TypeScript SDK calls

| Task                          | Railway Sandboxes                                                                      | Vercel Sandbox                                                                                                   |
| ----------------------------- | -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| Import                        | `import { Sandbox } from 'railway'`                                                    | `import { Sandbox } from '@vercel/sandbox'`                                                                      |
| Create a sandbox              | `Sandbox.create(options)`                                                              | `Sandbox.create(params)`                                                                                         |
| Set the lifetime              | `idleTimeoutMinutes`, in idle minutes                                                  | `timeout`, in milliseconds                                                                                       |
| Set resources                 | `resources: { cpu, memoryGB }`                                                         | `resources: { vcpus }`                                                                                           |
| Run a command                 | `sandbox.exec('node main.mjs')` or `sandbox.execHttp('node main.mjs')`                 | `sandbox.runCommand('node', ['main.mjs'])`                                                                       |
| Run a shell command           | `sandbox.exec('npm ci && npm test')`                                                   | `sandbox.runCommand('bash', ['-c', 'npm ci && npm test'])`                                                       |
| Set the working directory     | `exec(command, { cwd })`                                                               | `runCommand({ cmd, args, cwd })`                                                                                 |
| Set a command timeout         | `timeoutSec`, in seconds                                                               | `timeoutMs`, in milliseconds                                                                                     |
| Read output                   | `result.stdout`                                                                        | `await result.stdout()`                                                                                          |
| Get the exit code             | `result.exitCode`                                                                      | `result.exitCode`                                                                                                |
| Write to stdin                | `exec(command, { stdin: true })`, then `handle.stdin.write()` and `handle.stdin.end()` | `runCommand({ cmd, args, stdin: true, detached: true })`, then `command.writeStdin()` and `command.closeStdin()` |
| Leave a command running       | `handle.detach()`                                                                      | `detached: true` when you start the command                                                                      |
| List a sandbox's commands     | `sandbox.sessions()`                                                                   | No equivalent. Store each `command.cmdId`.                                                                       |
| Write a file                  | `sandbox.files.write(path, data)`                                                      | `sandbox.writeFiles([{ path, content }])`                                                                        |
| Read a file                   | `sandbox.files.read(path)`                                                             | `sandbox.fs.readFile(path, 'utf8')`, or `sandbox.readFileToBuffer({ path })` for bytes                           |
| List, create, or remove paths | `files.list()`, `files.mkdir()`, and `files.remove()`                                  | `sandbox.fs.readdir()`, `sandbox.fs.mkdir(path, { recursive: true })`, and `sandbox.fs.rm()`                     |
| Find a sandbox                | `Sandbox.connect(id)`                                                                  | `Sandbox.get({ name })`                                                                                          |
| List sandboxes                | `Sandbox.list()`                                                                       | `Sandbox.list()`, which can filter on one tag                                                                    |
| Manage saved state            | `Sandbox.checkpoints()` and `Sandbox.deleteCheckpoint()`                               | `sandbox.listSnapshots()` and `snapshot.delete()`                                                                |
| End a sandbox                 | `sandbox.destroy()`                                                                    | `sandbox.stop()` or `sandbox.delete()`                                                                           |

This script writes and runs a file in the token's Railway environment:

```javascript
import { Sandbox } from 'railway';

const sandbox = await Sandbox.create({
  idleTimeoutMinutes: 10,
  resources: { cpu: 2, memoryGB: 4 },
  env: { NODE_ENV: 'production' },
});

try {
  await sandbox.files.write('/app/main.mjs', 'console.log(21 * 2)');

  const result = await sandbox.exec('node /app/main.mjs', { timeoutSec: 60 });
  console.log(result.stdout);
  console.log('exit code', result.exitCode);
} finally {
  await sandbox.destroy();
}
```

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

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

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

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

  const result = await sandbox.runCommand({
    cmd: 'node',
    args: ['main.mjs'],
    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. Its 2 vCPUs come with 4 GB of memory, which matches the Railway sample's `cpu: 2` and `memoryGB: 4`. Railway sets the two values independently, so check the [size conversions](#fractional-vcpus-and-larger-sizes) for other combinations.

The `timeout` stops the session 10 minutes after creation, whereas Railway's `idleTimeoutMinutes` destroys the sandbox after 10 idle minutes. `persistent: false` keeps this example's behavior of discarding files when the sandbox stops.

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

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

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

#### Differences to check in every call

Railway's `exec()` runs a command string in a login shell, while Vercel runs the binary you specify with an argument array. Use `bash -c` for pipes, redirection, `&&`, or variable expansion, and `bash -lc` for commands that depend on a shell profile.

When reading results, replace Railway's string properties with Vercel's async methods, such as `await result.stdout()`, and check `exitCode` before using the output because neither SDK throws for a nonzero exit.

Set resources, timeout, and region explicitly because the defaults differ:

| Provider and plan | Resources     | Timeout          | Region                            |
| ----------------- | ------------- | ---------------- | --------------------------------- |
| Railway Hobby     | 4 vCPUs, 4 GB | 30 idle minutes  | `us-west2`                        |
| Railway Pro       | 8 vCPUs, 8 GB | 30 idle minutes  | `us-west2`                        |
| Vercel            | 2 vCPUs, 4 GB | 5-minute session | Project default, otherwise `iad1` |

Railway takes minutes for `idleTimeoutMinutes` and seconds for `timeoutSec`. Vercel's TypeScript SDK takes milliseconds for session and command timeouts and extensions. Its `sfo1` region is San Francisco, and `sin1` is Singapore.

#### File paths and sandbox cleanup

Railway's files API takes absolute paths and creates missing parent directories on writes. Its examples use `/app`; relative paths on Vercel managed images resolve from `/vercel`. Before `writeFiles()`, create missing directories with `sandbox.mkDir()`, or use `sandbox.fs.mkdir(path, { recursive: true })` for nested paths. Managed images run as `ubuntu` or `arch` with passwordless sudo. Pass `sudo: true` when a command needs root.

Stopping a persistent Vercel sandbox saves a snapshot that counts toward Snapshot Storage; use `persistent: false` to discard a one-off job's files. Both SDKs support `await using` with `Sandbox.create()` on Node.js 24+, or on Node.js 22 with TypeScript 5.2+ compilation. Scope exit destroys a Railway sandbox and stops a Vercel sandbox. Handles from `Sandbox.get()` and `Sandbox.getOrCreate()` aren't disposable, so stop named sandboxes in a `finally` block.

#### Background commands and streamed output

Railway's `exec()` streams output through `onStdout` and `onStderr`:

```javascript
const handle = sandbox.exec('for i in 1 2 3; do echo $i; sleep 1; done', {
  onStdout: (chunk) => process.stdout.write(chunk),
});

const result = await handle;
console.log('exit code', result.exitCode);
```

On Vercel, pass writable streams such as `process.stdout` as the `stdout` and `stderr` options of `runCommand()` to stream a command that you wait for. For a long-running process, use a detached command. 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);
```

Railway keeps a sandbox running while an `exec()` command runs. Vercel stops the session at its timeout even if a command is still running, so set a `timeout` that covers your longest command, [as described in step 7](#7.-replace-idle-timeouts-and-heartbeats-with-session-timeouts). To stop a command early, replace `handle.kill()` with `command.kill()`; both send a `TERM` signal by default.

Vercel Sandbox closes a connection that carries no data for 340 seconds, and 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 checkpoints with named sandboxes

Use a named persistent sandbox in place of capturing and tracking a Railway checkpoint for each agent session.

#### Reconnect to a sandbox by name

On Railway, your application captures a checkpoint before it destroys the sandbox, then creates a new sandbox from that checkpoint. The excerpt assumes that `sandbox` and `sessionId` identify the current session.

```javascript
// End of an agent session
await sandbox.checkpoint(`session-${sessionId}`);
await sandbox.destroy();

// Next agent session
const next = await Sandbox.create(`session-${sessionId}`);
```

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:

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

The Vercel sample prints `draft`. Your application stores the sandbox name instead of a checkpoint name and no longer captures checkpoints before teardown. This name is unique within its Vercel project and cannot change; resuming the sandbox starts a new session with its own timeout.

#### Set snapshot retention and handle missing state

Railway keeps checkpoints until you delete them, and reusing a checkpoint name replaces the saved copy. Vercel creates a snapshot on every stop and keeps earlier snapshots until they expire. Configure retention and deletion according to the copies you need to keep:

| What you need to control                | Vercel setting                                                                                                                    |
| --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| Expiration after last use               | The default is 30 days. Set `snapshotExpiration` in milliseconds to change it.                                                    |
| Disabling automatic expiration          | Set `snapshotExpiration` to `0` to disable expiration.                                                                            |
| Only the latest snapshot                | Set `keepLastSnapshots: { count: 1 }`.                                                                                            |
| Snapshots left after deleting a sandbox | `sandbox.delete()` preserves snapshots by default. Enable `deleteOrphanSnapshots` to remove snapshots that no other sandbox uses. |

If a snapshot expires, `getOrCreate()` with `resume: true` deletes the stale sandbox, creates one with the same name, and runs `onCreate`. Without immediate resume, it returns the existing sandbox, whose first resume fails with `snapshot_not_found`.

#### Restart processes after a resume

A Railway checkpoint and a Vercel snapshot both keep files without running processes, so restart the processes your application needs after each resume. In the TypeScript SDK, request a resume and use lifecycle hooks to start the server:

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

const sessionId = 'your-session-id';

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

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

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

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

#### Start many sandboxes from one snapshot

To start many sandboxes from one prepared environment, as you would from one Railway checkpoint or template, 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,
  },
});
let snapshot;
try {
  const result = await base.runCommand('npm', ['install']);
  if (result.exitCode !== 0) {
    throw new Error(await result.stderr() || 'Dependency installation failed');
  }
  snapshot = await base.snapshot();
} finally {
  await base.stop();
}

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

Calling `base.snapshot()` saves files and stops the session. Railway keeps checkpoints and template builds until you delete them, so pass `{ expiration: 0 }` to `snapshot()` to keep a base snapshot the same way. Use `Sandbox.fork()` with a `sourceSandbox` name to fork that sandbox's current 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.

#### Copy files from existing Railway checkpoints

Vercel Sandbox can't read a Railway checkpoint, so create a Railway sandbox from the checkpoint and archive the session files you need. This script assumes those files live in `/app`. Set `checkpointName` and `sourceDir` for your application, and rebuild system packages and tools in step 4.

```javascript
import { writeFile } from 'node:fs/promises';
import { Sandbox } from 'railway';

const checkpointName = 'session-123';
const sourceDir = '/app';

const sandbox = await Sandbox.create(checkpointName);

try {
  const result = await sandbox.exec(
    'tar -czf /tmp/workspace.tgz .',
    { cwd: sourceDir },
  );
  if (result.exitCode !== 0) {
    throw new Error(result.stderr);
  }

  const archive = await sandbox.files.read('/tmp/workspace.tgz', {
    format: 'bytes',
  });
  await writeFile('./workspace.tgz', archive);
} finally {
  await sandbox.destroy();
}
```

The `bytes` format loads the whole archive into memory. For larger archives, read with `format: 'stream'` and write the stream to a file. Destroying the temporary sandbox preserves its source checkpoint. To export all sessions, call `Sandbox.checkpoints()` and use each entry's `key` as the checkpoint name.

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

Before creating the destination, match its settings to the sandbox your application expects. Set the image and environment variables now because `sandbox.update()` cannot change them later. `Sandbox.getOrCreate()` also ignores creation settings when the name already exists. Add the required `--image`, `--vcpus`, `--publish-port`, `--env`, `--region`, and `--snapshot-expiration` flags to `sandbox create`.

The commands below use the default managed image. For a custom image, replace `/vercel` with its working directory. Run from the linked project, or select the project and team with `--project` and `--scope`. Use a new destination name for each import so a rerun cannot overwrite an existing session's files.

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

### 7\. Replace idle timeouts and heartbeats with session timeouts

Railway destroys a sandbox after `idleTimeoutMinutes` without activity, and commands or `heartbeat()` calls reset that timer. A Vercel session stops at a fixed `timeout`, which defaults to 5 minutes and can reach 45 minutes on Hobby or 24 hours on Pro and Enterprise. Vercel Sandbox has no idle timeout, so your application decides when a session ends.

| Railway behavior                                       | Vercel replacement                                                                                                   |
| ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- |
| `idleTimeoutMinutes: 30`                               | `timeout: 30 * 60 * 1000` as the session's upper bound, plus `sandbox.stop()` when work ends                         |
| `sandbox.heartbeat()` while work continues             | `sandbox.extendTimeout()` with the time to add, in milliseconds                                                      |
| A running `exec()` command defers teardown             | A `timeout` long enough for your longest command, because the session stops at its timeout even while a command runs |
| An idle sandbox is destroyed and its files are deleted | The session stops, and a persistent sandbox keeps its files                                                          |

To keep a session alive while a user or agent is active, move its deadline forward where your Railway code called `heartbeat()`:

```javascript
const IDLE_MS = 30 * 60 * 1000;

async function keepAlive(sandbox) {
  const expiresAt = sandbox.expiresAt?.getTime() ?? Date.now();
  const extension = Date.now() + IDLE_MS - expiresAt;
  if (extension > 0) {
    await sandbox.extendTimeout(extension);
  }
}
```

`sandbox.expiresAt` holds the time the current session stops. The helper asks for a deadline 30 minutes after the latest activity, and a session can't outlast your plan's maximum session duration. `extendTimeout()` resumes a stopped sandbox, so call the helper only for sessions that should be running. To extend only a running session, call `sandbox.currentSession().extendTimeout()` instead.

Call `sandbox.stop()` when work ends. If sessions should stop after inactivity, track activity in your application and have a background worker check that no jobs are running before stopping an idle session. Workloads using `idleTimeoutMinutes: 0` need the [always-on alternative](#always-on-sandboxes).

From a terminal, extend a running session 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. The command extends the running session's deadline and leaves the saved timeout for future sessions unchanged. Creation-time `timeout` settings apply only when `Sandbox.create()` or `Sandbox.getOrCreate()` creates a sandbox; use `sandbox.update({ timeout })` to change the saved timeout on an existing sandbox.

### 8\. Replace Railway domains with public ports

Replace Railway's `domains` with Vercel's `ports` and retrieve each public URL with `sandbox.domain(port)`. Both excerpts assume you've uploaded `server.js` and configured it to listen on `0.0.0.0` at port 8000.

```javascript
const sandbox = await Sandbox.create({
  networkIsolation: 'PRIVATE',
  domains: [{ port: 8000 }],
});

sandbox.exec('node /app/server.js');

await sandbox.refresh();
const route = sandbox.domains.find((entry) => entry.port === 8000);
console.log(`https://${route?.domain}`);
```

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

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

await sandbox.runCommand({
  cmd: 'node',
  args: ['server.js'],
  detached: true,
});

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

Railway publishes domains only in `PRIVATE` mode, which also connects the sandbox to the environment's private network. Vercel needs no network-mode setting to expose a port. Both products publish URLs that anyone can reach, so [authenticate callers in your server](#protect-a-published-port). If you used `railway sandbox forward` instead of a domain, [publish the port and protect it with a token](#ssh-and-local-port-forwarding).

| Port behavior          | What changes on Vercel                                                                                                        |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| URL format             | Read the full URL, including `https://`, from `sandbox.domain(port)`. Railway's `prefix` option has no equivalent.            |
| Number of ports        | Vercel allows up to 15 exposed ports; Railway allows up to 10 domains.                                                        |
| Changing ports         | Railway fixes domains at creation. `sandbox.update({ ports })` replaces Vercel's exposed port list.                           |
| Requests while stopped | Vercel returns HTTP 410. Resume the sandbox and restart its server with the lifecycle hooks in step 6 before sending traffic. |

### 9\. Replace Railway network modes and variables

#### Map network modes to a network policy

Railway's `networkIsolation` option decides whether a sandbox joins the environment's private network, and outbound internet access stays on in both modes. Vercel's `networkPolicy` option controls outbound access instead:

| Railway setting                                                                  | Vercel `networkPolicy`                                                                                     |
| -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `networkIsolation: "ISOLATED"`, the default                                      | `'allow-all'`, the default                                                                                 |
| `networkIsolation: "PRIVATE"`, set only to publish a domain                      | `'allow-all'`, with the port listed in `ports`                                                             |
| `networkIsolation: "PRIVATE"`, set to reach `*.railway.internal` services        | No equivalent. [Choose a replacement for each private service](#private-networking-with-railway-services). |
| No outbound access, which Railway's docs don't describe for sandboxes            | `'deny-all'`                                                                                               |
| Access to selected hosts only, which Railway's docs don't describe for sandboxes | `{ allow: ['api.openai.com', 'github.com', '*.github.com'] }`                                              |

A network policy is optional after the migration, because the default matches Railway's outbound access. To limit the hosts that sandboxed code can reach, set the policy at creation or replace it with `update()`. Updates replace the policy in full:

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

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

Vercel's `*.github.com` rule covers subdomains only, so list `github.com` separately. Domain rules match on the TLS hostname, and `'deny-all'` also blocks DNS.

#### Pass variables as environment variables

Railway and Vercel both take an `env` option at creation and for each command, so keep the option name. Pass values from your application through `env` when creating the sandbox or running a command:

```javascript
const databaseUrl = process.env.SANDBOX_DATABASE_URL;
if (!databaseUrl) throw new Error('SANDBOX_DATABASE_URL is required');
const apiToken = process.env.API_TOKEN;
if (!apiToken) throw new Error('API_TOKEN is required');

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

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

Railway resolves references such as `${{shared.NPM_TOKEN}}` or `${{Postgres.DATABASE_URL}}` when it creates a sandbox. Its CLI also accepts the bare `Service.VARIABLE` form, as in `--variable DATABASE_URL=Postgres.DATABASE_URL`, so check scripts for both forms. Vercel passes `env` values through unchanged.

For a backend on Railway, add the reference to the backend service's variables and pass its resolved `process.env` value to Vercel. If `DATABASE_URL` points at an internal address such as `postgres.railway.internal`, use [a public address for the service](#private-networking-with-railway-services).

#### Use managed npm credentials

For private packages, replace npm tokens with [managed npm credentials](https://vercel.com/docs/sandbox/concepts/credentials):

1. Add `NPM_TOKEN` or `NPM_RC` to the Vercel project's Development environment when your backend uses an access token. With OIDC, use the environment named by the token.
   
2. Set `credentials: { npm: true }` at creation so the firewall authenticates package downloads without putting the token in the sandbox. If you restrict egress, include the registry hosts in the allow list.
   

> **Warning:**
>
> Keep secrets out of command arguments, because Vercel Sandbox can store arguments and return them in command API responses.

#### Broker credentials with firewall rules

Code in a sandbox can read every value in its environment, on Railway and on Vercel. To keep a credential outside the sandbox, add a brokering rule, which sets the header after the request leaves the sandbox:

```javascript
const apiToken = process.env.API_TOKEN;
if (!apiToken) throw new Error('API_TOKEN is required');

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

The `'*'` entry allows requests to other domains. Remove it to restrict access to the named domains. To control which requests receive the credential, add a `match` for the path, method, query string, or headers. Finish the domain's rules with a `response` whose `statusCode` is `403` if unmatched requests must be rejected.

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

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 session workspaces being moved. Capture a final checkpoint for each one, then export, import, and verify the files before routing those sessions to Vercel.
   
3. Switch the flag for new sessions and monitor output and errors. Keep existing Railway sessions on Railway until they finish or their state has been imported.
   

#### Keep a rollback path until cleanup

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

After the rollback period, remove only the Railway call sites and data that migrated workloads no longer need. Keep checkpoints, templates, and variables used by workloads remaining on Railway. Destroy any migrated Railway sandbox that still runs with the idle timeout disabled. Remove the package and revoke its tokens only after confirming that no other application or job uses them.

## What doesn't map from Railway Sandboxes

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

### Private networking with Railway services

A Railway sandbox in `PRIVATE` mode joins its environment's private network and reaches services at internal addresses such as `postgres.railway.internal`. A Vercel sandbox runs outside Railway, so those addresses don't resolve there. Choose a replacement for each service the sandbox called:

| What the sandbox reached               | Replacement                                                                                                                                                                                                                                                |
| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| An HTTP service at an internal address | Give the service a [public domain](https://docs.railway.com/networking/public-networking) and require authentication on it. Allow that domain in `networkPolicy`, and [broker the credential as shown in step 9](#broker-credentials-with-firewall-rules). |
| A database at an internal address      | Add public access to the database, which creates a [TCP Proxy](https://docs.railway.com/networking/tcp-proxy), and pass the sandbox the public connection string.                                                                                          |
| A service that must stay private       | Keep the call in your backend on Railway. Have the sandbox return its result to your backend, or call an authenticated endpoint that your backend exposes.                                                                                                 |
| A private network outside Railway      | Run a VPN client in the sandbox with `sudo`, or attach the sandbox to a [Secure Compute](https://vercel.com/docs/sandbox/concepts/secure-compute) network to reach an AWS VPC. Secure Compute is an additional Enterprise purchase.                        |

#### Connect a Railway database

The TCP Proxy is public, and sandboxed code can read the connection string. Limit the database role to the task and use a development database where possible.

1. For a Railway PostgreSQL database, open the service's **Settings**, select **Networking**, and add **Public Access**. Railway creates a TCP Proxy and sets `DATABASE_PUBLIC_URL` on the database service. MySQL, Redis, and MongoDB services use `MYSQL_PUBLIC_URL`, `REDIS_PUBLIC_URL`, and `MONGO_PUBLIC_URL`.
   
2. On your backend service, set `SANDBOX_DATABASE_URL` to `${{Postgres.DATABASE_PUBLIC_URL}}`. Replace `Postgres` with your database service's name, then pass the resolved value when creating the sandbox:
   

```javascript
const databaseUrl = process.env.SANDBOX_DATABASE_URL;
if (!databaseUrl) throw new Error('SANDBOX_DATABASE_URL is required');

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

Vercel's domain rules support HTTPS and Postgres. For Postgres, allow the proxy hostname and use `sslmode=require` or stricter. For other databases, test the connection under your policy or allow the proxy's IP range with `subnets.allow`. Railway services calling into the sandbox also need to switch to its public port URL and [authenticate those requests](#protect-a-published-port).

### Always-on sandboxes

With `idleTimeoutMinutes: 0`, a Railway sandbox runs until you destroy it. A Vercel session lasts up to 45 minutes on Hobby or 24 hours on Pro and Enterprise, and its processes stop when the session ends.

For a long-lived workspace, use a named persistent sandbox. Its files carry over from one session to the next, and your backend resumes it and restarts its processes on demand, as shown in step 6. [Lifecycle webhooks](https://vercel.com/docs/sandbox/lifecycle-webhooks), available on Pro and Enterprise plans, can notify your backend when a session changes state.

For a process that must stay reachable without interruption, such as a queue consumer or a production API, deploy it as a service, on Railway or another platform, instead of running it in a sandbox. Continuously running queue consumers have a [migration path to Vercel Daemons](https://vercel.com/kb/guide/migrate-railway-workers-to-vercel-daemons).

### Forks and checkpoints of a running sandbox

Railway's `fork()` and `checkpoint()` copy a running sandbox's disk while it keeps running. On Vercel, `sandbox.snapshot()` saves the files and stops the session, and `Sandbox.fork()` starts from the source's current saved snapshot without the unsaved changes of a running session. To branch from work in progress, stop the source sandbox, then fork it by name:

```javascript
const source = await Sandbox.get({ name: 'base-environment' });
await source.stop();

const branch = await Sandbox.fork({
  sourceSandbox: 'base-environment',
  name: 'experiment-1',
});
```

The next command on `source` resumes it in a new session, so restart its processes as shown in step 6. For save points during a long task, write progress to a file and snapshot it at a natural pause, because snapshots end the session they capture.

Railway forks copy the disk and use their own idle timeout, size, network mode, domains, and variables. Vercel forks inherit the source's size, timeout, network policy, tags, environment variables, and region; supplied values replace those settings. Drive mounts are excluded, so pass `mounts` again when needed.

### Durable command sessions

Railway `exec()` commands use durable sessions by default. Another process can reattach with `exec({ sessionName })` and receive roughly the last 8 MiB of output. On Vercel, save a detached command's ID to retrieve it after a client disconnect, while its sandbox session is still running:

```javascript
// The process that starts the work
const sandbox = await Sandbox.get({ name: `session-${sessionId}` });
const command = await sandbox.runCommand({
  cmd: 'bash',
  args: ['-c', 'npm run agent > agent.log 2>&1'],
  detached: true,
});
await saveCommandId(sessionId, command.cmdId);

// A later process, while the same session is still running
const later = await Sandbox.get({ name: `session-${sessionId}` });
const running = await later.getCommand(await loadCommandId(sessionId));
const finished = await running.wait();
console.log('exit code', finished.exitCode);
console.log(await later.fs.readFile('agent.log', 'utf8'));
```

`saveCommandId()` and `loadCommandId()` stand for your application's session store. Keep command IDs with the session that created them, and start the command again after resuming if that session stops. Because `sandbox.getCommand()` can itself resume a stopped sandbox, use `currentSession()` and its `getCommand()` method for a lookup restricted to the current session.

Save output needed after the session ends to a file so the snapshot retains it. In terminal workflows, `sandbox exec --detach` prints a command ID. Pass the sandbox name and that ID to `sandbox commands logs` to stream output.

### SSH and local port forwarding

`railway sandbox ssh` opens a shell with an SSH key on your Railway account, and `railway sandbox forward` maps a local port to a port in the sandbox. Vercel Sandbox needs no SSH key and has no local port forwarding. Open an interactive shell with `sandbox connect`, which the Sandbox CLI also accepts as `sandbox ssh`:

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

Port forwarding kept the server private to your machine and carried any TCP protocol. Vercel port URLs are public and support HTTP and WebSocket traffic, so raw TCP needs a different service or protocol. To reach a server in the sandbox from your machine, publish its port, start the server, and print the port's public URL:

```bash
sandbox create --name preview-123 --publish-port 3000 --timeout 30m
sandbox copy ./server.js preview-123:/vercel/server.js
sandbox exec --detach preview-123 -- node server.js
sandbox domain preview-123 3000
```

### Protect a published port

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 this Node.js helper as `wait-for-http.mjs`. It retries while the server starts and throws if the service stays unavailable:

```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');
}
```

Save `server.mjs` and `call-protected-service.mjs` beside the helper. 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.

### Fractional vCPUs and larger sizes

Railway sets `cpu` and `memoryGB` independently and accepts fractional `cpu` values such as `0.5`. Current Pro limits allow up to 24 vCPUs and 24 GB, with 32 vCPUs and 32 GB available in some older Pro workspaces.

Vercel sandboxes have 1 vCPU or an even number up to 32, with 2 GB of memory per vCPU. Choose the smallest Vercel size that covers both Railway values:

| Railway `resources`         | Vercel `resources`          | Vercel plan               |
| --------------------------- | --------------------------- | ------------------------- |
| `{ cpu: 0.5, memoryGB: 1 }` | `{ vcpus: 1 }`, with 2 GB   | Hobby, Pro, or Enterprise |
| `{ cpu: 2, memoryGB: 4 }`   | `{ vcpus: 2 }`, with 4 GB   | Hobby, Pro, or Enterprise |
| `{ cpu: 2, memoryGB: 8 }`   | `{ vcpus: 4 }`, with 8 GB   | Hobby, Pro, or Enterprise |
| `{ cpu: 8, memoryGB: 8 }`   | `{ vcpus: 8 }`, with 16 GB  | Pro or Enterprise         |
| `{ cpu: 24, memoryGB: 24 }` | `{ vcpus: 24 }`, with 48 GB | Enterprise                |

A Railway Pro sandbox with more than 8 vCPUs or more than 16 GB of memory needs a Vercel Enterprise plan. On Pro, split the work across several sandboxes where the task allows it. Measure peak CPU and memory before you choose a size, as described in step 10.

## Troubleshooting

Each symptom in this table traces to a behavior that differs between Railway Sandboxes and Vercel Sandbox.

| What you observe                                                      | What to check                                                                                                                                                                                                                               |
| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Authentication fails locally after it worked earlier                  | The development OIDC token expires after 12 hours. Run `vercel env pull` again.                                                                                                                                                             |
| A command that ran on Railway fails to start                          | `runCommand()` takes a binary and an argument array. Split the Railway command string, or wrap it in `bash -c`.                                                                                                                             |
| Pipes, redirection, or `$VARIABLES` reach the program as literal text | `runCommand()` doesn't use a shell. Wrap the command in `bash -c`.                                                                                                                                                                          |
| `result.stdout` logs a function instead of text                       | `stdout()` and `stderr()` are async methods on Vercel. Call `await result.stdout()`.                                                                                                                                                        |
| A command or file write fails with a permission error                 | Commands run as the image's default user instead of root. Write under `/vercel`, or pass `sudo: true`.                                                                                                                                      |
| A file written to `/app` on Railway isn't where your code expects     | Managed images use `/vercel` as the working directory. Use relative paths or paths under `/vercel`, or set `WORKDIR /app` in a custom image.                                                                                                |
| A sandbox stops while a command is still running                      | A session ends at its `timeout`, which defaults to 5 minutes, even while a command runs. Set a longer `timeout`, or call `extendTimeout()`.                                                                                                 |
| A sandbox or command times out much sooner than on Railway            | Vercel's TypeScript SDK takes milliseconds. Multiply `idleTimeoutMinutes` by 60,000 and `timeoutSec` by 1,000.                                                                                                                              |
| A connection to a `*.railway.internal` address fails                  | A Vercel sandbox runs outside Railway's private network. [Reach the service through a public domain or a TCP Proxy](#private-networking-with-railway-services).                                                                             |
| `${{Service.VARIABLE}}` appears as literal text in the sandbox        | Railway resolves variable references only for its own sandboxes. Read the value in your application and pass it through `env`.                                                                                                              |
| Requests to a sandbox URL return HTTP 410                             | The sandbox is stopped. Run a command to resume the sandbox, then restart your server.                                                                                                                                                      |
| A server that ran before a stop isn't running after a resume          | Vercel restores files, not processes. Start the server in `onCreate` and `onResume`, as shown in step 6.                                                                                                                                    |
| Creation fails for a size that worked on Railway                      | Vercel sizes are 1 vCPU or an even number, up to your plan's maximum. [Convert the Railway size](#fractional-vcpus-and-larger-sizes) before you create the sandbox.                                                                         |
| `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`.                                                                               |
| 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`                        | Create the sandbox in the same region as its snapshot.                                                                                                                                                                                      |
| 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 Railway.

### 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 Railway Sandboxes](https://vercel.com/kb/guide/vercel-sandbox-vs-railway-sandboxes) for your workload
  
- Move the rest of your application by [migrating from Railway to Vercel](https://vercel.com/kb/guide/migrate-railway-to-vercel).
  

## Frequently asked questions

### Can I move Railway checkpoints to Vercel Sandbox directly?

No. Create a Railway sandbox from the checkpoint, archive the files, and read the archive with `sandbox.files.read()`. Use `sandbox copy` to transfer the archive to Vercel, then extract it into the sandbox's workspace.

### Can my application stay on Railway 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 a Vercel sandbox reach my Railway database?

Yes, through Railway's public TCP Proxy. Enable public access on the database and give the sandbox the public connection string for a role limited to its task. Railway's internal addresses are reachable only within its private network.

### Does Vercel Sandbox have an idle timeout like Railway's idleTimeoutMinutes?

No. Your application controls inactivity handling. Call `stop()` when work ends and `extendTimeout()` to move a running session's deadline forward. If the session times out, a persistent sandbox saves its files for the next resume.

### Do I need to rebuild my Railway templates for Vercel Sandbox?

Rebuild the tools your workload needs beyond the default image, which already contains Node.js 24, Python 3.14, git, and coding agents. Move the template's build steps into a Dockerfile for Vercel Container Registry, or run them in a sandbox and save a snapshot.

### Do commands run in a shell in Vercel Sandbox like they do with Railway's exec()?

No. `runCommand()` runs a binary with an argument array. Wrap a command in `bash -c` when it needs pipes, redirection, or variable expansion.

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

No. Stopping ends the running processes, and resuming restores the saved filesystem. Register an `onResume` hook in your TypeScript code to start servers and background jobs when the sandbox resumes.

### Can I run coding agents such as Claude Code or Codex in Vercel Sandbox?

Yes. The default image includes coding agents, and `sandbox create claude` or `sandbox create codex` starts a supported agent in a sandbox from your terminal. Pass each agent's credentials with `--env`, or sign in with the agent's own login.

### Can I run Docker in Vercel Sandbox?

Yes, after you install a container engine. Railway Sandboxes include the [Docker daemon and CLI](https://railway.com/changelog/2026-06-12-docker-in-sandboxes), and Vercel's managed images don't, so install Docker in a custom image or in a prepared sandbox that you snapshot. Commands run with sudo can start Docker or another container engine inside the microVM. Containers must trust the sandbox's [proxy CA certificate](https://vercel.com/docs/sandbox/concepts/security#trust-the-proxy-ca-in-containers) when they call domains with request-modifying firewall rules.

## Related Resources

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

## 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 Fly.io Sprites to Vercel Sandbox](/kb/guide/migrate-from-fly-io-sprites-to-vercel-sandbox): Migrate from Fly.io Sprites to Vercel Sandbox in TypeScript or Python, including images, persistent files, public ports, network policies, and 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>
```
