> ## Documentation Index
> Fetch the complete documentation index at: https://docs.manalens.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Node.js SDK

> Send events from a backend, a game server or the Electron main process with batching and retries.

The Node.js SDK sends `track` and `identify` events to `POST /v0/events`. It batches events, sends them on a timer, and retries failed requests. It has two modes:

| Mode | Where | Key | Events |
| - | - | - | - |
| `server` (default) | Your backend: webhooks, background jobs, purchase checks, a dedicated game server | **Secret key** (`ua_sk_...`) | `channel: 'server'`, up to 100 in a batch |
| `app` | The Electron main process, or a process on the player's machine | **Publishable key** (`ua_pk_...`) | `channel: 'app'` with `context.app`, up to 50 in a batch |

In app mode the SDK sends the Publishable key in the `x-publishable-key` header. Older publishable keys that start with `ua_` (without `pk_`) still work in app mode. API keys (`ua_api_`, or older `ua_mcp_`) read data and cannot send events: the SDK refuses them in both modes. The SDK also checks the length and checksum of a `ua_pk_` or `ua_sk_` key, so a typo fails at startup.

> [!WARNING]
>
> Never put the secret key (`ua_sk_`) in a game build, a web page or an Electron app. Anyone who has the build can read it. Use `app` mode with the Publishable key there. The SDK refuses a secret key in app mode and a Publishable key in server mode.

## Install

> [!NOTE]
>
> **Early access.** The Node.js package is available on request during early access. The repository is private until launch, so the steps below work only after you have access. To ask for it, use the Contact page of the ManaLens website (`/contact`) and tell us your engine and platform. The source will be published at launch.

```bash theme={null}
npm install @untitled-analytics/node
```

> [!NOTE]
>
> The package is not on npm yet. Until it is, install the package archive that you received, or build it from `sdks/node` in the repository when you have access (`pnpm --filter @untitled-analytics/node build`). It needs Node.js 20.3 or newer and has no dependencies.

## Server mode

