SDK
Terminals

Terminals

A terminal is a shell process which you can write to, listen to and is often combined with xTerm in the browser to allow users to get a full terminal experience.

The Terminals API allows you to create, manage and interact with terminal processes in your sandbox.

API

The Terminals API is available under sandbox.terminals.

Creating Terminals

You can create an interactive terminal that allows you to write, run commands and receive output:

const sandbox = await sdk.sandboxes.create()
const session = await sandbox.connect()
 
// Create a new terminal (bash is default)
const terminal = session.terminals.create()
 
// Open the terminal to get its current output. Required to get output events.
const output = await terminal.open();
 
// Listen to terminal output
const onOutputDisposer = terminal.onOutput((output) => {
  console.log(output);
});
 
// Run commands
await terminal.run("echo 'Hello, world!'");
 
// Kill the terminal when done
await terminal.kill();
 
// Dispose the listener when done
onOutputDisposer.dispose();
💡

Typically you want terminals to live beyond the immediate session of the user. Use the session.terminals.getAll() method to retrieve any existing terminals.

Browser Terminal

The terminal API is often combined with xTerm (opens in a new tab) to allow users to get a full terminal experience. In combination with local-echo (opens in a new tab) you can give your users an excellent terminal experience in the browser.

import { connectToSandbox } from "@codesandbox/sdk/browser";
import { Terminal } from '@xterm/xterm'
 
const sandbox = await connectToSandbox({
  session: initialSessionFromServer,
  getSession: (id) => fetchJson(`/api/sandboxes/${id}`)),
})
const terminal = await sandbox.terminals.create()
const xterm = new Terminal()
 
xterm.open(document.getElementById('terminal'))
 
// Open to get current output and subscribe to output events
const output = await terminal.open();
 
xterm.write(output)
 
terminal.onOutput((output) => {
  xterm.write(output)
});
 
xterm.onData((data) => {
  terminal.write(data)
})