Skip to content
AnswerWell geo Documentation

Research · 7 min read · Answerwell

Sandbox Browser Terminal: WebSocket PTY, xterm.js, Sessions, Protocol

How to connect a browser shell to a sandbox over WebSocket—Worker terminal(), xterm.js SandboxAddon, sessions, PTY protocol, and 0.x vs 1.0 behavior.

This page summarises Cloudflare documentation on exposing a live Linux shell from a sandbox in the browser. The browser runs a terminal UI (typically xterm.js) and talks to the container over WebSocket through a Worker. On the server, terminal() proxies the upgrade to a pseudo-terminal (PTY); on the client, SandboxAddon (Sandbox SDK 0.x) or a direct WebSocket (1.0) handles I/O, resize, and reconnection.

A browser terminal answers the need for an interactive shell in a remote sandbox—the same experience as SSH or a local terminal emulator—instead of firing one-off commands with exec().

Terminal connections let browser-based UIs interact directly with sandbox shells. Instead of executing discrete commands with exec(), a terminal connection opens a persistent, bidirectional channel to a bash shell — the same model as SSH or a local terminal emulator.

— Cloudflare, Terminal connections

The Sandbox SDK ↗︎ now supports PTY (pseudo-terminal) passthrough, enabling browser-based terminal UIs to connect to sandbox shells via WebSocket.

— Cloudflare, Interactive browser terminals in Sandboxes

Approach Use when
exec() Single command, non-interactive output
terminal() / PTY WebSocket Interactive shell, ANSI output, long-running processes

How WebSocket terminal connections work in the Worker

Section titled “How WebSocket terminal connections work in the Worker”

Terminal traffic follows a fixed path: the browser upgrades WebSocket to your Worker; the Worker forwards to the container PTY; raw bytes flow both ways.

Browser (xterm.js) <– WebSocket –> Worker <– proxy –> Container PTY (bash)

— Cloudflare, Terminal connections

Connect browser-based terminal UIs to sandbox shells via WebSocket. The server-side terminal() method proxies WebSocket connections to the container, and the client-side SandboxAddon integrates with xterm.js for terminal rendering.

— Cloudflare, Terminal

The new terminal() method proxies a WebSocket upgrade to the container’s PTY endpoint, with output buffering for replay on reconnect.

— Cloudflare, Interactive browser terminals in Sandboxes

terminal(request): proxy WebSocket upgrades in the Worker

Section titled “terminal(request): proxy WebSocket upgrades in the Worker”

terminal() accepts a WebSocket upgrade (Upgrade: websocket) and returns the upgrade response. Optional cols and rows set initial PTY size (defaults 80×24).

Prerequisites from the Browser terminals guide: an existing Cloudflare Worker with a sandbox binding, plus frontend packages @xterm/xterm, @xterm/addon-fit, and @cloudflare/sandbox when using xterm.js.

  1. Route paths such as /ws/terminal when the request is a WebSocket upgrade.

  2. Call getSandbox(env.Sandbox, sandboxId) and either sandbox.terminal(request, { cols, rows }) or session.terminal(request) for a named session.

  3. Return the WebSocket response from terminal(); other requests get your normal handlers.

Named sessions use a query parameter (for example session) so one Worker route can serve the default shell and isolated session shells—see Handle WebSocket upgrades in the Worker.

Sessions: multiple isolated terminals in one sandbox

Section titled “Sessions: multiple isolated terminals in one sandbox”

Each session can own its own terminal with its own working directory and environment, so users can run separate shells side by side in the same container.

Each session can have its own terminal with an isolated working directory and environment, so users can run separate shells side-by-side in the same container.

— Cloudflare, Interactive browser terminals in Sandboxes

Use await sandbox.getSession(sessionId) then return await session.terminal(request) for session-scoped PTY. Scope terminals per user sandbox; use sessions for multiple contexts in one workspace and separate sandboxes for separate users (Best practices).

xterm.js and SandboxAddon: connect the browser UI (SDK 0.x)

Section titled “xterm.js and SandboxAddon: connect the browser UI (SDK 0.x)”

For Sandbox SDK 0.x, Cloudflare documents Browser terminals and the Terminal API reference. New applications should follow Open a terminal in the browser; existing 0.x apps can move using Move browser terminals.

This guide shows you how to connect a browser-based terminal to a sandbox shell. You can use the SandboxAddon with xterm.js, or connect directly over WebSockets.

— Cloudflare, Browser terminals

The new @cloudflare/sandbox/xterm export provides a SandboxAddon for xterm.js ↗︎ with automatic reconnection (exponential backoff + jitter), buffered output replay, and resize forwarding.

— Cloudflare, Interactive browser terminals in Sandboxes

SandboxAddon setup: WebSocket URL, connect, and resize

Section titled “SandboxAddon setup: WebSocket URL, connect, and resize”

