Koyeb Sandbox SDK for JavaScript/TypeScript

September 1, 2026 ยท View on GitHub

License npm version

Overview

The Koyeb Sandbox SDK enables you to manage and interact with ephemeral sandboxes on Koyeb, a modern cloud infrastructure provider. Sandboxes are secure, isolated environments designed to execute untrusted or user-supplied code safely.

This SDK is ideal for building online code runners, education platforms, CI/CD systems, and any application that requires secure, on-demand code execution.

  • โšก Ephemeral environments: Create, manage, and destroy sandboxes programmatically
  • ๐Ÿ”’ Secure execution: Run untrusted code with strong isolation
  • ๐Ÿ“ Filesystem management: Upload / download files, create directories and more
  • โš™๏ธ Background processes: Start and manage background processes
  • ๐ŸŸฆ TypeScript support: Fully typed for a great developer experience

Installation

npm install @koyeb/api-client-js @koyeb/sandbox-sdk

Set your API access token before using the SDK:

export KOYEB_API_TOKEN="<your-api-token>"

Quick Start

import { Sandbox } from '@koyeb/sandbox-sdk';

async function main() {
  const sandbox = await Sandbox.create();

  const { stdout } = await sandbox.exec("echo 'Hello from Koyeb Sandbox!'");
  console.log(stdout.trim());

  await sandbox.delete();
}

main().catch(console.error);

See more examples.

Creating Sandboxes

Sandbox.create(options?)

Creates a new sandbox.

Options

OptionDescription
imageDocker image to boot. Defaults to koyeb/sandbox.
nameName shown in Koyeb and used in resource names.
wait_readyWait until the sandbox becomes healthy (enabled by default)
instance_typeInstance size to provision. Defaults to micro.
exposed_port_protocolProtocol used by the exposed port (one of http | http2).
envEnvironment variables injected into the container.
regionKoyeb region slug. Defaults to 'na' (north america).
api_tokenAPI token for authentication, overriding process.env.KOYEB_API_TOKEN.
timeoutSeconds to wait while checking readiness.
idle_timeoutSeconds before the sandbox scales to zero. Set 0 to disable sleep.
enable_tcp_proxyEnable TCP proxying on port 3031.
privilegedRun the sandbox in privileged mode.
registry_secretName of the Koyeb registry secret required to pull private images.
delete_after_delayTime to wait before automatically deleting the sandbox after creation.
delete_after_inactivity_delayTime to wait before automatically deleting the sandbox after inactivity.
_experimental_enable_light_sleepWhen enabled, uses idle_timeout for light_sleep and sets deep_sleep=3900.
block_networkBlock all outbound network access. Mutually exclusive with outbound_allowlist.
outbound_allowlistIPs/CIDRs allowed as outbound destinations; all other traffic is blocked. Bare IPs are normalized to /32 (IPv4) or /128 (IPv6).

Sandbox.get_from_id(serviceId, apiToken?)

Load an existing Sandbox from a Koyeb service ID. Useful for long-lived integrations.

Sandbox Lifecycle & Metadata

MethodDescription
wait_ready(timeout?, pollInterval?, signal?)Polls health until success or timeout. Resolves to true on success.
wait_tcp_proxy_ready(timeout?, pollInterval?, signal?)Polls until TCP proxy information becomes available.
is_healthy()Performs a /health check against the sandbox URL.
get_sandbox_url()Returns the HTTPS URL (https://<domain>/koyeb-sandbox).
get_tcp_proxy_info()Returns [host, publicPort] once the TCP proxy is ready, otherwise undefined.
get_domain()Fetches and caches the sandbox domain metadata.
update_lifecycle()Change the auto deletion properties.
update_network_policy(values?)Update the egress policy (block, allowlist, or reset). Triggers a redeployment.
delete()Tears down the underlying service.

Command Execution

MethodDescription
exec(cmd, options?)Runs a command and resolves with { stdout, stderr, code }. Supports cwd, env, and AbortSignal.
exec_stream(cmd, options?)Streams command output using Server-Sent Events. Emits stdout, stderr, and end.

Streaming Example

const stream = sandbox.exec_stream('npm test');

stream.addEventListener('stdout', ({ data }) => {
  process.stdout.write(`${data.data}\n`);
});

stream.addEventListener('stderr', ({ data }) => {
  process.stderr.write(`${data.data}\n`);
});

stream.addEventListener('exit', ({ data }) => {
  process.stderr.write(`Exit code: ${data.code}\n`);
});

stream.addEventListener('end', () => {
  console.log('Command finished');
});

Port Exposure

MethodDescription
expose_port(port)Binds a sandbox port to the public domain. Resolves { port, exposed_at }.
unexpose_port(port?)Unbinds the exposed port. Pass a specific port or omit to unbind the current one.

Process Management

MethodDescription
launch_process(cmd, options?)Starts a long-lived background process and returns its ID.
kill_process(processId)Stops a process started with launch_process.
list_processes()Lists processes with their status.
kill_all_processes()Stops every running sandbox process and returns the count.

Filesystem Helpers

Access via sandbox.filesystem. Operations run over the sandbox API and fall back to exec only when needed.

MethodDescription
mkdir(path, recursive?)Create a directory.
list_dir(path?)List entries inside a directory. Defaults to ..
delete_dir(path)Delete a directory tree.
write_file(path, content)Create or replace a text file.
write_files(files)Bulk write helper for multiple files.
read_file(path)Fetch { content, encoding } for a remote file.
rename_file(oldPath, newPath)Rename using an internal mv command.
rm(path, recursive?)Remove a file or directory (rm -rf when recursive).
exists(path)Return true if the path exists.
is_file(path)Return true if the path is a regular file.
is_dir(path)Return true if the path is a directory.
upload_file(localPath, remotePath)Read a local file and upload it.
download_file(localPath, remotePath)Download a sandbox file to disk.

Error Types

The SDK exports the following error classes for granular handling:

  • MissingApiTokenError
  • InvalidPortError
  • SandboxTimeoutError
  • NoSandboxSecretError
  • SandboxRequestError
  • EgressPolicyError

Contributing

Install dependencies with pnpm install and run pnpm build to compile TypeScript into lib/.

Need help? Reach out on community.koyeb.com.

Releasing a new version

Releases are published manually to the public npm registry as @koyeb/sandbox-sdk.

Prerequisites:

  • Publish rights on the @koyeb npm organization.

  • Log in against the public registry (required if your global npm registry points elsewhere):

    npm login --registry=https://registry.npmjs.org/
    npm whoami --registry=https://registry.npmjs.org/
    

Release steps:

# 1. Bump the version (creates a commit and a git tag)
npm version patch   # or: minor / major

# 2. Build and publish (the release script recompiles lib/ before publishing)
pnpm release

# 3. Push the version commit and tag
git push --follow-tags

Notes:

  • publishConfig in package.json forces the publish to registry.npmjs.org with public access, so it works regardless of your global npm registry.
  • The release script runs pnpm build explicitly, so the published lib/ is always fresh even when npm lifecycle scripts are disabled (ignore-scripts=true).
  • pnpm publish requires a clean git working tree; commit your changes first, or pass --no-git-checks to bypass the check.

License

This project is licensed under the Apache-2.0 License. See LICENSE for details.