Skip to main content

Node.js

The Node.js SDK opens Tuna tunnels straight from your code: expose a local HTTP or TCP service at a public address without installing tuna.

  • Two ways in: listen hands each incoming connection to your code as a stream, forward proxies connections to a local address.
  • Survives network failures: reconnects and keeps the same public address.
  • A single dependency, ssh2. TypeScript types are included.
info

The API is not stable yet: it may change before v1.

The package is @tuna-am/sdk on npm, source code is on GitHub.

Installation​

npm install @tuna-am/sdk

Requires Node.js 18 or later. The examples below are ES modules; require('@tuna-am/sdk') works too.

If npmjs.org is unavailable, the package is available in the code.tuna.am registry:

npm install @tuna-am/sdk --registry=https://code.tuna.am/api/packages/tuna/npm/

Authentication​

Create an API key with Run tunnels enabled (the For tunnels preset) and pass it in apiKey or the TUNA_API_KEY environment variable.

Serve HTTP without a local port​

listen feeds connections from the internet straight into your http.Server, no local port needed:

import http from 'node:http';
import tuna from '@tuna-am/sdk';

const server = http.createServer((req, res) => res.end('hello\n'));
const tunnel = tuna.listen({ protocol: 'http' });
tunnel.on('connection', (stream) => server.emit('connection', stream));

console.log('public URL:', await tunnel.ready);

Subscribe to connection right away: a connection that arrives with no listener is dropped. tunnel.close() stops accepting and reconnecting, connections already accepted keep working, and tunnel.done settles once the last one closes.

Forward to a local service​

forward proxies connections from the tunnel to a local address, host:port or unix:///path/to.sock:

const controller = new AbortController();
process.once('SIGINT', () => controller.abort());

await tuna.forward({
protocol: 'tcp',
port: 'my-db',
signal: controller.signal,
onEvent: (e) => {
if (e.type === 'connected') console.log(`forwarding ${e.url} -> 127.0.0.1:5432`);
},
}, '127.0.0.1:5432');

The promise resolves after signal is aborted and rejects when the tunnel ends for good.

Options​

FieldMeaning
protocolhttp or tcp, required
apiKeyAPI key, defaults to $TUNA_API_KEY
subdomain, domainHTTP: reserved subdomain or custom domain
portTCP: reserved port or its alias
proxyProtocolTCP: PROXY protocol version, 1 or 2
cidrAllow, cidrDenyTCP: client subnets allowed or rejected by the Tuna node
signalAbortSignal: aborting it closes the tunnel and all accepted connections
onEventcallback for tunnel events
connectTimeoutlimit on the wait for the first connection, in milliseconds; zero means no limit
serverURL, clientNameAPI address and client name reported to the server

Events and errors​

onEvent and the tunnel emitter receive connected, reconnecting, reconnected, banner, session_expiring, terminated and local_error as { type, url, message, reason, error, retryIn, expiresIn } objects. Durations are in milliseconds.

Network failures and temporary server errors are retried: the pause grows from 1 to 15 seconds with random jitter, and Retry-After is respected. If the node stops responding, reconnecting arrives after 15 seconds with a KeepAliveTimeoutError. The tunnel ends with an error when retrying is pointless; check it with isPermanent:

  • ServerError: the API rejected the request — bad or revoked key, missing permission, unknown reserved name, unpaid plan;
  • TerminatedError: the server closed the tunnel — it was deleted, suspended or hit the session time limit.

Behavior worth knowing​

  • signal bounds the whole life of the tunnel, not only the first connection. To give up early when the tunnel does not come up, set connectTimeout.
  • A stream from connection counts as open until close fires. Read it to the end, as http.Server does, or tunnel.done will keep waiting for it.
  • In forward, when the visitor closes its side of a connection, the connection is closed in both directions: a response sent after that is lost.
  • The Host header and the PROXY protocol header reach your service as sent.
  • The API client is the built-in fetch. On Node.js 24 and later it honors HTTPS_PROXY when NODE_USE_ENV_PROXY=1 is set. Connections to Tuna nodes are plain SSH and do not use the proxy.
  • For a private CA, use NODE_EXTRA_CA_CERTS.