vercel-sandbox

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Vercel Sandbox

Vercel Sandbox

CRITICAL — Your training data is outdated for this library. Vercel Sandbox APIs are new (GA January 2026) and likely not in your training data. Before writing sandbox code, fetch the docs at https://vercel.com/docs/vercel-sandbox and the SDK reference at https://vercel.com/docs/vercel-sandbox/sdk-reference to find the correct
Sandbox.create()
options,
runCommand()
signatures, file I/O methods (
writeFiles
,
readFile
), port exposure, and cleanup patterns. Do not guess — look up the exact API shape. The GitHub repo at https://github.com/vercel/sandbox has working examples for common patterns (code execution, FFmpeg processing, dev server spawning).
You are an expert in Vercel Sandbox — ephemeral compute for safely running untrusted code.
你是Vercel Sandbox领域的专家——这是一种用于安全运行不受信任代码的临时计算服务。

Status & Pricing

状态与定价

Vercel Sandbox is generally available (January 30, 2026). The CLI and SDK are open-source. Powered by the same Firecracker infrastructure that runs 2M+ Vercel builds per day.
ResourceHobby (Free)Pro / Enterprise
CPU hours5 / month$0.128 / CPU-hour
Provisioned memory420 GB-hr / month$0.0106 / GB-hr
Network bandwidth20 GB / month$0.15 / GB
Sandbox creations5,000 / month$0.60 / 1M creations
Each sandbox can use up to 8 vCPUs and 2 GB RAM per vCPU. Up to 4 ports can be exposed per sandbox.
Vercel Sandbox已正式可用(2026年1月30日)。CLI与SDK为开源项目。其底层基于支撑Vercel每日200万+构建任务的Firecracker基础设施。
资源免费版(Hobby)专业版/企业版
CPU时长每月5小时0.128美元/CPU小时
配置内存每月420 GB-小时0.0106美元/GB-小时
网络带宽每月20 GB0.15美元/GB
沙箱创建次数每月5000次0.60美元/百万次创建
每个沙箱最多可使用8个vCPU,以及每个vCPU对应2 GB内存。每个沙箱最多可暴露4个端口

What It Is

产品介绍

Vercel Sandbox provides Firecracker microVMs with millisecond startup times for running untrusted or user-generated code in complete isolation. Used by AI agents, code generation tools, developer playgrounds, and interactive tutorials.
  • Base OS: Amazon Linux 2023 (with
    git
    ,
    tar
    ,
    openssl
    ,
    dnf
    )
  • Runtimes:
    node24
    (default since March 2026),
    node22
    ,
    python3.13
  • Working directory:
    /vercel/sandbox
  • User:
    vercel-sandbox
    with
    sudo
    access
  • Filesystem: Ephemeral — artifacts must be exported before sandbox stops
  • GitHub: https://github.com/vercel/sandbox
