---
title: Build and test Rust code with Vercel Sandbox
description: Set up Rust in a Vercel Sandbox with @vercel/sandbox, fetch crates before locking down egress, run offline tests, and reuse toolchains via snapshots or VCR.
url: "https://vercel.com/kb/guide/build-test-rust-vercel-sandbox"
published: 2026-12-04
last_updated: 2026-12-04
authors: Ben Sabic
related_resources:
  - title: "Build Vercel Functions with the Rust runtime"
    url: "/kb/guide/vercel-functions-on-rust"
    description: "Create Rust handlers in api/ with vercel_runtime 2.x, parse JSON requests, run background tasks, configure Fluid compute settings, and deploy to Vercel."
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 build-test-rust-vercel-sandbox"
---

Rust build scripts and procedural macros can execute code during compilation, before you run the resulting binary. When you test code generated by an agent or submitted by a user, [Vercel Sandbox](https://vercel.com/docs/sandbox) isolates that work in a Firecracker microVM with its own filesystem and outbound network policy.

Use the `@vercel/sandbox` TypeScript SDK to prepare the Rust toolchain, fetch dependencies, and run builds and tests with outbound traffic blocked. Snapshots and custom images let later builds reuse that environment. For hosted HTTP endpoints, [deploy Rust handlers as Vercel Functions](https://vercel.com/kb/guide/vercel-functions-on-rust).

## Prerequisites

Before you start, make sure you have a [Vercel account](https://vercel.com/signup). For local development, install Node.js 24 or later and the latest [Vercel CLI](https://vercel.com/docs/cli).

## Build with your agent

Use this prompt in your project repository to have a coding agent set up isolated Rust builds and tests with Vercel Sandbox:

### Agent prompt

```txt
Help me build and test Rust code in Vercel Sandbox from this repository using https://vercel.com/kb/guide/build-test-rust-vercel-sandbox. Read and follow the guide using the Vercel CLI: `npx vercel@latest kb inspect build-test-rust-vercel-sandbox`.

Inspect the repository's TypeScript setup, Rust crate files, and Vercel project link first. If the target crate, test command, or binary to execute isn't clear, ask which files and Cargo targets should run inside the sandbox.

1. Set up `@vercel/sandbox` and project authentication (`vercel link` and `vercel env pull` for local `VERCEL_OIDC_TOKEN`, or pass `teamId`, `projectId`, and `token` explicitly to `Sandbox.create()` from `VERCEL_TEAM_ID`, `VERCEL_PROJECT_ID`, and `VERCEL_TOKEN` in external CI because setting those environment variables alone does not authenticate the SDK). Keep SDK credentials in the host script and never copy them into the sandbox.

2. Create the sandbox with `persistent: false` for one-off runs and a `timeout` suited to Rust compilation. Use a prepared snapshot or custom VCR image if one exists; otherwise install `build-essential` via `apt-get` with `sudo: true` and install the stable Rust toolchain with `rustup` using `--profile minimal`. Enable Bash `pipefail` when piping the installer into a shell so a failed download fails setup.

3. Upload the crate files with `sandbox.writeFiles()`, run `cargo fetch` while outbound access is restricted to the required registry hosts, and then call `sandbox.update({ networkPolicy: 'deny-all' })` before running `cargo build --offline`, `cargo test --offline`, and any compiled binary.

4. Keep secrets out of command arguments and uploaded files. If sandbox code needs outbound authentication, configure firewall credentials brokering instead of passing tokens into the microVM. Set per-command `timeoutMs`, treat command output as untrusted, inspect `exitCode`, `stdout()`, and `stderr()`, and stop the sandbox in a `finally` block.

5. Verify both a passing test run and a failing test case so nonzero exit handling is confirmed. Separate any local checks you run on the host machine from commands executed inside the remote sandbox.

Return the changed files, required environment configuration, and test results. Distinguish local machine checks from remote Vercel Sandbox results, and report any checks you could not run.

To find other KB guides, such as ones on related topics or next steps, search the Vercel Knowledge Base with the Vercel CLI: `npx vercel@latest kb search "<topic>"`
```

## Understand what runs locally and what runs in the sandbox

Driving Vercel Sandbox from TypeScript involves two separate environments. Knowing where each command runs keeps local toolchains or host network access from masking sandbox failures.

| Environment                                 | Commands you run                                                                                                      | What it verifies                                                                                            |
| ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| Local machine (optional Rust check)         | `cargo test` in your local directory                                                                                  | Crate logic against your local Rust toolchain and host OS, with no sandbox isolation or network boundary.   |
| Local machine (driver script)               | `vercel link`, `vercel env pull`, `pnpm add`, `pnpm tsx run-rust.ts`                                                  | SDK authentication and orchestration logic running on your computer against the Vercel Sandbox API.         |
| Remote Vercel Sandbox (Firecracker microVM) | `apt-get`, `rustup`, `cargo fetch`, `cargo build --offline`, `cargo test --offline`, `./target/debug/pricing-sandbox` | Linux compilation, linking, offline test execution, and binary output inside an isolated microVM on Vercel. |

Passing `cargo test` locally verifies the crate against your own compiler and operating system. Successful tests from `run-rust.ts` verify it inside the remote Linux microVM with outbound traffic blocked.

## Set up the project and Rust crate

### 1\. Initialize the local TypeScript project and authenticate

Run these commands on your local machine to create a project folder, link it to a Vercel project, and pull a development [Vercel OIDC token](https://vercel.com/docs/sandbox/concepts/authentication):

```bash
mkdir rust-sandbox-demo && cd rust-sandbox-demo
npm init -y
vercel link
vercel env pull
```

When `vercel link` prompts you, create a new project or select an existing one. You do not need to deploy anything to the project; it exists so Vercel can issue `VERCEL_OIDC_TOKEN` into `.env.local`. That development token expires after 12 hours, so run `vercel env pull` again if authentication later fails.

Next, install the [Vercel Sandbox JavaScript SDK](https://vercel.com/docs/sandbox/sdk/javascript) and TypeScript runner dependencies on your local machine:

**pnpm**

```bash
pnpm i @vercel/sandbox dotenv @types/node tsx typescript
```

**npm**

```bash
npm i @vercel/sandbox dotenv @types/node tsx typescript
```

**yarn**

```bash
yarn add @vercel/sandbox dotenv @types/node tsx typescript
```

**bun**

```bash
bun add @vercel/sandbox dotenv @types/node tsx typescript
```

The `dotenv` package loads `VERCEL_OIDC_TOKEN` from `.env.local`, and `tsx` runs TypeScript files directly with Node.js.

### 2\. Create the Rust pricing crate

Create `Cargo.toml` at the project root using the TOML format to declare the crate and its `serde` dependencies:

```text
[package]
name = "pricing-sandbox"
version = "0.1.0"
edition = "2024"

[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
```

Cargo fetches `serde` and `serde_json` before outbound traffic is blocked, and the binary uses them to serialize its quote as JSON.

Create `src/` on your local machine, then add `src/pricing.rs`. The `calculate_quote` function calculates a proposed quote and flags discounts above 10% for approval, and the `#[cfg(test)]` module verifies its behavior:

```rust
use serde::Serialize;

#[derive(Debug, Serialize)]
pub struct Quote {
    pub total_cents: u64,
    pub approval_required: bool,
    pub rule_version: &'static str,
}

pub fn calculate_quote(
    subtotal_cents: u64,
    discount_percent: u8,
) -> Result<Quote, &'static str> {
    if discount_percent > 100 {
        return Err("Discount must be between 0 and 100");
    }

    // Round the discount down to a whole cent.
    let discount_cents =
        u128::from(subtotal_cents) * u128::from(discount_percent) / 100;

    Ok(Quote {
        total_cents: subtotal_cents - discount_cents as u64,
        approval_required: discount_percent > 10,
        rule_version: "pricing-v1",
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn discount_10_skips_approval() {
        let quote = calculate_quote(10_000, 10).unwrap();
        assert_eq!(quote.total_cents, 9_000);
        assert!(!quote.approval_required);
        assert_eq!(quote.rule_version, "pricing-v1");
    }

    #[test]
    fn discount_11_approval() {
        let quote = calculate_quote(10_000, 11).unwrap();
        assert_eq!(quote.total_cents, 8_900);
        assert!(quote.approval_required);
    }

    #[test]
    fn fractional_cent_rounds_down() {
        let quote = calculate_quote(101, 10).unwrap();
        assert_eq!(quote.total_cents, 91);
        assert!(!quote.approval_required);
    }

    #[test]
    fn rejects_discount_over_100() {
        let err = calculate_quote(10_000, 101).unwrap_err();
        assert_eq!(err, "Discount must be between 0 and 100");
    }
}
```

Amounts use integer cents, and fractional-cent discounts round down. For a $100 subtotal, a 10% discount returns $90 without requiring approval; 11% returns $89 with approval required. Discounts above 100% return an error string.

Create `src/main.rs` so the crate also produces a runnable binary that prints a serialized quote to standard output:

```rust
mod pricing;

use pricing::calculate_quote;

fn main() {
    match calculate_quote(10_000, 11) {
        Ok(quote) => {
            let json = serde_json::to_string_pretty(&quote)
                .expect("serialize quote");
            println!("{json}");
        }
        Err(err) => {
            eprintln!("pricing error: {err}");
            std::process::exit(1);
        }
    }
}
```

If you have the [Rust toolchain](https://rustup.rs) installed locally, run `cargo test` in this directory to check the crate on your own machine before sending it to a sandbox:

```bash
cargo test
```

Running `cargo test` locally uses your host compiler and does not exercise the remote Linux environment or firewall rules. Skip this command if you do not have Rust installed locally; the sandbox installs its own toolchain in the next step.

## Build and test the crate inside Vercel Sandbox

The [Vercel Managed Images](https://vercel.com/docs/sandbox/concepts/images#vercel-managed-images) do not include Rust or Cargo. The default `universal` image bundles Node.js, Python, and coding agents. This Rust workload uses `vcr.vercel.com/vercel/sandbox/ubuntu:latest`, based on Ubuntu 26.04 with `sudo`, to keep those extra toolchains out of the environment and any snapshots.

The script starts with `apt-get update` and installs `build-essential`, which provides Cargo's C linker. These commands run with `sudo: true` under the default `allow-all` network policy because Ubuntu package mirrors can use plain HTTP, which domain allowlists do not permit. See the [system package installation workflow](https://vercel.com/docs/sandbox/examples/install-system-packages) for details.

After package installation, the script allows the HTTPS hosts needed by `rustup` and crates.io. It installs the stable Rust toolchain with `--profile minimal`, uploads the crate, and fetches dependencies before switching the [firewall](https://vercel.com/docs/sandbox/concepts/firewall) to `deny-all`. Builds and tests then run offline with outbound connections and DNS blocked. This also restricts code executed during compilation by build scripts and procedural macros.

### 3\. Write the TypeScript driver script

Create `run-rust.ts` at the project root. This script runs locally on your machine and executes every build and test command inside a remote sandbox:

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

import { readFile } from 'node:fs/promises';
import { Sandbox } from '@vercel/sandbox';

const RUST_ALLOWLIST = [
  'sh.rustup.rs',
  'static.rust-lang.org',
  'crates.io',
  'index.crates.io',
  'static.crates.io',
];

async function runChecked(
  label: string,
  sandbox: Sandbox,
  params: {
    cmd: string;
    args?: string[];
    env?: Record<string, string>;
    sudo?: boolean;
    timeoutMs?: number;
  },
) {
  const result = await sandbox.runCommand(params);
  if (result.exitCode !== 0) {
    const stderr = await result.stderr();
    throw new Error(`${label} failed (${result.exitCode}):\n${stderr}`);
  }
  return result;
}

async function runCargo(sandbox: Sandbox, command: string, timeoutMs: number) {
  return sandbox.runCommand({
    cmd: 'bash',
    args: ['-c', `export PATH="$HOME/.cargo/bin:$PATH" && ${command}`],
    timeoutMs,
  });
}

async function main() {
  const [cargoToml, pricingRs, mainRs] = await Promise.all([
    readFile('Cargo.toml'),
    readFile('src/pricing.rs'),
    readFile('src/main.rs'),
  ]);

  const sandbox = await Sandbox.create({
    image: 'vcr.vercel.com/vercel/sandbox/ubuntu:latest',
    persistent: false,
    timeout: 10 * 60 * 1000,
    resources: { vcpus: 2 },
  });

  try {
    await runChecked('apt-get update', sandbox, {
      cmd: 'apt-get',
      args: ['update'],
      sudo: true,
      timeoutMs: 120_000,
    });

    await runChecked('install C toolchain', sandbox, {
      cmd: 'apt-get',
      args: ['install', '-y', 'build-essential', 'curl', 'ca-certificates'],
      env: { DEBIAN_FRONTEND: 'noninteractive' },
      sudo: true,
      timeoutMs: 180_000,
    });

    await sandbox.update({
      networkPolicy: { allow: RUST_ALLOWLIST },
    });

    const installRust =
      'curl --proto "=https" --tlsv1.2 -sSf https://sh.rustup.rs ' +
      '| sh -s -- -y --profile minimal --default-toolchain stable';

    await runChecked('install rustup', sandbox, {
      cmd: 'bash',
      args: ['-o', 'pipefail', '-c', installRust],
      timeoutMs: 180_000,
    });

    await sandbox.mkDir('src');
    await sandbox.writeFiles([
      { path: 'Cargo.toml', content: cargoToml },
      { path: 'src/pricing.rs', content: pricingRs },
      { path: 'src/main.rs', content: mainRs },
    ]);

    const fetchResult = await runCargo(sandbox, 'cargo fetch', 120_000);
    if (fetchResult.exitCode !== 0) {
      throw new Error(`cargo fetch failed:\n${await fetchResult.stderr()}`);
    }

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

    const buildResult = await runCargo(
      sandbox,
      'cargo build --offline',
      180_000,
    );
    if (buildResult.exitCode !== 0) {
      throw new Error(`cargo build failed:\n${await buildResult.stderr()}`);
    }

    const testResult = await runCargo(sandbox, 'cargo test --offline', 120_000);
    console.log(`cargo test exitCode: ${testResult.exitCode}`);
    console.log(await testResult.stdout());

    if (testResult.exitCode !== 0) {
      console.error(await testResult.stderr());
      process.exitCode = testResult.exitCode;
      return;
    }

    const binResult = await runChecked('run binary', sandbox, {
      cmd: './target/debug/pricing-sandbox',
      timeoutMs: 30_000,
    });
    console.log('Binary output:');
    console.log(await binResult.stdout());
  } finally {
    await sandbox.stop();
  }
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
```

#### Timeouts and cleanup

With `persistent: false`, [`sandbox.stop()`](https://vercel.com/docs/sandbox/examples/stop-a-sandbox) discards the filesystem and ends compute usage when `finally` runs. [Persistence is enabled by default](https://vercel.com/docs/sandbox/concepts/persistent-sandboxes), so omitting this setting saves the filesystem on stop and incurs [Snapshot Storage](https://vercel.com/docs/sandbox/pricing#snapshot-storage) charges.

The 10-minute session timeout exceeds the 5-minute default and stays within the [session limits](https://vercel.com/docs/sandbox/pricing#runtime-limits): 45 minutes on Hobby and 24 hours on Pro and Enterprise. Per-command `timeoutMs` limits each setup or build step and sends `SIGKILL` on expiry.

#### User and file paths

Only package installation uses `sudo: true`, running as `root` with `HOME=/root`. Rustup and Cargo run as `ubuntu` with `/vercel` as both home and working directory.

Rustup installs executables in `/vercel/.cargo/bin`, which the `runCargo` helper adds to `PATH`. Before uploading the crate, `sandbox.mkDir('src')` creates `/vercel/src`, following the [file upload workflow](https://vercel.com/docs/sandbox/examples/prepare-files-and-download-artifacts).

### 4\. Run the script and inspect a passing and failing test

Run the TypeScript driver script from your local machine:

**pnpm**

```bash
pnpm tsx run-rust.ts
```

**npm**

```bash
npx tsx run-rust.ts
```

**yarn**

```bash
yarn tsx run-rust.ts
```

**bun**

```bash
bunx tsx run-rust.ts
```

When every unit test passes inside the remote sandbox, `testResult.exitCode` is `0`, `testResult.stdout()` reports four passing tests, and `binResult.stdout()` prints the serialized quote, producing illustrative output like the following:

```text
cargo test exitCode: 0
running 4 tests
test pricing::tests::discount_10_skips_approval ... ok
test pricing::tests::discount_11_approval ... ok
test pricing::tests::fractional_cent_rounds_down ... ok
test pricing::tests::rejects_discount_over_100 ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Binary output:
{
  "total_cents": 8900,
  "approval_required": true,
  "rule_version": "pricing-v1"
}
```

In `src/pricing.rs`, negate the approval assertion in `discount_11_approval` by adding `!` before `quote.approval_required`. Rerun the driver to see the failing test details on standard output and Cargo's error summary on standard error. The test command exits with a nonzero status:

```text
cargo test exitCode: 101
running 4 tests
test pricing::tests::discount_10_skips_approval ... ok
test pricing::tests::discount_11_approval ... FAILED
test pricing::tests::fractional_cent_rounds_down ... ok
test pricing::tests::rejects_discount_over_100 ... ok

failures:

---- pricing::tests::discount_11_approval stdout ----
thread 'pricing::tests::discount_11_approval' panicked at src/pricing.rs:45:9:
assertion failed: !quote.approval_required

test result: FAILED. 3 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out
```

Because `run-rust.ts` checks `testResult.exitCode !== 0`, it skips executing the binary, sets `process.exitCode` to Cargo's nonzero exit code, and still runs `sandbox.stop()` in `finally`. Revert `src/pricing.rs` back to `assert!(quote.approval_required);` when you finish testing.

## Reuse the prepared environment

Installing `build-essential` and `rustup` on every run adds setup latency and requires `allow-all` network access for `apt-get` on each fresh microVM. You can prepare the Rust toolchain once and reuse it through either a [snapshot](https://vercel.com/docs/sandbox/concepts/snapshots) or a [custom image](https://vercel.com/docs/sandbox/concepts/images#custom-images) stored in [Vercel Container Registry (VCR)](https://vercel.com/docs/container-registry).

### Save and restore a snapshot

Create a one-time setup script, `create-snapshot.ts`, to install the C toolchain and Rust once and capture the filesystem with `sandbox.snapshot()`:

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

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

const FOURTEEN_DAYS_MS = 14 * 24 * 60 * 60 * 1000;

async function main() {
  const sandbox = await Sandbox.create({
    image: 'vcr.vercel.com/vercel/sandbox/ubuntu:latest',
    persistent: false,
    timeout: 10 * 60 * 1000,
  });

  try {
    const update = await sandbox.runCommand({
      cmd: 'apt-get',
      args: ['update'],
      sudo: true,
      timeoutMs: 120_000,
    });
    if (update.exitCode !== 0) throw new Error(await update.stderr());

    const pkgs = await sandbox.runCommand({
      cmd: 'apt-get',
      args: ['install', '-y', 'build-essential', 'curl', 'ca-certificates'],
      env: { DEBIAN_FRONTEND: 'noninteractive' },
      sudo: true,
      timeoutMs: 180_000,
    });
    if (pkgs.exitCode !== 0) throw new Error(await pkgs.stderr());

    const installRust =
      'curl --proto "=https" --tlsv1.2 -sSf https://sh.rustup.rs ' +
      '| sh -s -- -y --profile minimal --default-toolchain stable';

    const rust = await sandbox.runCommand({
      cmd: 'bash',
      args: ['-o', 'pipefail', '-c', installRust],
      timeoutMs: 180_000,
    });
    if (rust.exitCode !== 0) throw new Error(await rust.stderr());

    const snapshot = await sandbox.snapshot({ expiration: FOURTEEN_DAYS_MS });
    console.log(`Snapshot ID: ${snapshot.snapshotId}`);
  } catch (err) {
    await sandbox.stop();
    throw err;
  }
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
```

Run `create-snapshot.ts` on your local machine and record the printed snapshot ID:

**pnpm**

```bash
pnpm tsx create-snapshot.ts
```

**npm**

```bash
npx tsx create-snapshot.ts
```

**yarn**

```bash
yarn tsx create-snapshot.ts
```

**bun**

```bash
bunx tsx create-snapshot.ts
```

Calling `sandbox.snapshot()` captures the filesystem and stops the session. The setup sandbox uses `persistent: false` so `sandbox.stop()` in `catch` discards an incomplete environment if installation fails.

The manual snapshot expires 14 days after its last use, compared with the default of 30 days after last use. Valid custom values are `0` for no expiration or between 1 day and 10 years. See the [snapshot and restore pattern](https://vercel.com/docs/sandbox/examples/snapshot-and-restore) for the lifecycle.

To start a one-off build sandbox from that snapshot with network access already restricted to crates.io, create `run-from-snapshot.ts` and replace `your-snapshot-id` with the ID printed above:

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

import { readFile } from 'node:fs/promises';
import { Sandbox } from '@vercel/sandbox';

const SNAPSHOT_ID = process.env.RUST_SNAPSHOT_ID ?? 'your-snapshot-id';
const CRATES_ALLOWLIST = ['crates.io', 'index.crates.io', 'static.crates.io'];

async function runCargo(sandbox: Sandbox, command: string, timeoutMs: number) {
  return sandbox.runCommand({
    cmd: 'bash',
    args: ['-c', `export PATH="$HOME/.cargo/bin:$PATH" && ${command}`],
    timeoutMs,
  });
}

async function main() {
  const [cargoToml, pricingRs, mainRs] = await Promise.all([
    readFile('Cargo.toml'),
    readFile('src/pricing.rs'),
    readFile('src/main.rs'),
  ]);

  const sandbox = await Sandbox.create({
    source: { type: 'snapshot', snapshotId: SNAPSHOT_ID },
    persistent: false,
    timeout: 5 * 60 * 1000,
    networkPolicy: { allow: CRATES_ALLOWLIST },
  });

  try {
    await sandbox.mkDir('src');
    await sandbox.writeFiles([
      { path: 'Cargo.toml', content: cargoToml },
      { path: 'src/pricing.rs', content: pricingRs },
      { path: 'src/main.rs', content: mainRs },
    ]);

    const fetchRes = await runCargo(sandbox, 'cargo fetch', 120_000);
    if (fetchRes.exitCode !== 0) {
      throw new Error(`cargo fetch failed:\n${await fetchRes.stderr()}`);
    }

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

    const testRes = await runCargo(sandbox, 'cargo test --offline', 120_000);
    console.log(`cargo test exitCode: ${testRes.exitCode}`);
    console.log(await testRes.stdout());
    if (testRes.exitCode !== 0) {
      console.error(await testRes.stderr());
      process.exitCode = testRes.exitCode;
    }
  } finally {
    await sandbox.stop();
  }
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
```

Run the restored-environment script from the project directory:

**pnpm**

```bash
pnpm tsx run-from-snapshot.ts
```

**npm**

```bash
npx tsx run-from-snapshot.ts
```

**yarn**

```bash
yarn tsx run-from-snapshot.ts
```

**bun**

```bash
bunx tsx run-from-snapshot.ts
```

The script runs the four unit tests and stops the temporary sandbox before exiting with Cargo's status. It does not execute the pricing binary.

Snapshots are tied to their source region. Starting a sandbox from a snapshot in another region fails with `snapshot_region_mismatch` unless failover loads it.

Follow the [security responsibilities for snapshots](https://vercel.com/docs/sandbox/concepts/images#security-responsibilities-for-images-and-snapshots) by recreating them regularly for operating system patches and Rust updates. Nightly Vercel Managed Image releases update rolling image tags without changing existing snapshots.

### Build a custom image in VCR

Custom images keep your toolchain definition in source control for digest pinning and sharing across projects and teams. Install Docker, Podman, or Buildah locally, then create a `Dockerfile` based on the Ubuntu managed image:

```docker
FROM vcr.vercel.com/vercel/sandbox/ubuntu:latest

USER root
RUN apt-get update \
  && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
    build-essential \
    curl \
    ca-certificates \
  && rm -rf /var/lib/apt/lists/*

USER ubuntu
WORKDIR /vercel

SHELL ["/bin/bash", "-o", "pipefail", "-c"]

RUN curl --proto "=https" --tlsv1.2 -sSf https://sh.rustup.rs \
  | sh -s -- -y --profile minimal --default-toolchain stable

ENV PATH="/vercel/.cargo/bin:${PATH}"
```

Setting `WORKDIR /vercel` makes `sandbox.runCommand()` and relative `sandbox.writeFiles()` paths start in `/vercel`. Without `WORKDIR`, custom images start in `/`. Vercel Sandbox does not execute Docker `ENTRYPOINT` or `CMD`, so omit them and start commands explicitly with `sandbox.runCommand()`.

[Authenticate your container tool with VCR](https://vercel.com/docs/container-registry/getting-started), then build and push locally. These commands use Docker; substitute `podman` or `buildah` as needed:

```bash
vercel vcr login docker
vercel vcr build docker . rust-sandbox:latest --push
```

`vercel vcr build` builds for `linux/amd64` by default. For `arm64` sandboxes, which are in beta and run only in `iad1`, pass `--platform linux/arm64` and set `architecture: 'arm64'` with `region: 'iad1'` when creating the sandbox.

After pushing, wait for the repository details page in the Vercel dashboard to report `Ready`. Until VCR finishes preparing the optimized image, `Sandbox.create()` returns `image_not_ready`.

Once the image is `Ready`, create `run-from-image.ts` to boot a sandbox directly from `rust-sandbox:latest`, or pin a digest such as `rust-sandbox@sha256:your-digest`:

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

import { readFile } from 'node:fs/promises';
import { Sandbox } from '@vercel/sandbox';

const CRATES_ALLOWLIST = ['crates.io', 'index.crates.io', 'static.crates.io'];

async function main() {
  const [cargoToml, pricingRs, mainRs] = await Promise.all([
    readFile('Cargo.toml'),
    readFile('src/pricing.rs'),
    readFile('src/main.rs'),
  ]);

  const sandbox = await Sandbox.create({
    image: 'rust-sandbox:latest',
    persistent: false,
    timeout: 5 * 60 * 1000,
    networkPolicy: { allow: CRATES_ALLOWLIST },
  });

  try {
    await sandbox.mkDir('src');
    await sandbox.writeFiles([
      { path: 'Cargo.toml', content: cargoToml },
      { path: 'src/pricing.rs', content: pricingRs },
      { path: 'src/main.rs', content: mainRs },
    ]);

    const fetchRes = await sandbox.runCommand({
      cmd: 'cargo',
      args: ['fetch'],
      timeoutMs: 120_000,
    });
    if (fetchRes.exitCode !== 0) {
      throw new Error(`cargo fetch failed:\n${await fetchRes.stderr()}`);
    }

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

    const testRes = await sandbox.runCommand({
      cmd: 'cargo',
      args: ['test', '--offline'],
      timeoutMs: 120_000,
    });
    console.log(`cargo test exitCode: ${testRes.exitCode}`);
    console.log(await testRes.stdout());
    if (testRes.exitCode !== 0) {
      console.error(await testRes.stderr());
      process.exitCode = testRes.exitCode;
    }
  } finally {
    await sandbox.stop();
  }
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
```

Run the image-based script from the linked project directory:

**pnpm**

```bash
pnpm tsx run-from-image.ts
```

**npm**

```bash
npx tsx run-from-image.ts
```

**yarn**

```bash
yarn tsx run-from-image.ts
```

**bun**

```bash
bunx tsx run-from-image.ts
```

It tests the crate using your image and stops the temporary sandbox afterward. The Dockerfile adds `/vercel/.cargo/bin` to `PATH`, so this script calls `cargo` directly.

Custom images retain the software they were built with. Rebuild and push the image periodically to pick up base-image patches and Rust toolchain updates.

### Choose between snapshots and custom images

Snapshots and custom images reuse the installed toolchain. Start with a crates.io allowlist to fetch dependencies, or block outbound traffic immediately if the environment already contains every dependency the build needs.

| Criterion           | Snapshot                                                                                 | Custom VCR image                                                                        |
| ------------------- | ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| Setup workflow      | Created programmatically from a running sandbox with `sandbox.snapshot()`.               | Built from a `Dockerfile` and pushed with `vercel vcr build`.                           |
| Sharing and regions | Scoped to the project and region where it was captured.                                  | Can be shared across projects and teams, and pinned by immutable `@sha256:...` digest.  |
| Warm crate caches   | Includes pre-fetched crates or compiled `target/` artifacts when captured after a build. | Possible in the Dockerfile, though better suited to toolchains and stable dependencies. |
| Maintenance         | Expires 30 days after last use by default; recreate to update OS and Rust.               | Rebuild and push in CI to update OS patches and Rust versions.                          |

Use a snapshot when you want fast setup inside one project and region, or when you want to cache a specific workspace's crate downloads. Use a custom VCR image when your toolchain definition belongs in source control, needs digest pinning for CI, or must be shared across multiple projects.

## Guardrails for agent-generated Rust code

Each Firecracker microVM has its own kernel, filesystem, and network namespace. Apply the [Sandbox security model](https://vercel.com/docs/sandbox/concepts/security) to untrusted code by limiting outbound traffic and execution time while keeping credentials outside the microVM.

### Restrict network access before compiling

Cargo executes arbitrary code during `cargo build` and `cargo test` through `build.rs` build scripts and procedural macros. Do not leave the default `allow-all` policy active while compiling or running untrusted crates.

Start from a snapshot or custom image with a narrow HTTPS allowlist (`crates.io`, `index.crates.io`, `static.crates.io`), run `cargo fetch`, and switch to `networkPolicy: 'deny-all'` before compiling. If your crates are already vendored or cached in a snapshot, pass `networkPolicy: 'deny-all'` directly in `Sandbox.create()` so the session never has outbound access.

The `deny-all` policy blocks outbound connections and DNS, so wait for the firewall update to succeed before running untrusted code. Live and saved changes apply separately in `sandbox.update()`, and a rejected call can leave some changes in effect. Retrieve fresh metadata and inspect the active session before retrying.

### Keep credentials out of the sandbox

Keep `VERCEL_OIDC_TOKEN`, `VERCEL_TOKEN`, `VERCEL_TEAM_ID`, and `VERCEL_PROJECT_ID` in your host script or server environment. Never write SDK tokens into uploaded files or pass secrets in command arguments, which [Sandbox can store and expose through its API](https://vercel.com/docs/sandbox/examples/run-commands-in-sandbox).

For external HTTPS APIs or private Cargo registries, use [credentials brokering](https://vercel.com/docs/sandbox/concepts/firewall#credentials-brokering). Firewall `transform` rules inject the `Authorization` header while keeping the secret outside the microVM. [Sandbox Credentials](https://vercel.com/docs/sandbox/concepts/credentials) is in Beta and supports npm through `credentials: { npm: true }`, but does not manage Cargo credentials.

For transformation, forwarding, or direct-response rules, Sandbox terminates TLS and adds a per-sandbox [proxy CA certificate](https://vercel.com/docs/sandbox/concepts/security#proxy-ca-certificates) to the system trust store. It points `CARGO_HTTP_CAINFO`, `CURL_CA_BUNDLE`, and `SSL_CERT_FILE` to `/etc/ssl/certs/ca-certificates.crt` so Cargo trusts the proxy automatically.

### Bound compute time, resources, and long builds

Set both a session `timeout` in `Sandbox.create()` and a per-command `timeoutMs` in `sandbox.runCommand()` so infinite loops or runaway macro expansions terminate promptly. On expiry, `timeoutMs` kills the process with `SIGKILL`.

Each sandbox starts with 2 vCPUs by default (2 GB of memory per vCPU) and 64 GB of ephemeral NVMe disk. You can raise `resources: { vcpus }` up to your plan's [resource limits](https://vercel.com/docs/sandbox/pricing#resource-limits): 4 vCPUs (8 GB RAM) on Hobby, 8 vCPUs (16 GB RAM) on Pro, and 32 vCPUs (64 GB RAM) on Enterprise.

Vercel Sandbox closes idle connections after 340 seconds, even when the command keeps running. Setting `detached: true` returns a command handle immediately, but `command.logs()` and `command.wait()` can still time out.

For quiet builds, have the command emit a progress line every few minutes to keep its log connection active. Cargo's `--verbose` flag adds detail without guaranteeing regular output. See the [long-running task guidance](https://vercel.com/docs/sandbox/examples/execute-long-running-tasks#idle-connection-timeout) for the affected calls.

### Clean up sandboxes and snapshots

Set `persistent: false` for one-off builds and call `sandbox.stop()` in `finally` to end the session without saving an automatic snapshot. Persistent sandboxes instead retain a snapshot when stopped, which incurs Snapshot Storage charges.

To retire a persistent workspace, [delete the sandbox](https://vercel.com/docs/sandbox/examples/delete-a-sandbox) with `sandbox.delete()`. Snapshots are preserved by default for other sandboxes to use. Set `deleteOrphanSnapshots` to remove snapshots with no remaining references.

> **Warning:**
>
> Calling `sandbox.delete()` permanently deletes the sandbox and all of its sessions and cannot be undone. Confirm you no longer need the workspace before deleting it.

### Treat sandbox output as untrusted

Check `result.exitCode` before acting on command output. Bound or truncate `stdout()` and `stderr()` before passing them to an LLM prompt, database, or web UI, and treat all printed text and downloaded artifacts as untrusted input that may contain prompt injections, control characters, or malformed JSON.

## Troubleshooting

### Linker `cc` not found during `cargo build` or `cargo test`

Cargo needs a C linker for Rust binaries and crates with native dependencies. Ubuntu managed images do not preinstall one, so check with `which cc` inside the sandbox. If none is present, run `apt-get update` and `apt-get install -y build-essential` with `sudo: true`, or install the package in your snapshot or Dockerfile. Verify recovery with `cc --version`.

### Compilation fails on edition 2024 or `let` chains

Check your compiler inside the sandbox with `rustc --version` and update the stable toolchain with `rustup update stable`. If you installed Rust through Ubuntu's `apt-get` repository instead of `rustup`, the packaged `rustc` can be older than edition 2024 requires. If the project pins a toolchain in `rust-toolchain.toml`, update that pin too, and recreate your snapshot or custom image after updating.

### `cargo fetch` fails when a network policy is active

Check that `cargo fetch` runs before the switch to `deny-all`. The allowlist must include `crates.io`, `index.crates.io`, `static.crates.io`, and any Git hosts referenced in `Cargo.toml`.

Domain allowlists match TLS traffic by SNI. Wildcards such as `*.crates.io` exclude the apex domain, so add `crates.io` separately. Allow every HTTPS hostname needed to fetch the crates, then block outbound traffic before compiling.

### `Sandbox.create()` returns `image_not_ready`

After a push, VCR prepares an optimized image for Sandbox. Wait for the repository details page in your project dashboard to show `Ready`, then retry `Sandbox.create()`.

For `Ready (unoptimized)` or `Error`, check VCR optimization limits and the image’s target architecture. Use `linux/amd64`, or `linux/arm64` for ARM sandboxes in `iad1`.

### Authentication errors after local setup worked earlier

The development OIDC token in `.env.local` expires after 12 hours. Refresh it with `vercel env pull` from the linked project directory, then rerun your TypeScript script.

For external CI, use [access-token authentication](https://vercel.com/docs/sandbox/concepts/authentication#access-tokens) and pass `teamId`, `projectId`, and `token` to `Sandbox.create()`. The SDK does not infer these options from environment variables, so your script must read and pass their values.

## Next steps

- [Deploy Rust HTTP handlers](https://vercel.com/kb/guide/vercel-functions-on-rust) with the native Vercel Functions runtime.
  
- Configure commands and file operations with the [JavaScript SDK reference](https://vercel.com/docs/sandbox/sdk/javascript).
  
- [Control outbound traffic](https://vercel.com/docs/sandbox/concepts/firewall) with allowlists and credential brokering.
  
- Build [custom Sandbox images](https://vercel.com/docs/sandbox/concepts/images) and publish them to [Vercel Container Registry](https://vercel.com/docs/container-registry).
  
- Set [snapshot retention](https://vercel.com/docs/sandbox/concepts/snapshots) and manage [persistent workspaces](https://vercel.com/docs/sandbox/concepts/persistent-sandboxes).
  
- Check [resource limits and billing](https://vercel.com/docs/sandbox/pricing) before running larger builds.

## Related Resources

- [Build Vercel Functions with the Rust runtime](/kb/guide/vercel-functions-on-rust): Create Rust handlers in api/ with vercel\_runtime 2.x, parse JSON requests, run background tasks, configure Fluid compute settings, and deploy to Vercel.

## 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.
- [Migrate from Railway Sandboxes to Vercel Sandbox](/kb/guide/migrate-from-railway-sandboxes-to-vercel-sandbox): Migrate Railway Sandboxes to Vercel Sandbox, adapting templates, checkpoints, timeouts, and networking with a staged cutover.

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