Expose ports and share preview links
Get a public HTTPS URL for a web server running in a sandbox, wait until it answers, and remove it when you are done.
Serve a page and open it
import { Sandbox } from "@tangle-network/sandbox";
const client = new Sandbox({
apiKey: process.env.TANGLE_API_KEY!,
baseUrl: "https://sandbox.tangle.tools",
});
const box = await client.create();
try {
await box.process.spawn(
`node -e "require('http').createServer((q, s) => s.end('<h1>Served from a sandbox</h1>')).listen(3000)"`,
);
const link = await box.previewLinks.create(3000);
const { url } = await box.previewLinks.waitUntilReady(link.previewId);
console.log(url);
console.log(await (await fetch(url)).text());
} finally {
await box.delete();
}The URL has the form https://<sandbox>-<port>.tangle.sh. waitUntilReady resolves once the public route reaches your server, so the first visitor never sees a startup error.
Port 8080 belongs to the sandbox runtime, so a server started there fails with Address already in use. Serve on another port, such as 3000.
A preview link is public. Anyone with the URL can open it, with no login. Treat the URL as a credential, put your own authentication in the app if it serves private data, and remove the link when you are done.
Manage links
import assert from "node:assert/strict";
import { Sandbox } from "@tangle-network/sandbox";
const client = new Sandbox({
apiKey: process.env.TANGLE_API_KEY!,
baseUrl: "https://sandbox.tangle.tools",
});
const box = await client.create({ agent: false, maxLifetimeSeconds: 300 });
try {
await box.process.spawnExact("python3", ["-m", "http.server", "3000", "--bind", "0.0.0.0"], { timeoutMs: 120_000 });
const link = await box.previewLinks.create(3000, { metadata: { purpose: "review" } });
assert.equal(link.port, 3000);
await box.previewLinks.waitUntilReady(link.previewId, { timeoutMs: 60_000 });
const fresh = await box.previewLinks.get(link.previewId);
assert.equal(fresh.status, "ready");
const links = await box.previewLinks.list();
assert(links.some((item) => item.previewId === link.previewId));
await box.previewLinks.remove(link.previewId);
assert.equal((await box.previewLinks.list()).some((item) => item.previewId === link.previewId), false);
console.log(fresh.status, fresh.lastProbe?.httpStatus);
} finally {
await box.delete();
}create returns the existing link when the port already has one; created says which happened. status is provisioning, ready, error or disabled. get refreshes the link’s last delivery check:
lastProbe.code | Meaning |
|---|---|
PREVIEW_ROUTE_NOT_PUBLISHED | The public route is still being published. |
PREVIEW_UPSTREAM_UNAVAILABLE | Nothing answered on the port inside the sandbox. |
PREVIEW_REQUEST_TIMED_OUT | The server did not answer in time. |
PREVIEW_NETWORK_ERROR, PREVIEW_INVALID_URL | The check could not reach the link. |
ready means the route reached your app. It does not judge the response body, so keep your own health check.
waitUntilReady(previewId, { timeoutMs, pollIntervalMs, signal }) sets how long and how often to check. Aborting the signal stops the wait and leaves the link in place.
Start a dev server and publish it
process.ensureDevServer detects a Node, Rust, Go or Python project, installs dependencies when they are missing, and starts its dev process. A second call returns the server that is already running.
import assert from "node:assert/strict";
import { Sandbox } from "@tangle-network/sandbox";
const client = new Sandbox({
apiKey: process.env.TANGLE_API_KEY!,
baseUrl: "https://sandbox.tangle.tools",
});
const box = await client.create({ agent: false, maxLifetimeSeconds: 300 });
try {
await box.write("app/package.json", JSON.stringify({
name: "dev-server-example", version: "1.0.0", private: true,
scripts: { dev: "node server.cjs" },
}));
await box.write("app/server.cjs", "const http=require('http'); const i=process.argv.indexOf('--port'); const p=i<0?Number(process.env.PORT??3000):Number(process.argv[i+1]); http.createServer((q,s)=>s.end('development ready')).listen(p,'0.0.0.0');");
const server = await box.process.ensureDevServer({ cwd: "app" });
assert(server.port, "The development server returned no port");
assert(server.pid > 0);
const link = await box.previewLinks.create(server.port);
const ready = await box.previewLinks.waitUntilReady(link.previewId, { timeoutMs: 60_000 });
const response = await fetch(ready.url, { signal: AbortSignal.timeout(20_000) });
assert.equal(response.ok, true);
assert((await response.text()).includes("development ready"));
console.log(server.family, server.port, server.startedNow);
} finally {
await box.delete();
}In the CLI, tangle preview start does both steps, and tangle preview publish --port <port> publishes a service that is already running without starting or replacing a process. Inside a sandbox, --self targets the sandbox the command runs in, so a coding agent can share its own work.
Expose a port without a link record
network.exposePort returns a URL string for a port. listUrls returns every exposed port.
import assert from "node:assert/strict";
import { Sandbox } from "@tangle-network/sandbox";
const client = new Sandbox({
apiKey: process.env.TANGLE_API_KEY!,
baseUrl: "https://sandbox.tangle.tools",
});
const box = await client.create({ agent: false, maxLifetimeSeconds: 300 });
try {
await box.process.spawnExact("python3", ["-m", "http.server", "8000", "--bind", "0.0.0.0"], { timeoutMs: 60_000 });
const url = await box.network.exposePort(8000);
assert.equal(typeof url, "string");
assert(url.length > 0);
const urls = await box.network.listUrls();
assert.equal(urls[8000], url);
const config = await box.network.getConfig();
assert(Array.isArray(config.ports));
console.log(url, config.ports);
} finally {
await box.delete();
}tangle sandbox expose my-project --port 8000
tangle sandbox urls my-project --jsonUse previewLinks when you need readiness checks, status and removal by id.
WebSockets and long requests
Preview traffic passes through Cloudflare. WebSockets work, and connections can drop when Cloudflare deploys a release, so an app’s hot reload reconnects on its own. The idle read timeout and the request body cap are on Limits.
From the CLI
tangle preview create my-project 3000
tangle preview list my-project # ids are shortened in the table
tangle preview list my-project --json # full ids
tangle preview remove my-project <preview-id>
tangle preview start my-project --cwd app
tangle preview publish my-project --port 3000tangle preview remove needs the full preview id, so read it from --json.
Python and REST
Python cannot create preview links or expose ports. Use TypeScript, the CLI, or the REST runtime routes through client.fetch, which returns the raw response and does not raise on an error status:
import os
import time
import uuid
from urllib.parse import urlsplit
import httpx
from tangle_sandbox import Sandbox, SandboxStatus
with Sandbox(
api_key=os.environ["TANGLE_API_KEY"],
base_url="https://sandbox.tangle.tools",
) as client:
created = client.fetch("POST", "/v1/sandboxes", json={
"agent": False, "maxLifetimeSeconds": 300,
}).raise_for_status().json()
try:
box = client.get(created["id"])
assert box is not None
box.wait_for(SandboxStatus.RUNNING)
expected = "preview-" + uuid.uuid4().hex
box.write("index.html", expected)
spawned = client.fetch("POST", f"/v1/sandboxes/{box.id}/runtime/process/spawn", json={
"executable": "python3", "args": ["-m", "http.server", "8000", "--bind", "0.0.0.0"],
"blocking": False, "timeoutMs": 120_000,
}).raise_for_status().json()
assert spawned["success"] is True
assert spawned["data"]["pid"] > 0
response = client.fetch("POST", f"/v1/sandboxes/{box.id}/runtime/network/expose", json={"port": 8000})
response.raise_for_status()
url = response.json()["url"]
assert urlsplit(url).scheme == "https"
deadline = time.monotonic() + 60
served = False
while time.monotonic() < deadline:
try:
public = httpx.get(url, timeout=5)
if public.status_code == 200 and public.text == expected:
served = True
break
except httpx.HTTPError:
pass
time.sleep(0.5)
assert served, "The exposed port did not serve the owned page before the deadline"
print(url)
finally:
client.fetch("DELETE", f"/v1/sandboxes/{created['id']}").raise_for_status()