# The TypeScript SDK

`@sandboxrouterio/sdk` is the Sandbox Router API ([The API](/docs/api)) as typed TypeScript methods: sandboxes and their execs, files, ports, metrics and logs; snapshots, images, pools, providers and your own provider accounts; MCP servers; connectors and their workspace accounts; your users' connections and sign-ins; and your workspace's settings, audit log and billing. It has no runtime dependencies and runs on Node 22 or later, Deno, Bun and Cloudflare Workers.

## Install the SDK

```sh
npm install @sandboxrouterio/sdk
```

## Connect it to your workspace

The SDK sends an API key from your workspace. Create one in the [console](https://console.sandboxrouter.io/) under **Settings**, as [The API](/docs/api) describes, and set it as `SANDBOXROUTER_API_KEY`:

```sh
export SANDBOXROUTER_API_KEY=<api-key>
export SANDBOXROUTER_NAMESPACE=<namespace>
```

A client reads `SANDBOXROUTER_API_KEY` when you don't pass `apiKey`, and `SANDBOXROUTER_NAMESPACE` when you don't pass `namespace`: your workspace's namespace, its slug, which the paths of its sandboxes, snapshots, images, pools and provider accounts name. Copy it from the console under **Settings** → **Workspace**, where it's the **Namespace** (see [Send the key](/docs/api#send-the-key)).

```ts
import { SandboxRouter } from "@sandboxrouterio/sdk";

const sandboxrouter = new SandboxRouter({ namespace: "acme" });
```

Every request acts in the key's workspace.

## Run a sandbox

```ts
const sandbox = await sandboxrouter.sandboxes.run({ metadata: { name: "build-agent" }, spec: { resources: { size: "m" },
  network: { egress: { mode: "allow", allow: [{ domain: "registry.npmjs.org" }] } } } });
if (sandbox.status?.phase !== "Running") throw new Error(sandbox.status?.conditions?.find((c) => c.type === "Ready")?.message);

const result = await sandboxrouter.sandboxes.exec.run("build-agent", { command: ["node", "--version"] });
console.log(result.exitCode, result.stdout);

await sandboxrouter.sandboxes.files.write("build-agent", "/workspace/hello.txt", "hello\n");
const text = await sandboxrouter.sandboxes.files.readText("build-agent", "/workspace/hello.txt");

await sandboxrouter.sandboxes.stop("build-agent");
await sandboxrouter.sandboxes.delete("build-agent");
```

`run` answers the sandbox once it runs or failed, holding as long as that takes; `create` answers at once, `Pending`, and `get(uid, { waitMs })` waits while it starts. `start` and `stop` answer at once: wait for the sandbox to settle with `get(name, { waitMs })`. To restart one, stop it, wait, and start it. `patch` changes its labels, egress, idle timeout or state, as a JSON merge patch. Every method that names a sandbox takes its name or its uid. Sandboxes are `sandboxrouter.io/v1` objects, `metadata`, `spec` and `status`, typed under `V1` (`V1.Sandbox`). An exec's command is an array, which runs as it is, or a string, which runs through `/bin/sh -c`. A command that exits nonzero isn't an error: read its `exitCode`. A stopped sandbox stays stopped until a start: an exec or a file call answers `not_running`.

### Long-running commands

An exec holds until the command ends. With `waitMs`, it answers once that long passed while the command still runs; read it by its `execId` later, or cancel it:

```ts
const job = await sandboxrouter.sandboxes.exec.run("build-agent", { command: ["make", "release"], detach: true, timeoutSeconds: 86_400, waitMs: 5_000 });
const done = await sandboxrouter.sandboxes.exec.get("build-agent", job.execId, { waitMs: 60_000 });
await sandboxrouter.sandboxes.exec.cancel("build-agent", job.execId);
```

A command's output arrives when it ends.

### Files, logs, metrics, ports and snapshots

```ts
await sandboxrouter.sandboxes.files.write("build-agent", "/workspace/app.js", bytes); // a file, whole
await sandboxrouter.sandboxes.files.delete("build-agent", "/workspace/app.js");

for await (const entry of sandboxrouter.sandboxes.followLogs("build-agent")) console.log(entry.kind, entry.message);

// its provider's own CPU, memory and disk samples, oldest first, null where it doesn't measure one
const { samples } = await sandboxrouter.sandboxes.metrics("build-agent", { from: new Date(Date.now() - 3_600_000) });

const { url, headers } = await sandboxrouter.sandboxes.port("build-agent", 3000); // its provider's own URL, while it runs; headers are a secret

// its provider's own, named as a sandbox is; Pending while its provider still makes it, then Ready
let snapshot = await sandboxrouter.snapshots.create({ metadata: { name: "nightly" }, spec: { sandboxRef: { name: "build-agent" } } });
const sandbox = await sandboxrouter.sandboxes.get("build-agent");
for await (const item of sandboxrouter.snapshots.list({ labelSelector: { [V1_SNAPSHOT_LABELS.sandboxUid]: sandbox.metadata.uid! } })) {
  console.log(item.metadata.name, item.status?.state); // one sandbox's snapshots, by the label of its uid
}
// A restore of a Pending snapshot is refused 409: read it again until it's made.
while (snapshot.status?.state === "Pending") {
  await new Promise((resolve) => setTimeout(resolve, 1_000));
  snapshot = await sandboxrouter.snapshots.get(snapshot.metadata.uid!);
}
// Ready restores; Inactive is renewed at its provider, then restored; Failed and Expired never will.
if (snapshot.status?.state === "Failed" || snapshot.status?.state === "Expired") {
  throw new Error(`snapshot ${snapshot.metadata.name} is ${snapshot.status.state}: ${snapshot.status.message ?? ""}`);
}
await sandboxrouter.sandboxes.run({ metadata: { name: "restored" }, spec: { from: { snapshotRef: { name: snapshot.metadata.name! } } } });
await sandboxrouter.snapshots.delete("nightly");
```

`V1_SNAPSHOT_LABELS` is exported by `@sandboxrouterio/sdk`.

`sandboxrouter.images`, `pools`, `platformPools`, `providers` and `providerConfigs` read and change the namespace's images, pools, the providers and your own provider accounts; `providers.autoOrder()` and `providers.setAutoOrder(order)` read and set your workspace's Auto order.

## MCP servers

```ts
const server = await sandboxrouter.mcpServers.create({
  name: "search",
  sandbox: { image: "registry.caas.sh/<tenant-id>/search-mcp@sha256:…", egress: ["api.search.example"] },
  transport: { http: { port: 8080 } },
});
```

[MCP servers](/docs/mcp) explains what each field does.

## Your users

`sandboxrouter.users` signs your users in and makes their connect links, one user at a time (see [Connect each user's account](/docs/connectors#connect-each-users-account)). Sign a user in to a connector they sign in to with a code, such as Codex (ChatGPT), before a sandbox of theirs needs it (see [Sign users in with a code](/docs/connectors#sign-users-in-with-a-code)); `waitForSignIn` waits until they have, calling `onCode` with each code to show them:

```ts
await sandboxrouter.users.signIn("user_123", "codex");
await sandboxrouter.users.waitForSignIn("user_123", "codex", { onCode: (signIn) => showToUser(signIn.code!, signIn.url!) });
const sandbox = await sandboxrouter.sandboxes.run({ spec: { user: "user_123", connectors: ["codex"] } });
```

`waitForSignIn` reads the user's connection again after each answer's `pollAfterMs`, never on a timer of its own, and calls `onCode` with each code it hasn't shown yet. It resolves with the connection once the user is signed in, and rejects with a `SandboxRouterSignInError` (its `signInStatus`, `expired`, `failed` or `none`, and `reason`) when the code expires or the sign-in fails, or when there's no sign-in to wait for. Pass a `signal` to stop waiting.

```ts
const { signIn } = await sandboxrouter.users.signIn("user_123", "codex"); // the code under way, a new one, or a sign-in again for a user who's signed in
const { connectUrl } = await sandboxrouter.users.link("user_123", { connector: "linear", returnUrl: "https://app.acme.com/settings" });
const connection = await sandboxrouter.users.connection("user_123", "linear");
await sandboxrouter.users.disconnect("user_123", "linear");
```

`sandboxrouter.users.logins` manages a user's [logins](/docs/logins), their sign-ins to websites, which their sandboxes' browsers sign in with; `sandboxrouter.connectors.account.logins` has the same methods for your workspace's logins, but `link`, its first argument the Logins connector's ID:

```ts
const login = await sandboxrouter.users.logins.create("user_123", { site: "github.com", username: "ana@acme.com", methods: ["passkey", "typed"], password });
const { connectUrl } = await sandboxrouter.users.logins.link("user_123", { site: "github.com" }, { returnUrl: "https://app.acme.com/settings" });
await sandboxrouter.users.logins.session.upload("user_123", login.id, await context.storageState());
const { signedIn } = await sandboxrouter.users.logins.check("user_123", login.id);
```

`list`, `get`, `update` and `delete` read and change logins; `passkeys.rename` and `passkeys.delete` a login's passkeys; `session.get`, `session.upload` and `session.delete` its saved sign-in, whose `StorageState` is Playwright's, so `context.storageState()` passes straight in (a Browserbase login takes no upload); and `live.open`, `live.done` and `live.cancel` a live view for a person to sign in by hand. A login never carries its password or code back. `create` sends an `Idempotency-Key`, its own unless you pass `idempotencyKey`, so a retry adds the login once.

## Lists

Lists of sandboxes, snapshots, MCP servers, logins and audit log entries come in pages. Await a list for one page, or iterate it for every item:

```ts
const page = await sandboxrouter.sandboxes.list({ limit: 20, labelSelector: { team: "web" } });

for await (const sandbox of sandboxrouter.sandboxes.list()) console.log(sandbox.metadata.name, sandbox.status?.phase);
```

## Errors and retries

Every failure is a `SandboxRouterError` with the HTTP `status`, the API's `code`, a `message` and the `requestId`, which you can quote when reporting a problem. Subclasses name the status, such as `NotFoundError`, `ConflictError` and `PaymentRequiredError`:

```ts
import { ConflictError } from "@sandboxrouterio/sdk";

try {
  await sandboxrouter.sandboxes.exec.run("build-agent", { command: ["npm", "test"] });
} catch (error) {
  if (error instanceof ConflictError && error.code === "not_running") console.log("start it first");
  else throw error;
}
```

The SDK retries a request that is safe to send again, twice by default, after a `429`, a `5xx` or no answer. Creating a sandbox, running an exec and creating an MCP server each send an `Idempotency-Key`, so a retry never creates anything twice.

## Switch from Daytona

Code written for Daytona's TypeScript SDK (`@daytonaio/sdk`) runs on Sandbox Router as it is. Change two settings and nothing else:

```sh
export DAYTONA_API_URL=https://api.sandboxrouter.io/daytona
export DAYTONA_API_KEY=<api-key>
```

Or pass the same two values in code:

```ts
import { Daytona } from "@daytonaio/sdk";

const daytona = new Daytona({ apiUrl: "https://api.sandboxrouter.io/daytona", apiKey: process.env.SANDBOXROUTER_API_KEY });
const sandbox = await daytona.create();
const { exitCode, result } = await sandbox.process.executeCommand("echo hi");
```

The key is an API key from your workspace, as above. Set `DAYTONA_API_URL` in the real environment (your shell, CI or platform settings), not in a `.env` file: the Daytona SDK reads it only from the environment, so a `.env` value sends your key to Daytona instead. Leave off a trailing slash.

What works: creating, listing, starting, stopping and deleting sandboxes, labels, the idle stop (`autoStopInterval`, 5 to 240 minutes), network settings, `executeCommand`, uploading, downloading and deleting files, and preview links. A sandbox's `snapshot`, or `image` given by name, is an image in your workspace's registry ([Images](/docs/images)). Pick a provider with the label `sandboxrouter.io/provider`, such as `{ labels: { "sandboxrouter.io/provider": "cloudflare" } }`. `executeCommand` runs in zsh or bash when the image has one, else `sh`, as Daytona runs it, and in `/workspace` unless you pass a `cwd`, which is also where a relative file path goes. Its `result` is the command's output followed by its errors. `daytona.get` finds a sandbox by its ID or its `name`; a sandbox just created can take a moment to be found by name. A `name` is a lowercase DNS label (1 to 63 letters, digits and hyphens, starting and ending with a letter or digit), one per sandbox: a name another sandbox has raises a `DaytonaConflictError`, and a sandbox created without one gets a generated name. Network settings change what a sandbox created with a limited network (`networkBlockAll` or an allow list) can reach, but can't turn a sandbox that reaches every destination into a limited one, or back: that raises a `DaytonaValidationError`, so create a new sandbox instead.

What answers an error instead: sessions, PTY, `codeRun`, git, LSP, computer use, listing or moving files, snapshots, volumes and archiving each raise a `DaytonaError` with status `501`. A setting Sandbox Router can't honour, such as `ttlMinutes`, a GPU or `autoStopInterval: 0`, raises a `DaytonaValidationError` that names it. So does `ephemeral: true`, or any `autoDeleteInterval` but `-1`: a sandbox stops when idle and stays until you delete it. `autoArchiveInterval` and `target` are accepted and have no effect. A create answers once the sandbox runs; if your images take longer than a minute to start, pass a larger timeout, such as `daytona.create(params, { timeout: 300 })`, or the SDK gives up before it learns the sandbox's ID. An upload takes at most 5,000 files at once.

## Switch from E2B

Code written for E2B's TypeScript SDK (`e2b`) runs on Sandbox Router as it is. Change two settings and nothing else:

```sh
export E2B_DOMAIN=e2b.sandboxrouter.io
export E2B_API_KEY=<api-key>
```

Or pass the same two values in code:

```ts
import { Sandbox } from "e2b";

const sandbox = await Sandbox.create({ domain: "e2b.sandboxrouter.io", apiKey: process.env.SANDBOXROUTER_API_KEY });
const { exitCode, stdout } = await sandbox.commands.run("echo hi");
```

The key is an API key from your workspace, as above.

What works: creating, connecting to, getting, listing and killing sandboxes, metadata, `commands.run` in the foreground or the background, and reading, writing, checking and removing files. A template other than `base` is an image in your workspace's registry ([Images](/docs/images)). Pick a provider with the metadata key `sandboxrouter.io/provider`, such as `{ metadata: { "sandboxrouter.io/provider": "cloudflare" } }`. `Sandbox.connect` starts a stopped sandbox again, as E2B resumes a paused one. A command's output arrives when it ends, so `onStdout` and `onStderr` are called then, not while it runs. A relative file path goes under `/workspace`. `getHost(port)` names a host that sends a program, with your key, on to the port's own address; a browser can't follow it. A sandbox has no time limit: `timeout` is accepted and has no effect, and a sandbox stops when idle.

What answers an error instead: PTY, stdin, running as another user, listing, making or moving directories, watching files, signed file URLs, pausing, snapshots, `setTimeout`, and the templates, volumes and secrets APIs each raise an error that says it is not supported. So does a create setting it can't honour, such as `network`, `volumeMounts` or `mcp`, which the error names. Killing a running command works on providers that can stop one; elsewhere it raises an error and the command runs on.

## Use it from a browser

The API doesn't answer browsers' cross-origin requests, so keep the API key on your server and call the API from there.
