Low-level SDK

Client

The browser-side API for creating and controlling an isolated Node.js runtime. Use it when you want full control over files, commands, processes, and previews.

$npm i @nodesandbox-ai/client

Create a sandbox

Pass a public, origin-scoped API key and a project source to Sandbox.create(). Creation prepares the filesystem and installs dependencies. Start a preview explicitly with start(). The core includes the shell, Node/npm, terminals, and previews; agent commands are optional plugins.

sandbox.ts
import { Sandbox } from '@nodesandbox-ai/client';

const sandbox = await Sandbox.create({
  apiKey: import.meta.env.VITE_NODESANDBOX_API_KEY,
  source: {
    type: 'git',
    url: 'https://github.com/vercel/sandbox-example-next.git',
  },
});
Safe for the browser.

API keys are intentionally public and only authorize exact origins configured in your dashboard.

Send COOP and COEP headers.

The page that embeds a sandbox must be cross-origin isolated, or the runtime has no SharedArrayBuffer. See Cross-origin isolation.

Readiness and events

onReady fires once files and shell commands are usable, while npm may still be installing. The callback receives the sandbox and is not awaited. Sandbox.create() resolves after dependency installation and framework setup.

readiness.ts
const sandbox = await Sandbox.create({
  apiKey,
  source,
  onReady(sandbox) {
    // Commands that do not need project dependencies can run now.
    void sandbox.runCommand('ls').then(result => {
      console.log(result.stdout);
    }).catch(console.error);
  },
  onDevOutput: chunk => console.log(chunk),
});

// Project-dependent work starts after create() resolves.
const preview = await sandbox.start();
console.log(preview.url);
APIBehavior
onReady(sandbox)The filesystem, commands, and terminals are available. This does not imply dependencies or an agent are ready.
onBootProgress(progress)Dependency progress while the runtime boots: phase (resolving, restoring, installing, then complete), completed, total (null when it cannot count), and message.
onLog(entry)Runtime log entries containing source, message, and ts.
onDevOutput(chunk)Raw stdout/stderr from the dev process started by start() with the Node engine.
onFileChanged(path, content, meta)A project file changed inside the runtime. Null means deleted; meta.encoding === "base64" identifies binary content.
onHmr(update)An HMR update with type and path.
onConsole(event)Console events from the preview.

Use onDevOutput to recognize framework-specific startup output: buffer complete lines and remove ANSI escapes before matching a banner. There is no onNextReady callback. start() resolves when its HTTP listener is available. Agent readiness and credential events belong to each plugin.

Files

sandbox.fs is the editor's mirrored virtual filesystem. Project edits synchronize with the runtime. Use requestFileSystem() when you need an acknowledged operation on the runtime's authoritative filesystem, including generated and agent configuration files.

files.ts
sandbox.fs.writeFileSync('/index.html', '<h1>Updated</h1>');

await sandbox.requestFileSystem('mkdir', { path: '/config', recursive: true });
await sandbox.requestFileSystem('writeFile', {
  path: '/config/example.json',
  data: new TextEncoder().encode(JSON.stringify({ enabled: true })),
});
const bytes = await sandbox.requestFileSystem('readFile', {
  path: '/config/example.json',
});
console.log(new TextDecoder().decode(bytes));

Run commands

Use runCommand() for a program and argument list. It keeps arguments separate across the transport. Reach for runShell() only when you intentionally need shell syntax.

commands.ts
const version = await sandbox.runCommand('node', ['--version']);
console.log(version.stdout); // v25.5.0

const files = await sandbox.runShell('find src -name "*.tsx" | sort');
console.log(files.stdout);
runCommand(program, args)

Direct, safely separated arguments.

runShell(command)

Pipes, redirects, variables, and shell expansion.

runScript(name)

Run a finite package.json script.

commands.session()

Keep a working directory and environment between calls.

Terminals

Create a terminal, attach your UI, and then open it. startCommand runs once after opening, so an interactive program starts with the attached terminal's dimensions.

