SDK
Ports

Ports

The Ports API allows you to monitor and interact with HTTP ports in your sandbox. This is particularly useful when working with development servers or any other services that need to listen on specific ports.

Whenever a port is opened within a sandbox, we'll automatically expose it under https://<sandbox-id>-<port>.csb.app.

💡

If the sandbox is private you need to use the host tokens.

We automatically resume a sandbox whenever a port is accessed while the sandbox is hibernated.

API

The Ports API is available under sandbox.ports. It provides methods for monitoring port activity.

Monitoring Ports

You can listen for ports being opened and closed in your sandbox:

const sandbox = await sdk.sandboxes.create()
const session = await sandbox.connect()
 
// Listen for ports being opened
const listener1 = session.ports.onDidPortOpen((portInfo) => {
  console.log(`Port ${portInfo.port} opened`);
  console.log(`URL: ${session.hosts.getUrl(portInfo.port)}`);
});
 
// Listen for ports being closed
const listener2 = session.ports.onDidPortClose((port) => {
  console.log(`Port ${port} closed`);
});
 
// Remove listeners when done
listener1.dispose();
listener2.dispose();

Getting Port Information

You can get information about currently opened ports:

const sandbox = await sdk.sandboxes.create()
const session = await sandbox.connect()
 
// Get all opened ports
const openPorts = session.ports.getAll();
for (const port of openPorts) {
  console.log(`Port ${port.port} is open at ${port.host}`);
}

Waiting for Ports

When starting services, you often need to wait for a port to become available:

const sandbox = await sdk.sandboxes.create()
const session = await sandbox.connect()
 
// Start a development server
const command = session.commands.runBackground("npm run dev");
 
// Wait for the dev server port to open
const portInfo = await session.ports.waitForPort(3000);
console.log(`Dev server is ready at: ${portInfo.host}`);