Skip to content

Previews

When a program in the VM listens on a port, for example a small web server on port 3000, vm.exposePort gives you a URL for it. Put that URL in an iframe or open it in a new tab, and the guest server answers. The requests never leave the browser: a Service Worker on a separate preview origin hands them to the server inside the VM.

With the hosted runtime frame, previews work without setup: the SDK serves them from https://<session>.tabvm.dev. With a self-hosted engine, or to use a preview origin of your own, they need two things: a preview option when you create the VM, and a host that serves the SDK’s preview files on that origin. Previews work in both modes.

This demo writes the Python web server on the left into a Linux VM in this tab, starts it and shows the page it answers with on the right. The requests go from the preview to the server inside your browser. Change the code, then apply your changes to restart the server.

The VM runs a small image of its own, Alpine Linux with Python 3, built with the image builder. It downloads only the files Python reads.

A web server in the VMUserspaceNot started
localhost:3000
Downloads Linux into this tab when you click.

It works like the example below: vm.workspace.writeText puts the file in the workspace, vm.spawn starts python3 server.py, and vm.exposePort(3000) returns the address the preview opens.

OxVM uses tabvm.dev for isolated previews and reserves oxvm.dev for trusted services. Change a configured preview origin under oxvm.dev to https://tabvm.dev, or omit preview to use the hosted default. Keep per-session isolation. The SDK refuses a preview origin under oxvm.dev before it starts the VM, even with the old official runtime host.

To use your own preview origin, pass preview to createVM:

Option Meaning
origin A bare origin with no path or query: HTTPS, or HTTP on localhost, a name ending in .localhost, 127.0.0.1 or [::1]. It must not be your app’s origin.
isolation: "per-session" Each preview gets its own origin, https://<session>.<preview host>/, so cookies and storage stay apart between previews. The origin needs a host name, not an IP address. Use this for deployed apps.
isolation: "shared" with developmentOnly: true Every preview opens on the preview origin itself, and all of them share cookies and storage. Use it only for local development, for example when you cannot set up wildcard host names. The origin may be an IP address.

Without preview, a VM in the frame on https://run.oxvm.dev uses { origin: "https://tabvm.dev", isolation: "per-session" }. Any other VM created without preview reports vm.capabilities.previews as { available: false, reason: "not-configured" }, and exposePort rejects with FEATURE_NOT_AVAILABLE.

This example writes a small Node.js server into the workspace, starts it, and shows it in an iframe:

preview.ts
import { createVM } from "@oxvm/sdk";
const serverSource = `
require("node:http")
.createServer((request, response) => {
response.writeHead(200, { "content-type": "text/html; charset=utf-8" });
response.end("<h1>Hello from the guest</h1>");
})
.listen(3000, "0.0.0.0");
`;
// Read a process stream to the end so the guest never blocks on a full pipe.
function drain(stream: ReadableStream<Uint8Array>): void {
const decoder = new TextDecoder();
stream
.pipeTo(new WritableStream({ write: (bytes) => console.log(decoder.decode(bytes, { stream: true })) }))
.catch((error: unknown) => console.error(error));
}
export async function startPreview(frame: HTMLIFrameElement): Promise<() => Promise<void>> {
const vm = await createVM({ mode: "userspace", runtime: { hosting: "frame" } });
try {
await vm.workspace.writeText("server.cjs", serverSource);
const server = await vm.spawn({ command: "node", args: ["server.cjs"] });
await server.stdin.close();
drain(server.stdout);
drain(server.stderr);
const preview = await vm.exposePort(3000, { signal: AbortSignal.timeout(60_000) });
frame.src = preview.url.href;
// Disposing the VM closes its previews and stops the server.
return () => vm.dispose();
} catch (error) {
await vm.dispose();
throw error;
}
}

With a self-hosted engine, also pass preview: { origin: "https://preview.example.com", isolation: "per-session" } and host the preview files there.

exposePort waits until a guest program listens on the port at an address the SDK can reach, and until the preview origin is connected. Bound that wait with signal; the deadline above is your choice. It then resolves with a PreviewHandle:

Member Meaning
url The preview’s URL. Use url.href as an iframe src or a link.
port The guest port.
isolation "per-session" or "shared", as configured.
close() Removes the route. The guest server keeps running.

Exposing the same port again while its route is open shares that route, which closes when its last handle closes. vm.dispose() closes every preview of the VM.

To keep the preview connected, the SDK adds a hidden iframe from the preview origin to your page. The URL works in your iframe and in other tabs while the page that created the VM stays open.