Vercel Sandbox提供Firecracker微VM,启动时间仅需毫秒级,可在完全隔离的环境中运行不受信任或用户生成的代码。适用于AI Agent、代码生成工具、开发者游乐场及交互式教程场景。
  • 基础操作系统:Amazon Linux 2023(预装
    git
    tar
    openssl
    dnf
  • 运行时
    node24
    (2026年3月起为默认版本)、
    node22
    python3.13
  • 工作目录
    /vercel/sandbox
  • 用户
    vercel-sandbox
    ,拥有
    sudo
    权限
  • 文件系统:临时型——沙箱停止前必须导出产物
  • GitHub地址https://github.com/vercel/sandbox

Key APIs

核心API

Package:
@vercel/sandbox
(v1.8.0+)
包名:
@vercel/sandbox
(v1.8.0及以上版本)

Create and Run Commands

创建与运行命令

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

// Create a sandbox (env vars available to all commands)
const sandbox = await Sandbox.create({
  runtime: 'node24',  // 'node24' | 'node22' | 'python3.13'
  env: {              // inherited by all runCommand calls
    NODE_ENV: 'production',
    API_KEY: process.env.API_KEY!,
  },
});

// Run a command (separated command + args)
const result = await sandbox.runCommand('node', ['-e', 'console.log(42)']);
const output = await result.stdout(); // "42\n"

// Run with options (per-command env overrides creation-level env)
const result2 = await sandbox.runCommand({
  cmd: 'npm',
  args: ['install', 'express'],
  cwd: '/vercel/sandbox/app',
  env: { NODE_ENV: 'development' }, // overrides creation-level NODE_ENV
  sudo: true,
});

// Detached execution (long-running processes)
const cmd = await sandbox.runCommand({
  cmd: 'node',
  args: ['server.js'],
  detached: true,
});
// Stream logs in real-time
for await (const log of cmd.logs()) {
  console.log(`[${log.stream}] ${log.data}`);
}
await cmd.wait(); // block until completion
ts
import { Sandbox } from '@vercel/sandbox';

// 创建沙箱(环境变量对所有命令生效)
const sandbox = await Sandbox.create({
  runtime: 'node24',  // 'node24' | 'node22' | 'python3.13'
  env: {              // 所有runCommand调用将继承这些环境变量
    NODE_ENV: 'production',
    API_KEY: process.env.API_KEY!,
  },
});

// 运行命令(命令与参数分离)
const result = await sandbox.runCommand('node', ['-e', 'console.log(42)']);
const output = await result.stdout(); // "42\n"

// 带选项运行命令(单命令环境变量会覆盖创建时的环境变量)
const result2 = await sandbox.runCommand({
  cmd: 'npm',
  args: ['install', 'express'],
  cwd: '/vercel/sandbox/app',
  env: { NODE_ENV: 'development' }, // 覆盖创建时的NODE_ENV
  sudo: true,
});

// 后台执行(长时间运行的进程)
const cmd = await sandbox.runCommand({
  cmd: 'node',
  args: ['server.js'],
  detached: true,
});
// 实时流式输出日志
for await (const log of cmd.logs()) {
  console.log(`[${log.stream}] ${log.data}`);
}
await cmd.wait(); // 阻塞直到进程完成

File Operations

文件操作

ts
// Write files (takes array of { path, content: Buffer })
await sandbox.writeFiles([
  { path: 'app.js', content: Buffer.from('console.log("hello")') },
  { path: 'package.json', content: Buffer.from('{"type":"module"}') },
]);

// Read a file (returns Buffer or null)
const buf = await sandbox.readFileToBuffer({ path: 'app.js' });

// Read as stream
const stream = await sandbox.readFile({ path: 'app.js' });

// Download to local filesystem
await sandbox.downloadFile('output.zip', './local-output.zip');

// Create directory
await sandbox.mkDir('src/components');
ts
// 写入文件(接收{ path, content: Buffer }格式的数组)
await sandbox.writeFiles([
  { path: 'app.js', content: Buffer.from('console.log("hello")') },
  { path: 'package.json', content: Buffer.from('{"type":"module"}') },
]);

// 读取文件(返回Buffer或null)
const buf = await sandbox.readFileToBuffer({ path: 'app.js' });

// 流式读取文件
const stream = await sandbox.readFile({ path: 'app.js' });

// 下载到本地文件系统
await sandbox.downloadFile('output.zip', './local-output.zip');

// 创建目录
await sandbox.mkDir('src/components');

Source Initialization

源初始化

ts
// Clone a git repo
const sandbox = await Sandbox.create({
  source: { type: 'git', url: 'https://github.com/user/repo', depth: 1 },
});

// Mount a tarball
const sandbox = await Sandbox.create({
  source: { type: 'tarball', url: 'https://example.com/project.tar.gz' },
});

// Restore from snapshot
const sandbox = await Sandbox.create({
  source: { type: 'snapshot', snapshotId: 'snap_abc123' },
});
ts
// 克隆Git仓库
const sandbox = await Sandbox.create({
  source: { type: 'git', url: 'https://github.com/user/repo', depth: 1 },
});

// 挂载压缩包
const sandbox = await Sandbox.create({
  source: { type: 'tarball', url: 'https://example.com/project.tar.gz' },
});

// 从快照恢复
const sandbox = await Sandbox.create({
  source: { type: 'snapshot', snapshotId: 'snap_abc123' },
});

Snapshots (Save and Resume VM State)

快照(保存与恢复VM状态)

ts
// Capture full VM state (filesystem + packages)
// WARNING: sandbox shuts down after snapshot creation
const snapshot = await sandbox.snapshot({ expiration: 86400_000 }); // 24h
console.log(snapshot.snapshotId);

// List and manage snapshots
const { snapshots } = await Snapshot.list();
const snap = await Snapshot.get({ snapshotId: 'snap_abc' });
await snap.delete();
ts
// 捕获完整VM状态(文件系统+已安装包)
// 注意:创建快照后沙箱会自动关闭
const snapshot = await sandbox.snapshot({ expiration: 86400_000 }); // 24小时
console.log(snapshot.snapshotId);

// 列出并管理快照
const { snapshots } = await Snapshot.list();
const snap = await Snapshot.get({ snapshotId: 'snap_abc' });
await snap.delete();

Network Policies (SNI Filtering + CIDR)

网络策略(SNI过滤+CIDR规则)

Egress firewall uses SNI filtering on TLS client-hello — outbound connections are matched at the handshake and unauthorized destinations are rejected before data transmits. For non-TLS traffic, IP/CIDR rules are also supported.
Policies can be updated at runtime without restarting the sandbox process, enabling multi-step workflows (e.g., open access during setup → deny-all before running untrusted code).
ts
// Lock down before running untrusted code
await sandbox.updateNetworkPolicy('deny-all');

// Allow specific domains only (SNI filtering)
await sandbox.updateNetworkPolicy({
  allow: ['api.openai.com', '*.googleapis.com'],
});

// Credential brokering (inject API keys so untrusted code never sees them)
await sandbox.updateNetworkPolicy({
  allow: {
    'ai-gateway.vercel.sh': [{
      transform: [{ headers: { 'x-api-key': process.env.SECRET_KEY! } }],
    }],
  },
});
出口防火墙采用SNI过滤机制,在TLS客户端握手阶段匹配出站连接,未授权的目标将在数据传输前被拒绝。对于非TLS流量,同时支持IP/CIDR规则。
策略可在运行时更新,无需重启沙箱进程,支持多步骤工作流(例如:在设置阶段开放所有权限 → 运行不受信任代码前切换为拒绝所有)。
ts
// 运行不受信任代码前锁定网络
await sandbox.updateNetworkPolicy('deny-all');

// 仅允许特定域名(SNI过滤)
await sandbox.updateNetworkPolicy({
  allow: ['api.openai.com', '*.googleapis.com'],
});

// 凭证代理(注入API密钥,使不受信任代码无法直接获取)
await sandbox.updateNetworkPolicy({
  allow: {
    'ai-gateway.vercel.sh': [{
      transform: [{ headers: { 'x-api-key': process.env.SECRET_KEY! } }],
    }],
  },
});

Public URLs and Lifecycle

公共URL与生命周期

ts
// Expose a port and get a public URL
const sandbox = await Sandbox.create({ ports: [3000] });
const url = sandbox.domain(3000); // public URL

// Extend timeout
await sandbox.extendTimeout(300_000); // +5 minutes

// Clean up
await sandbox.stop();

// Check status
sandbox.status; // 'pending' | 'running' | 'stopping' | 'stopped' | 'failed'

// Resource tracking (after stop)
sandbox.activeCpuUsageMs;
sandbox.networkUsage; // { ingress, egress } in bytes
ts
// 暴露端口并获取公共URL
const sandbox = await Sandbox.create({ ports: [3000] });
const url = sandbox.domain(3000); // 公共URL

// 延长超时时间
await sandbox.extendTimeout(300_000); // +5分钟

// 清理资源
await sandbox.stop();

// 检查状态
sandbox.status; // 'pending' | 'running' | 'stopping' | 'stopped' | 'failed'

// 资源使用统计(停止后可查看)
sandbox.activeCpuUsageMs;
sandbox.networkUsage; // { ingress, egress } 单位为字节

List and Rehydrate

列出与重新连接

ts
// List existing sandboxes
const { sandboxes } = await Sandbox.list({ limit: 10 });

// Reconnect to a running sandbox
const sandbox = await Sandbox.get({ sandboxId: 'sbx_abc123' });
ts
// 列出所有已存在的沙箱
const { sandboxes } = await Sandbox.list({ limit: 10 });

// 重新连接到运行中的沙箱
const sandbox = await Sandbox.get({ sandboxId: 'sbx_abc123' });

Timeout Limits

超时限制

PlanMax Timeout
Default5 minutes
Hobby45 minutes
Pro/Enterprise5 hours
套餐最大超时时间
默认5分钟
免费版45分钟
专业版/企业版5小时

Agent Patterns

Agent典型场景

  1. Safe AI code execution: Run AI-generated code without production risk
  2. Snapshot-based fast restart: Install deps once → snapshot → create from snapshot (skip setup)
  3. Network isolation: Allow all during setup →
    deny-all
    before untrusted code
  4. Credential brokering: Inject API keys via network policy transforms
  5. Live preview: Expose ports via
    sandbox.domain(port)
    for generated apps
  6. File I/O workflow:
    writeFiles()
    → execute →
    readFileToBuffer()
    results
  1. 安全AI代码执行:运行AI生成的代码,无生产环境风险
  2. 基于快照的快速重启:一次性安装依赖 → 创建快照 → 从快照启动(跳过设置步骤)
  3. 网络隔离:设置阶段开放所有权限 → 运行不受信任代码前切换为"拒绝所有"
  4. 凭证代理:通过网络策略转换注入API密钥
  5. 实时预览:通过
    sandbox.domain(port)
    暴露端口,用于生成的应用
  6. 文件I/O工作流
    writeFiles()
    → 执行代码 →
    readFileToBuffer()
    获取结果

When to Use

适用场景

  • AI agents need to execute generated code safely
  • User-submitted code execution (playgrounds, tutorials)
  • Code review validation (used by Vercel Agent)
  • Ephemeral development environments
  • AI Agent需要安全执行生成的代码
  • 用户提交代码的执行场景(游乐场、教程)
  • 代码审查验证(Vercel Agent已使用)
  • 临时开发环境

When NOT to Use

不适用场景

  • Production workloads → use Vercel Functions
  • Long-running services → use a dedicated server
  • Simple function execution → use Serverless Functions
  • 生产负载 → 请使用Vercel Functions
  • 长时间运行的服务 → 请使用专用服务器
  • 简单函数执行 → 请使用Serverless Functions

References

参考链接