terminal.ts
const terminal = sandbox.terminals.create({
  cwd: '/', cols: 100, rows: 30,
});
const output = terminal.onOutput(chunk => terminalView.write(chunk));
const input = terminalView.onData(data => terminal.write(data));
terminalView.write(await terminal.open());
terminal.resize({ cols: 120, rows: 40 });

// When the panel closes:
input.dispose();
output.dispose();
await terminal.kill();

terminalView represents your terminal renderer, such as xterm.js. For an agent, install its plugin and set startCommand: 'claude', 'opencode', or 'codex'. Terminals can run basic commands during installation; await create() before launching work that needs project dependencies.

Plugins

Provide the optional commands and programs each sandbox needs. The default is plugins: []. Plugins own their assets, credentials, readiness events, and cleanup.

plugins.ts
import { claudeCodePlugin } from '@nodesandbox-ai/plugin-claude';
import { opencodePlugin } from '@nodesandbox-ai/plugin-opencode';

const claude = claudeCodePlugin();
const opencode = opencodePlugin({ preload: true });
const sandbox = await Sandbox.create({
  apiKey, source, plugins: [claude, opencode],
});

await sandbox.plugins.get(claude).prepare(); // Does not launch Claude.
const terminal = sandbox.terminals.create({ startCommand: 'claude' });
await terminal.open();

See Plugins for lifecycle and credential APIs, or Develop a plugin for custom commands and terminal programs.

Long-running processes

Spawn a dev server, stream its output, and wait for the exact listener you expect. The process handle exits early if startup fails and can be terminated explicitly.

server.ts
const process = await sandbox.spawn('npm', ['run', 'dev']);

const stopListening = process.onOutput((chunk) => {
  console.log(chunk);
});

const preview = await sandbox.waitForPort(3000, { process });
console.log(preview.url, preview.port);

// Later:
stopListening();
process.kill('SIGTERM');

For the common case, start() spawns npm run dev and discovers the first HTTP listener. Pass { port: 3000 } when your application requires an exact port.

Project sources

Initialize from in-memory files, a ZIP archive, or a shallow Git checkout. NodeSandbox stores no files, so bring them from your own storage or Git. Omit source for an empty sandbox that only needs commands.

sources.ts
const files = await Sandbox.create({
  apiKey,
  source: { type: 'files', files: { 'index.js': 'console.log("hi")' } },
});

const zip = await Sandbox.create({
  apiKey,
  source: { type: 'zip', url: 'https://example.com/project.zip' },
});

const git = await Sandbox.create({
  apiKey,
  source: {
    type: 'git',
    url: 'https://github.com/org/repo.git',
    branch: 'staging', // defaults to the remote's default branch
  },
});

Lifecycle

Provide a stable sessionId when a runtime needs to retain the same isolated origin. Always dispose the runtime when its owning screen or session ends.

For a local or self-hosted runtime, supply hostUrl instead of a hosted API key. sessionId identifies a disposable runtime origin; projectId names the workspace, and plugins key browser-local state by it. Pass signal to cancel creation or dispose the sandbox on abort.

Installed packages' large files (32 KiB and up) stay compressed in the sandbox's memory, inflated only when read. Most of node_modules is never read, so this lowers memory use by a few hundred MiB for a Next.js app, at the cost of a slightly slower first install. It is on by default; set compressPackages: false to store them uncompressed.

self-hosted.ts
const controller = new AbortController();
const sandbox = await Sandbox.create({
  hostUrl: 'http://localhost:4322',
  signal: controller.signal,
});
console.log((await sandbox.runCommand('ls')).stdout);
// Later: controller.abort();

An installation failure rejects create() and disposes any handle already delivered to onReady. Always handle creation errors and release the sandbox when the owning screen closes.

lifecycle.ts
const sandbox = await Sandbox.create({
  apiKey,
  sessionId: 'project-preview-42',
  source: { type: 'files', files },
});

window.addEventListener('pagehide', () => sandbox.dispose(), { once: true });