vm.listeningPorts() returns the ports guest programs listen on right now. vm.watchListeningPorts(onChange, { signal }) calls onChange with the current list and then after every change, until signal aborts; its promise then resolves. It rejects if reading the ports fails or your callback throws.

ports.ts
import type { VM } from "@oxvm/sdk";
export function watchPorts(vm: VM, render: (lines: string[]) => void): AbortController {
const watching = new AbortController();
vm.watchListeningPorts(
(ports) => {
render(ports.map((port) => `${port.port} ${port.program ?? "unknown program"} ${port.previewable ? "" : "(unreachable)"}`));
},
{ signal: watching.signal },
).catch((error: unknown) => console.error(error));
return watching;
}

Each entry is a ListeningPort:

Field Meaning
port The port number.
address The address the program bound, such as 0.0.0.0 or ::.
program The listening program, or null when it is not known.
previewable Whether exposePort can reach this listener.

Bind guest servers to 0.0.0.0 or 127.0.0.1; both modes reach those. Userspace also reaches ::1, System does not. A listener the SDK cannot reach still appears in the list with previewable: false, and exposePort keeps waiting for a reachable one.

The SDK presents each request the way a browser on the same machine sends it to localhost, in both modes. Development servers therefore work without allowedHosts, allowedDevOrigins or similar settings:

  • Host is localhost:<port> for requests and WebSocket upgrades.
  • Origin and Referer headers that name the preview origin become http://localhost:<port>, and Referer keeps its path and query. Other origins pass unchanged. A WebSocket upgrade always carries Origin: http://localhost:<port>.
  • X-Forwarded-Proto and X-Forwarded-Host name the preview origin, for servers that build public URLs behind a proxy.
  • In responses, absolute http://localhost:<port>, http://127.0.0.1:<port> and http://[::1]:<port> URLs in Location, Content-Location, Refresh and Access-Control-Allow-Origin point back at the preview origin. Response bodies and other ports are not rewritten.
  • A cookie set with Domain=localhost is kept as a host-only cookie of the preview origin. Secure cookies are kept the way a browser keeps them on localhost.

A preview page runs the guest’s code in your user’s browser, so by default it reaches only its own origin. Your app decides which other sites its pages may reach, for example a weather API that a page calls with fetch.

A preview page’s Content Security Policy admits its own preview origin, plus data: and blob: where pages need them, and nothing else: connect-src 'self'. fetch, XMLHttpRequest, EventSource and WebSocket to another host fail, and so do scripts, styles, fonts, images, media and frames from one. A WebSocket to the page’s own host still reaches the guest’s server.

Earlier preview files set connect-src 'self' ws: wss:, which let a page’s sockets reach any host. The default no longer allows plain ws: or wss: to another host: a wss: socket connects only to a site your app allowed, and a ws: socket to another host never does. The preview host’s files set this policy, and one preview host serves previews of every SDK version. Once a preview host, such as tabvm.dev for the hosted frame, serves the files of an SDK release with site access, the default applies to all of its previews, whichever SDK version created them. A page that relied on sockets to another host reaches it again once your app allows the site.

Site access is a PreviewSiteAccess:

Access The preview’s pages may also reach
{ kind: "none" } Nothing. This is the default.
{ kind: "sites", sites } https:// and wss:// on each listed site, at most 64 (MAX_PREVIEW_SITES).
{ kind: "any" } Every https: and wss: origin. Never http: or ws:.

A site is a DNS host name with an optional port, in canonical form. previewSite(value) from @oxvm/sdk turns a host name, or an https:// or wss:// URL, into that form: lowercase, punycode, without one trailing dot and without port 443, so "https://API.Example.com:443/v1" becomes "api.example.com". It returns null for IP addresses, localhost and names below it, single-label names, names ending in .local and other schemes, and setSiteAccess refuses those sites.

A granted site joins the policy’s default-src, script-src, style-src, img-src, font-src and connect-src; worker-src, frame-ancestors and base-uri stay as they are. The preview keeps Cross-Origin-Embedder-Policy: require-corp, so an image, script or stylesheet that a page loads from a granted site without CORS still needs Cross-Origin-Resource-Policy from that site.

Pass siteAccess when you expose the port, and change it later with the handle’s setSiteAccess:

preview-sites.ts
import { MAX_PREVIEW_SITES, previewSite, type PreviewHandle, type VM } from "@oxvm/sdk";
// Exposes the app with the one API its pages call already allowed.
export function exposeWeatherApp(vm: VM): Promise<PreviewHandle> {
return vm.exposePort(3000, {
siteAccess: { kind: "sites", sites: ["api.open-meteo.com"] },
signal: AbortSignal.timeout(60_000),
});
}
// Adds a site the user allowed, then reloads the preview so its next page may reach it.
export async function allowSite(
preview: PreviewHandle,
frame: HTMLIFrameElement,
allowed: readonly string[],
input: string,
): Promise<readonly string[]> {
const site = previewSite(input);
if (site === null) throw new Error(`${input} is not a site a preview can reach`);
const sites = [...new Set([...allowed, site])];
if (sites.length > MAX_PREVIEW_SITES) throw new Error(`A preview can reach at most ${MAX_PREVIEW_SITES} sites`);
await preview.setSiteAccess({ kind: "sites", sites });
frame.src = preview.url.href;
return sites;
}
// Offers each other site the preview's pages tried to reach, until `signal` aborts.
export function offerBlockedSites(
preview: PreviewHandle,
offer: (site: string) => void,
signal: AbortSignal,
): Promise<void> {
return preview.watchBlockedSites((blocked) => offer(blocked.site), { signal });
}
  • With siteAccess, exposePort resolves once the access applied. When it cannot apply, exposePort rejects as setSiteAccess does and releases that exposure.
  • setSiteAccess changes the access for pages loaded after it resolves. A page keeps the policy it loaded with, so reload the preview’s iframe once the change resolved, as allowSite does. A page open in another tab keeps its old policy until it reloads.
  • Exposures of one port share a session and its access, so the last change wins. { kind: "any" } allows every https and wss site, and { kind: "none" } takes every site back.
  • Keep the user’s choices in your app, for example per workspace, not in the project’s files, and pass them again when you expose the port on a later visit.
  • The preview’s Service Worker keeps a session’s access in memory only. When the browser restarts that worker, the hidden frame that keeps the preview connected gives the access back; a page loaded before then has the default policy until it reloads.

With your own preview origin, use preview files from SDK 0.0.23 or later. Update the files before or with the SDK. Newer preview files accept older SDKs. Against older files, any access other than { kind: "none" } fails after 10 seconds with FEATURE_NOT_AVAILABLE and detail.reason: "preview-host-outdated". { kind: "none" } on a session that never had other access sends nothing and works with every preview host.

preview.watchBlockedSites(listener, { signal }) calls listener once for each other site that a page of this preview reports its policy blocked, with a BlockedPreviewSite: the canonical site, and the directive that blocked it (connect, script, style, image, font, media or frame). Show each site once, with an Allow button that calls allowSite.

  • A report comes from the page, which runs the guest’s code. It is a hint to show the user, never a grant: only setSiteAccess grants. Never allow a site only because a page reported it.
  • One watch delivers at most 64 sites, and one page reports at most 32. A watch hears only previews framed by your page, not a preview open in a tab of its own.
  • The watch resolves when signal aborts, its handle closes or the VM’s disposal begins, and rejects with the listener’s error if the listener throws.

setSiteAccess, and exposePort with siteAccess, reject with:

Error Cause
INVALID_ARGUMENT The access is invalid: an unknown kind or key, a site previewSite refuses, or more than 64 sites. exposePort also refuses null options, options that are not an object, and keys other than signal and siteAccess.
ABORTED The handle was closed, your signal aborted, or the session ended before the change applied (detail.reason: "retired" when the preview origin reported that).
PROTOCOL_ERROR The VM is being disposed or was, or the preview’s Service Worker already holds this or a newer change (detail.reason: "stale").
RELAY_ERROR, detail.reason: "no-worker" No preview Service Worker took the change.
RELAY_ERROR, detail.reason: "no-answer" The preview origin answered an earlier change of this session, but not this one within 10 seconds.
FEATURE_NOT_AVAILABLE, detail.reason: "preview-host-outdated" The preview host did not answer within 10 seconds and has answered no change of this session before, because its files predate site access. Update them; see Host the preview files.

A change that failed with RELAY_ERROR, with FEATURE_NOT_AVAILABLE, or with ABORTED because its signal aborted may still take effect later, when the preview’s hidden frame reconnects the session’s Service Worker and sends the last access again. Call setSiteAccess again to settle the access; the later change wins.

watchBlockedSites rejects at once with INVALID_ARGUMENT without a listener function or without exactly an AbortSignal in its options, with ABORTED after the handle was closed, and with PROTOCOL_ERROR once the VM’s disposal began.

