> Markdown version of https://tuna.am/en/docs/guides/install/sdk/node/. Documentation index: [llms.txt](https://tuna.am/en/llms.txt), full text in one file: [llms-full.txt](https://tuna.am/en/llms-full.txt). Any page is available as Markdown: append `.md` to its URL without the trailing slash.

# 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](https://www.npmjs.com/package/ssh2). TypeScript types are included.

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

The package is [@tuna-am/sdk](https://www.npmjs.com/package/@tuna-am/sdk) on npm, source code is on [GitHub](https://github.com/yuccastream/tuna-sdk-nodejs).

## Installation

```shell
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:

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

```

## Authentication

Create an [API key](https://my.tuna.am/api_keys?lang=en) 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:

```js
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`:

```js
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

| Field                     | Meaning                                                                                                                                                          |
| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `protocol`                | `http` or `tcp`, required                                                                                                                                        |
| `apiKey`                  | API key, defaults to `$TUNA_API_KEY`                                                                                                                             |
| `subdomain`, `domain`     | HTTP: [reserved subdomain](https://tuna.am/en/docs/tunnels/http.md#reserved-subdomain) or [custom domain](https://tuna.am/en/docs/tunnels/http.md#custom-domain) |
| `port`                    | TCP: [reserved port](https://tuna.am/en/docs/tunnels/ports.md) or its alias                                                                                      |
| `proxyProtocol`           | TCP: [PROXY protocol](https://tuna.am/en/docs/tunnels/tcp.md#proxy-protocol) version, `1` or `2`                                                                 |
| `cidrAllow`, `cidrDeny`   | TCP: client subnets allowed or rejected by the Tuna node                                                                                                         |
| `signal`                  | `AbortSignal`: aborting it closes the tunnel and all accepted connections                                                                                        |
| `onEvent`                 | callback for tunnel events                                                                                                                                       |
| `connectTimeout`          | limit on the wait for the first connection, in milliseconds; zero means no limit                                                                                 |
| `serverURL`, `clientName` | API 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`.
