# Node.js

Source: https://tiltas.openpanel.sh/docs/sdks/node

> npm install tiltas puts one Node.js program on your Network, with listen, fetch, dial and whois.

The Node.js package wraps [libtiltas](/docs/sdks/c) with [koffi](https://koffi.dev), so nothing is compiled when you
install it. The library comes in one small package per platform, which npm picks for you.

## Install

```sh
npm install tiltas
```

Node.js 20 or newer, on Linux x64 and arm64 (glibc 2.34 or newer), macOS 12 or newer (Apple silicon and Intel) and
Windows x64. The package is ESM and ships TypeScript types.

<Component type="warn" title="Beta: not published yet">
Until `tiltas` is on npm, pack it from a copy of the Tiltas repository (Go 1.27.4 and a C compiler), then install
the two packages for your platform:

```sh
sdk/c/build.sh
sdk/node/build.sh
npm install ./sdk/node/dist/tiltas-0.1.0.tgz ./sdk/node/dist/tiltas-"$(node -p 'process.platform + "-" + process.arch')"-0.1.0.tgz
```
</Component>

## Use

```js
import { Server } from 'tiltas';

const tiltas = await new Server({ name: 'billing-api' }).up(); // the Join key comes from TILTAS_JOIN_KEY
const res = await tiltas.fetch('http://ledger/'); // the Service named ledger
console.log(await res.text());
await tiltas.close();
```

The complete server and client are in the [quickstart](/docs/sdks/quickstart).

## API

### class Server

```js
new Server({ name, panel, joinKeyFile, persistent = false, dir, verbose = false })
```

| Option | Default |
|---|---|
| `name` | `TILTAS_NAME`, else the host name. The Panel makes it unique. |
| `panel` | `TILTAS_PANEL`, else `https://tiltas.openpanel.sh`. |
| `joinKeyFile` | `TILTAS_JOIN_KEY`, else the file in `TILTAS_JOIN_KEY_FILE`. |
| `persistent` | `false`: an ephemeral Device that leaves on `close()`. `true` keeps it across restarts; needs `dir`. |
| `dir` | The state directory of a persistent Server, mode 0700. |
| `verbose` | `false`. `true` writes the network engine's logs to stderr, secrets removed. |

| Method | What it does |
|---|---|
| `await up({ timeout = 60000 })` | Joins on the first start and connects; resolves with the Server once it is a Device. |
| `await close()` | Disconnects. An ephemeral Device leaves the Network. `await using` calls it where your Node.js supports it. |
| `await listen(port, app)` | Serves on the Network's `port` with an Express app, a `(req, res)` listener, or a `net.Server` you made; resolves with the server. |
| `await fetch(url, init)` | `fetch()` over the Network: `http://` and `https://`; bodies are strings, Buffers, Uint8Arrays or URLSearchParams. |
| `await dial(host, port, { timeout = 30000 })` | A `net.Socket` connected over the Network to a Device or Service by name (short or full) or address. |
| `await whois(req)` | The `Identity` behind a request, a socket, or an address of the Network. |
| `deviceId`, `domain`, `addresses` | This Device's id (`dev_…`), the Network's domain, and this Device's addresses. |

`Identity` has `device_id` (for Servers), `name`, `dns_name`, `kind` (`'server'` or `'personal'`), `addresses`,
`tags`, and for Personal devices `member_email` and `member_name`. Errors are `TiltasError`, and never contain a key.

## How listen works

`listen(80, app)` starts your server on a free port of `127.0.0.1` and has the library forward every connection to the
Network's port 80 to it. `whois(req)` maps the request's peer back to the Device that called. Other programs on the
same computer can also connect to that loopback port; `whois` rejects them, so check every caller with it, as the
examples do.

## Express

```js title="examples/node/express.mjs"
// An Express app served only on a Tiltas Network.
//
//   npm install express
//   TILTAS_JOIN_KEY=qlj_… TILTAS_NAME=hello-server node express.mjs
import express from 'express';
import { Server } from 'tiltas';

const tiltas = await new Server().up();

const app = express();
app.get('/', async (req, res) => {
  const who = await tiltas.whois(req).catch(() => null);
  if (!who) return res.status(403).send('unknown caller\n');
  res.type('text').send(`hello ${who.name}\n`);
});

const http = await tiltas.listen(80, app);
console.log(`serving on the Network only, as Device ${tiltas.deviceId}`);

for (const signal of ['SIGINT', 'SIGTERM']) {
  process.once(signal, async () => {
    http.close();
    await tiltas.close(); // an ephemeral Device leaves the Network
    process.exit(0);
  });
}
```

## Ephemeral or persistent

An ephemeral Server (the default) joins on every start and leaves on `close()`. Node.js does not run cleanup when it is
killed, so handle `SIGTERM` and `SIGINT` as the examples do; `docker stop` sends `SIGTERM`.

```js
const tiltas = await new Server({ name: 'nas-backup', persistent: true, dir: '/var/lib/nas-backup/tiltas' }).up();
```

A persistent Server joins once and reuses its Device from `dir` on later starts.