Create the secret key in your project settings first: see [Create the secret key](https://docs.manalens.dev/sdks/server.md#create-the-secret-key). Keep it in an environment variable on your backend.

```ts theme={null}
import { UntitledAnalytics } from '@untitled-analytics/node';

const analytics = new UntitledAnalytics(process.env.UA_SECRET_KEY!, {
  endpoint: 'https://YOUR_COLLECTOR_ENDPOINT',
});

analytics.track({
  event: 'purchase_confirmed',
  userId: 'player_123',
  properties: { sku: 'dlc_harbor', price: 4.99 },
});

analytics.identify({
  userId: 'player_123',
  traits: { plan: 'supporter', email: 'ada@example.com' },
});
```

Each server event needs `userId`, `anonymousId` (a UUID, for example the one the web or game SDK made), or both. With both, the event links that device to the user. See [Join server events to players](https://docs.manalens.dev/sdks/server.md#join-server-events-to-players).

### Send the player's IP and user agent

A backend's own IP and user agent are not the player's. When an event comes from a player's request, pass theirs in `context`. The collector uses the IP only to look up the country, in memory, and never stores it. It uses the user agent for device, OS and browser.

```ts Express theme={null}
import express from 'express';
import { UntitledAnalytics } from '@untitled-analytics/node';

const analytics = new UntitledAnalytics(process.env.UA_SECRET_KEY!, { endpoint: 'https://YOUR_COLLECTOR_ENDPOINT' });
const app = express();
app.set('trust proxy', true); // so req.ip is the client IP behind a load balancer

app.post('/api/checkout', express.json(), (req, res) => {
  analytics.track({
    event: 'checkout_started',
    userId: req.body.userId,
    anonymousId: req.body.anonymousId, // optional: from analytics.getAnonymousId() in the browser
    sessionId: req.body.sessionId,     // optional: from analytics.getSessionId() in the browser
    properties: { items: req.body.items.length },
    context: { ip: req.ip, userAgent: req.get('user-agent') },
  });
  res.sendStatus(204);
});

const server = app.listen(3000);

process.on('SIGTERM', async () => {
  server.close();
  await analytics.shutdown();
  process.exit(0);
});
```

**Send the client's session ID.** A server event with the `sessionId` (and the `anonymousId`) of the client is in the visitor's [session](https://docs.manalens.dev/data/metrics.md#sessions), also when your backend sends it late. A server event without a `sessionId` is valid: it joins the session of the same `anonymousId` that is active at that time, if there is one. `sessionId` is an option of each `track()` and `identify()` call. See [server events](https://docs.manalens.dev/sdks/server.md#session-id-of-the-client).

Other `context` fields for server events: `country` (two letters), `locale`, `device` (`desktop`, `mobile`, `tablet`), `os`, `browser`, `page` (`path`, `title`, `url`) and `app` (see below). A dedicated game server can set the `app` option once, and every event gets `context.app`. When `context.app` has a native platform, it sets the OS and device; the browser still comes from the user agent.

The SDK adds `context.library_name` (`@untitled-analytics/node`) and `context.library_version` to every event in both modes.

## App mode (Electron main process)

In Electron, use the [web SDK](https://docs.manalens.dev/sdks/web.md) in the renderer. Use this SDK in the main process only for events the renderer cannot see, such as app start, updates or crashes of a window.

```ts main.ts theme={null}
import { app as electronApp } from 'electron';
import { UntitledAnalytics } from '@untitled-analytics/node';

const analytics = new UntitledAnalytics('ua_pk_your_publishable_key', {
  endpoint: 'https://YOUR_COLLECTOR_ENDPOINT',
  mode: 'app',
  app: {
    platform: process.platform === 'darwin' ? 'macos' : process.platform === 'win32' ? 'windows' : 'linux',
    storefront: 'steam',
    app_version: electronApp.getVersion(),
    engine: 'other',
  },
  anonymousId: loadOrCreatePlayerId(), // a UUID you keep in the user data folder
});

electronApp.whenReady().then(() => {
  analytics.track({ event: 'app_started' });
});

electronApp.on('will-quit', event => {
  event.preventDefault();
  analytics.track({ event: 'app_quit' });
  analytics.shutdown(2000).finally(() => electronApp.exit(0));
});
```

App events follow the [app event rules](https://docs.manalens.dev/sdks/app-events.md):

* `app.platform` is required: `windows`, `macos`, `linux`, `web`, `android`, `ios` or `other`. Optional: `storefront` (`steam`, `itch`, `epic`, `gog`, `app_store`, `play`, `other`), `app_version` (up to 32 characters), `build` (up to 64), `engine` (`godot`, `unity`, `unreal`, `other`).
* Every event has an `anonymous_id`. The SDK uses the `anonymousId` option, or a new UUID for each process. Keep one UUID per player on disk and pass it, or each launch counts as a new player. Use the same ID as the renderer's web SDK to join the two.
* The SDK makes a `session_id`. It starts a new session after 30 minutes without events, and when the session is 24 hours old. `getSessionId()` returns the session ID of the next event. Pass the `sessionId` option to set your own; the SDK then never changes it, and you must keep a session under 24 hours.
* Every app event needs a `session_id` that is not the `anonymous_id`. The SDK drops an event that breaks this (the collector refuses it with `SESSION_ID_REQUIRED` or `SESSION_ID_IS_ANONYMOUS_ID`).
* The collector refuses app events more than 7 days old, so the SDK drops them.

## Options

| Option | Default | Description |
| - | - | - |
| `endpoint` | required | The collector URL, without `/v0/events`. |
| `mode` | `'server'` | `'server'` or `'app'`. |
| `app` | none | `context.app` for every event. Required in app mode. |
| `anonymousId` | new UUID | App mode: the player's anonymous ID. |
| `sessionId` | new UUID | App mode: a fixed session ID. |
| `locale` | none | App mode: `context.locale` for every event. |
| `flushAt` | `20` | Send when this many events wait. At most 100 (server) or 50 (app). |
| `flushInterval` | `10000` | Send at least this often, in ms (1000 to 300000). |
| `maxQueueSize` | `500000` | Send when the queued JSON is larger than this, in bytes. |
| `maxQueueLength` | `10000` | Drop new events when this many wait. |
| `retryCount` | `3` | Retries after the first attempt. |
| `retryDelay` | `1000` | First retry wait in ms. It doubles on each retry, with jitter, up to 60 seconds. |
| `timeout` | `10000` | Request timeout in ms. |
| `debug` | `false` | Log dropped events and failed requests. |
| `logger` | `console.warn` | Where debug messages go. |

## Track and identify

```ts theme={null}
analytics.track({
  event: 'match_won',          // 1 to 128 characters
  userId: 'player_123',        // 1 to 255 characters
  anonymousId: '3f0c5c1e-8a8e-4c1b-9d7e-2b1f4e6a9c10',
  sessionId: 'match-8812',
  properties: { map: 'harbor', kills: 7, ranked: true },
  timestamp: new Date(),       // default: now
  messageId: crypto.randomUUID(), // default: a new UUID
});

analytics.identify({ userId: 'player_123', traits: { name: 'Ada' } });
```

Property and trait values are strings (up to 1024 characters), finite numbers, booleans or `null`. Trait names have 1 to 100 characters.

`track()` and `identify()` never throw for a bad event. The SDK drops the event and, with `debug: true`, logs why. The collector refuses a whole batch when one event is bad, so the SDK checks each event first with the same rules.

## Delivery and retries

* Every event has a `message_id`. A retry sends the same batch with the same IDs, so reports count each event once.
* The SDK retries network errors, timeouts, `5xx`, `408` and `429`. It waits for the `Retry-After` header when the collector sends one, else 1, 2, 4 seconds with jitter.
* Other `4xx` responses (a wrong key, an invalid batch) are not retried. The SDK drops the batch and, in debug mode, logs the status and the response of the collector, which has the reason code of each refused event (for example `SESSION_ID_REQUIRED`).

## Flush and shut down

`flush()` sends every queued event now. `shutdown(timeoutMs = 5000)` sends every queued event for at most `timeoutMs`, then stops the timer. Calls after `shutdown()` are dropped.

The SDK adds no process exit hooks. Call `shutdown()` yourself before the process exits:

```ts theme={null}
// A script or a job
await analytics.shutdown();

// A server
process.on('SIGTERM', async () => {
  await analytics.shutdown();
  process.exit(0);
});

// A serverless function: flush before you return
await analytics.flush();
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.