vkma.devRU

Node API: createTunnel

On this page

createTunnel starts a tunnel from code: from a script, from a server on Express, from a build task. It does what the CLI does, but a program drives it.

Creating a tunnel

// tunnel.mts
import { createTunnel } from "@vkma.dev/tunnel";

const tunnel = await createTunnel({ port: 5173 });
console.log(tunnel.primaryUrl); // https://<id>.opentunnel.xyz

for await (const event of tunnel.events) {
    if (event.type === "reconnecting") console.warn("the tunnel is reconnecting");
    // the loop ends when the tunnel stops
}

await tunnel.closed; // resolves after close(), rejects on a fatal error

createTunnel(options) returns a promise. It resolves once the tunnel is up. tunnel.close() closes the tunnel.

Options

options takes the fields of the config (provider, port, host, profile and the provider’s section) and, besides them:

Option Meaning
signal an AbortSignal, aborting it stops the tunnel
onEvent a function that receives every tunnel event
onProgress a function that receives the stage of the connection
onWarning a function that receives warnings
keepAlive the periodic request against an idle connection, true by default
hostRewrite the proxy that rewrites the Host header, on by default
dataDir the directory that stores identities
cwd the working directory for config discovery, the default profile name and a relative cloudflared.binary
pid the process id written into the profile record; it names the rival process in a route-conflict hint. process.pid by default

The handle’s hostname, urls and primaryUrl follow the provider.

Events

Events are read from tunnel.events or through onEvent. The main ones:

Event When
connecting the package is connecting, attempt counts the tries
connected the tunnel is up, routes lists its routes
reconnecting the connection was lost, the package reconnects after delayMs
route-conflict the service still holds the route for the previous session, the package takes it over
url-changed the URL changed under the same tunnel handle
stopped the tunnel stopped; error is set when an error was the cause

Some events, route-conflict for one, reach onEvent before the createTunnel promise resolves. The handler has to work without the tunnel handle.

Next

vkma.dev
RU
Esc