Some ways a page can reach another site are outside the page’s policy. Examples are navigation (links, form submissions and window.open; the policy has no form-action directive), WebRTC and DNS prefetch hints. This list is not complete.

Requests that the guest’s own server makes, such as a Next.js route handler or a Vite proxy, are not page requests. They leave the VM through its network, so they need guest internet access through vm.network and a relay, which site access does not turn on. See Networking.

The preview origin serves a few static files from the SDK package. Requests to the guest app itself are answered inside the browser and never reach this server.

  • Serve index.html, bootstrap.js, sw.js, websocket.js and location.js from node_modules/@oxvm/sdk/assets/preview/ under /__oxidevm/, and answer /__oxidevm/ itself with index.html. Serve the HTML as text/html and the scripts as JavaScript.
  • Send the headers from headers.json in the same folder on every response. Among them, Service-Worker-Allowed: / lets /__oxidevm/sw.js control the whole origin, and Cross-Origin-Embedder-Policy: require-corp with Cross-Origin-Resource-Policy: cross-origin let your isolated page embed it.
  • Return 404 for every other path, including a missing transport file. Do not add a fallback page.
  • For per-session, every host below the preview host must serve the same files: wildcard DNS for *.preview.example.com and a TLS certificate that covers it.
  • Copy the files again when you upgrade the SDK. They form one transport with the SDK version in your app.

If your app sends a Content Security Policy, allow the preview origin in frame-src: https://*.tabvm.dev for the frame’s previews, or https://*.preview.example.com for per-session previews on your own origin. See Deploying.

Chromium-based browsers and Firefox resolve localhost and every name below it, such as <session>.preview.localhost, to your own computer, so per-session previews work locally without DNS setup. Save this script in your project root. It serves the preview files on http://preview.localhost:4178 and on every session host below it:

serve-preview.ts
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
const directory = new URL("./node_modules/@oxvm/sdk/assets/preview/", import.meta.url);
const headers: Record<string, string> = JSON.parse(await readFile(new URL("headers.json", directory), "utf8"));
const files = new Map([
["/__oxidevm/", "index.html"],
["/__oxidevm/index.html", "index.html"],
["/__oxidevm/bootstrap.js", "bootstrap.js"],
["/__oxidevm/sw.js", "sw.js"],
["/__oxidevm/websocket.js", "websocket.js"],
["/__oxidevm/location.js", "location.js"],
]);
createServer((request, response) => {
const name = files.get(new URL(request.url ?? "/", "http://localhost").pathname);
if (name === undefined) {
response.writeHead(404, headers).end();
return;
}
const type = name.endsWith(".html") ? "text/html; charset=utf-8" : "text/javascript; charset=utf-8";
readFile(new URL(name, directory)).then(
(body) => response.writeHead(200, { ...headers, "Content-Type": type }).end(body),
() => response.writeHead(500, headers).end(),
);
}).listen(4178, "127.0.0.1");
Terminal window
node serve-preview.ts

Create the VM with preview: { origin: "http://preview.localhost:4178", isolation: "per-session" }. Then check the preview origin from your app’s development URL:

Terminal window
npx oxvm doctor http://localhost:5173/ --preview-origin http://preview.localhost:4178

The preview-origin check loads the preview page in a frame of your app and passes once its Service Worker registers and asks for a connection. Pass the origin exactly, without a trailing slash.

Error Cause
FEATURE_NOT_AVAILABLE, detail.reason: "not-configured" The VM was created without preview, and not in the frame on https://run.oxvm.dev.
INVALID_ARGUMENT The port is not a whole number from 1 to 65535. createVM also rejects a preview origin with a path or query, HTTP on a host other than the loopback names above, and isolation: "shared" without developmentOnly: true. exposePort rejects a per-session origin whose host is an IP address.
ABORTED Your signal aborted before the listener and the preview were ready.
PERMISSION_DENIED, detail.reason: "service-worker-blocked" The browser refused the preview origin’s Service Worker. Some privacy settings block Service Workers in cross-site frames.
RELAY_ERROR, detail.reason: "service-worker-failed" The preview origin’s Service Worker failed to start. Check the files and headers above.
RELAY_ERROR without detail.reason The preview origin did not finish its startup handshake in time. Check that /__oxidevm/ answers with index.html and the headers from headers.json.

With siteAccess, exposePort can also fail with the site access errors.

See Errors for all codes and VM for the full method signatures.