SandboxAddon from @cloudflare/sandbox/xterm manages the WebSocket, reconnection, and resize forwarding. You implement getWebSocketUrl({ sandboxId, sessionId?, origin }) to point at your Worker route (for example ${origin}/ws/terminal?…). Call addon.connect({ sandboxId, sessionId? }) after loading the addon into xterm.js.

Use FitAddon and call fitAddon.fit() on window resize so column and row counts match the DOM and the PTY—without FitAddon, text wraps incorrectly (Best practices). On unmount, call addon.disconnect().

onStateChange reports connecting, connected, or disconnected. Calling connect() with a new target switches sessions; same target while connected is a no-op (SandboxAddon).

WebSocket PTY protocol: custom clients without xterm.js

Section titled “WebSocket PTY protocol: custom clients without xterm.js”

If you build a custom UI, connect directly over WebSockets. Set binaryType to arraybuffer before connecting.

Direction Frame type Content
Client → server Binary UTF-8 keystrokes
Server → client Binary Terminal output (including ANSI)
Client → server Text (JSON) Control (for example resize)
Server → client Text (JSON) Status (ready, exit, error)

The HTTP bridge documents the same model on GET /v1/sandbox/:id/pty with query params cols, rows, shell, and session (HTTP API reference).

Connection lifecycle, buffering, and control messages

Section titled “Connection lifecycle, buffering, and control messages”
  1. Client opens WebSocket to the Worker; server may replay buffered output as binary frames before ready.
  2. Server sends {"type":"ready"} when the PTY accepts input; client should send initial resize if needed.
  3. Binary I/O runs in both directions until disconnect or exit.

If the client disconnects, the PTY stays alive. Reconnecting to the same session replays buffered output so the terminal appears unchanged.

— Cloudflare, Connection lifecycle

The container buffers terminal output in a ring buffer. When a client disconnects and reconnects, the server replays buffered output so the terminal appears unchanged.

— Cloudflare, Output buffering

Resize (client → server) must include positive cols and rows:

{ "type": "resize", "cols": 120, "rows": 30 }

Status examples from the server (Status messages): ready, exit with code and signal, error with message. Full walkthrough: Connect without xterm.js.

Sandbox SDK 1.0: tmux sessions and no SandboxAddon

Section titled “Sandbox SDK 1.0: tmux sessions and no SandboxAddon”

Move browser terminals describes the behavioral shift when upgrading to @cloudflare/sandbox 1.0:

In Sandbox SDK 0.12, terminal() attaches a WebSocket to a shell that the container keeps for each session, and SandboxAddon reconnects the browser to it. In 1.0, your Durable Object attaches each WebSocket to a tmux ↗︎ session with exec(argv, { pty }). tmux keeps the shell running between connections.

— Cloudflare, Move browser terminals

1.0 has no @cloudflare/sandbox/xterm module; the page opens the WebSocket itself with retry logic similar to the addon (exponential backoff, cap at 10 attempts). Reconnect shows tmux’s redrawn screen rather than replaying up to 256 KiB of buffered output as in 0.12. Shell exit closes the socket with code 1000 and a reason such as Terminal closed with code 0; the next connection starts a new shell. Detaching with Ctrl+B then D also closes with 1000 while the tmux session keeps running.

Open a terminal in the browser describes the 1.0 pattern: xterm.js plus WebSocket to a tmux-backed shell that survives reloads. To end a session from the Worker without a browser, run tmux kill-session in the Durable Object (see that command doc).

  • Skipping FitAddon or resize handling — PTY size drifts from the visible grid; always fit on load and window resize.
  • Forgetting binaryType — Custom clients must use arraybuffer before connect.
  • Treating JSON as terminal output — Binary frames are shell I/O; parse string frames as control/status only.
  • Not calling addon.disconnect() — Leaves stale connections when removing the UI from the page.
  • Wrong session scope — Multiple users in one sandbox without session isolation share one shell context.

Automatic reconnection in 0.x is built into SandboxAddon; custom clients must implement their own backoff while server-side buffering still applies (Automatic reconnection).

Further reading: Terminal connections, Terminal API reference, API reference.

  1. Deploy the Worker route that calls terminal() on a WebSocket upgrade to /ws/terminal (or your chosen path), matching Browser terminals.
  2. Open the page with xterm.js, connect with SandboxAddon (0.x) or your 1.0 WebSocket client per Move browser terminals.
  3. In browser developer tools, select the terminal WebSocket and confirm the first JSON message is {"type":"ready"} after connect (Check the terminal).
  4. Run echo pwd=$(pwd) NODE_ENV=$NODE_ENV; stty size and confirm working directory, env vars, and dimensions match what you sent (for example cols/rows query params or resize messages).
  5. Start a long-running loop, reload the page, and confirm the process state matches your SDK version (buffer replay in 0.x vs tmux redraw in 1.0); run exit and confirm the socket closes with code 1000 without unwanted reconnect.
  6. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about.