---
title: How to reconnect to a running Sandbox
description: Learn how to use `Sandbox.get()` to reconnect to an existing sandbox from a different process or after a script restart.
url: /kb/guide/how-to-reconnect-to-a-running-sandbox
canonical_url: "https://vercel.com/kb/guide/how-to-reconnect-to-a-running-sandbox"
published: 2026-01-29
last_updated: 2026-02-02
authors: Allen Zhou, Amy Burns
related:
  - /docs/projects
  - /docs/vercel-sandbox/concepts/snapshots
  - /docs/vercel-sandbox/sdk-reference
install_vercel_plugin: npx plugins add vercel/vercel-plugin
---
<!-- docsgraph:related -->
## Related pages

> **For AI agents:** Follow these links to understand how this page connects to the rest of the Vercel ecosystem. For the full cross-link map (inbound, outbound, prerequisites, and semantic neighbors), see the .graph.md link below.

- [Examples](https://vercel.com/docs/sandbox/working-with-sandbox?from=related) — Task-oriented examples for common Vercel Sandbox operations in TypeScript and Python.
- [Persistence](https://vercel.com/docs/sandbox/concepts/persistent-sandboxes?from=related) — Sandboxes automatically save their filesystem state when stopped and restore it when resumed. No manual snapshot managem
- [Run Commands in Vercel Sandbox](https://vercel.com/docs/sandbox/run-commands-in-sandbox?from=related) — Create isolated sandbox environments to run builds, tests, and commands safely.
- [JS SDK Reference](https://vercel.com/docs/sandbox/sdk-reference?from=related) — A comprehensive reference for the Vercel Sandbox JavaScript SDK, which lets you run code in a secure, isolated environme
- [Concepts](https://vercel.com/docs/sandbox/concepts?from=related) — Learn how Vercel Sandboxes provide on-demand, isolated compute environments for running untrusted code, testing applicat
- [How to use snapshots for faster sandbox startup](https://vercel.com/kb/guide/how-to-use-snapshots-for-faster-sandbox-startup?from=related) — Learn how to save sandbox state with snapshots and skip installation on future runs.
- [How to test a container image in Vercel Sandbox before deploying](https://vercel.com/kb/guide/test-container-image-vercel-sandbox?from=related) — Validate a container image before deploying by booting it as a custom Sandbox image from Vercel Container Registry \\(VCR

Full cross-link map for this page: [/kb/guide/how-to-reconnect-to-a-running-sandbox.graph.md](/kb/guide/how-to-reconnect-to-a-running-sandbox.graph.md)
<!-- /docsgraph:related -->


When you create a sandbox, it continues running until it times out or you explicitly stop it. If your script crashes, your connection drops, or you need to interact with the sandbox from a different process, you can reconnect using `Sandbox.get()`.

This is [different from snapshots](#key-differences:-sandbox.get-vs-snapshot.get), which save the sandbox state for later restoration. `Sandbox.get()` connects to a sandbox that is actively running.

## Prerequisites

You need the Vercel CLI, Node.js 22+, and a [Vercel project](https://vercel.com/docs/projects) to link your sandbox and generate an OIDC token.

## 1\. Set up the project

```bash
mkdir sandbox-reconnect-demo && cd sandbox-reconnect-demo
pnpm init
pnpm add @vercel/sandbox dotenv
pnpm add -D @types/node
vercel link
vercel env pull
```

This installs the SDK, links to your Vercel project, and creates `.env.local` with authentication credentials.

## 2\. Write the script

Create `index.ts` with the code below. It runs in two phases:

- Phase 1: Create a sandbox, persist its ID to disk, and exit
  
- Phase 2: Load the ID, call Sandbox.get() to reconnect
  

```typescript
import { config } from 'dotenv';
config({ path: '.env.local' });

import { Sandbox } from '@vercel/sandbox';
import { readFileSync, writeFileSync, existsSync, unlinkSync } from 'fs';

const ID_FILE = './sandbox-id.txt';

async function main() {
  if (existsSync(ID_FILE)) {
    const id = readFileSync(ID_FILE, 'utf-8').trim();
    try {
      const sandbox = await Sandbox.get({ sandboxId: id });
      console.log(`Reconnected to ${sandbox.sandboxId}`);

      // Do work here...

      await sandbox.stop();
      unlinkSync(ID_FILE);
    } catch {
      unlinkSync(ID_FILE);
      await createSandbox();
    }
  } else {
    await createSandbox();
  }
}

async function createSandbox() {
  const sandbox = await Sandbox.create({ timeout: 10 * 60 * 1000 });
  writeFileSync(ID_FILE, sandbox.sandboxId);
  console.log(`Created ${sandbox.sandboxId}, run again to reconnect`);
}

main().catch(console.error);
```

### With timing comparison

To measure the speedup from reconnecting vs cold start:

```typescript
import { config } from 'dotenv';
config({ path: '.env.local' });

import { Sandbox } from '@vercel/sandbox';
import { readFileSync, writeFileSync, existsSync, unlinkSync } from 'fs';

const ID_FILE = './sandbox-id.txt';
const TIME_FILE = './cold-start.txt';

const read = (f: string) => readFileSync(f, 'utf-8').trim();
const write = (f: string, v: string) => writeFileSync(f, v);
const rm = (f: string) => existsSync(f) && unlinkSync(f);

async function main() {
  if (existsSync(ID_FILE)) {
    const id = read(ID_FILE);
    const coldMs = existsSync(TIME_FILE) ? +read(TIME_FILE) : null;

    try {
      const start = Date.now();
      const sandbox = await Sandbox.get({ sandboxId: id });
      const reconnectMs = Date.now() - start;

      console.log(`Reconnected in ${(reconnectMs / 1000).toFixed(2)}s`);
      if (coldMs) {
        console.log(`Cold: ${(coldMs / 1000).toFixed(2)}s → ` +
          `${(coldMs / reconnectMs).toFixed(1)}x faster`);
      }
      await sandbox.stop();
    } catch {
      console.log('Sandbox expired, creating new...');
    }
    rm(ID_FILE);
    rm(TIME_FILE);
  } else {
    const start = Date.now();
    const sandbox = await Sandbox.create({ timeout: 10 * 60 * 1000 });
    write(ID_FILE, sandbox.sandboxId);
    write(TIME_FILE, String(Date.now() - start));
    console.log(`Created ${sandbox.sandboxId}, run again to reconnect`);
  }
}

main().catch(console.error);
```

## 3\. Test it out

Execute the script twice in quick succession:

```bash
pnpm dlx tsx index.ts
```

First execution:

```javascript
Created sbx_abc123, run again to reconnect
```

Second execution (before the 10-minute timeout):

```javascript
Reconnected in 0.31s
Cold: 2.34s → 7.5x faster
```

## Use cases for Sandbox.get()

- **Script recovery:** Reconnect after a crash without losing your running environment
  
- **Multi-process workflows:** Access the same sandbox from different scripts or terminals
  
- **CLI tools:** Separate sandbox lifecycle management from command execution
  
- **Interactive development:** Keep a sandbox warm between debugging sessions
  

## Handling expired sandboxes

If the sandbox timed out or was stopped, `Sandbox.get()` throws an error. Always wrap it in a try-catch:

```typescript
try {
  const sandbox = await Sandbox.get({ sandboxId });
  console.log('Reconnected successfully');
} catch (error) {
  console.log('Sandbox no longer available, creating a new one...');
  const sandbox = await Sandbox.create({ runtime: 'node22' });
}
```

## Performance

| Operation                      | Typical Time |
| ------------------------------ | ------------ |
| Create new sandbox             | ~2-3s        |
| Reconnect with `Sandbox.get()` | ~0.3s        |

The ~10x speedup makes `Sandbox.get()` ideal for keeping sandboxes warm between commands.

## Key differences: Sandbox.get() vs Snapshot.get()

|                 | Sandbox.get()          | Snapshot.get()         |
| --------------- | ---------------------- | ---------------------- |
| **Target**      | Running sandbox        | Saved state            |
| **Requirement** | Sandbox must be active | Sandbox can be stopped |
| **Persistence** | Until timeout          | 7 days                 |
| **Best for**    | Interactive sessions   | Reusable templates     |

## Next steps

- Learn about [snapshots](https://vercel.com/docs/vercel-sandbox/concepts/snapshots) for persisting sandbox state across sessions
  
- See the [Sandbox SDK reference](https://vercel.com/docs/vercel-sandbox/sdk-reference) for all available methods