# The ravensight package for browser games and Node

One zero-dependency client for browser games and Node 18 or newer, shipped as both ESM and CommonJS. It owns sessions, batching, the offline queue, rate limits and the server-side kill switch, so your game code calls `init()` once and `track()` from then on.

Code samples scroll horizontally when needed. Focus a sample and use the arrow keys, or swipe to read a long line.

## Install

```
npm install ravensight
```

There is no build step for consumers. It suits Phaser, PixiJS, three.js, Excalibur and hand-written canvas games. Godot HTML5 exports use the [Godot SDK](https://ravensight.io/docs/godot-sdk/) instead.

## Quickstart

```
import Ravensight from 'ravensight';

const rs = new Ravensight({
  ingestKey: 'gt_live_your_publishable_key',
  gameVersion: '1.4.0',
});

// Reads the server kill switch and opens a session. Call it once at startup.
await rs.init();

rs.track('level_completed', { level: 3, deaths: 2, seconds: 91 });

// Optional: player feedback from an in-game form.
await rs.submitFeedback('The boss fight is too long', 'suggestion', 4);
```

In a browser the SDK sends `game_started` and `game_exited` for you; pass `autoEvents: false` to send your own.

In CommonJS, use `const Ravensight = require('ravensight');`. Events go out in batches on a timer and when the page is hidden, so you never have to call `flush()` yourself. A Node process should `await rs.dispose()` before it exits, so the last batch goes out.

## Options

Pass these to `new Ravensight(options)`.

| Option | Default | Notes |
| --- | --- | --- |
| `ingestKey` | required | Your publishable `gt_live_...` key. Safe to ship in a client build. |
| `apiUrl` | `https://api.ravensight.io/api/v1` | `/api/v1` is appended if you leave it off. |
| `gameVersion` | `'1.0.0'` | Reported with the session. |
| `platform` | auto | `'web'` in a browser, `node-` in Node. |
| `autoFlushMs` | `15000` | Flush interval. `0` flushes only on demand. |
| `maxQueueSize` | `500` | Offline queue cap. The oldest events are dropped first. |
| `persistQueue` | `true` | Keep the queue across a reload, a crash or a lost network: one `localStorage` entry per ingest key in a browser, one file per key in Node. `false` keeps it in memory only. |
| `queueDir` | `~/.ravensight` | Node only: the folder the queue file is written to. |
| `maxSessions` | `64` | Sessions cached at once, one per device id. The least recently used is dropped first, never the current id, and reopens on that device's next event. |
| `storage` | auto | Anything with `getItem` and `setItem`. Holds the device id. |
| `deviceId` | auto | Overrides the generated device id. |
| `enabled` | `true` | Pass `false` to start opted out. |
| `autoEvents` | `true` | Send `game_started` and `game_exited` for you, in a browser only. A client that starts with `enabled: false` sends neither. |
| `fetch` | global | Inject a custom fetch. |
| `debug` | `false` | Logs SDK activity to the console, and warns about reserved `rs_` keys. |
| `performance` | `false` | Sample the frame rate and send one `health` event per session on page hide. Browser only. See [typed events](https://ravensight.io/docs/dashboard/#typed-events). |

## Methods

| Method | Description |
| --- | --- |
| `await rs.init()` | Reads the kill switch from `GET /api/v1/settings`, then opens a session. Resolves with `{ trackingEnabled, sessionReady, reason }` and never throws on a network failure. `reason` is `null` when the session is ready, otherwise one of the values in the table below. If tracking is off for your game, nothing further is sent. |
| `rs.track(event, data?, { deviceId }?)` | Queues an event and records its timestamp at the moment of the call. Safe before `init()`. Returns `false` when tracking is off. `deviceId` sends this one event as another device, under that id's own session, so one Node client can serve many players. It must be a non-empty string or `track()` throws a `TypeError`. |
| `rs.trackPurchase({ amount, currency, itemType, itemId, cart?, transactionId?, data?, event? })` | A typed purchase. `amount` is whole minor units, an integer or a digit string, and the currency is upper-cased. Event name `purchase`. Returns what `track()` returns. |
| `rs.trackResource({ flow, resource, amount, itemType?, itemId?, data?, event? })` | A resource gained (`'source'`) or spent (`'sink'`). Event name `resource_source` or `resource_sink`. |
| `rs.trackProgression({ status, p1, p2?, p3?, score?, data?, event? })` | A progression step: `'start'`, `'complete'` or `'fail'`. Event name `progression_start`, `progression_complete` or `progression_fail`. |
| `rs.trackError({ severity, message, stack?, data?, event? })` | An error. `severity` is `'debug'`, `'info'`, `'warning'`, `'error'` or `'critical'`; the message is cut to 200 characters and the stack to 2000. Event name `error`. |
| `rs.trackAd(network, format, result, { placement, revenueMicros, currency }?)` | An [`ad` typed event](https://ravensight.io/docs/dashboard/#typed-events). Revenue is a digit string of whole micros, sent only with `shown` and always with a currency. Returns `false` and sends nothing for a value the server would flag. |
| `rs.trackAdRevenue(network, format, placement, revenueMicros, currency)` | A paid impression. `microsFromDecimalString('0.0015')` and `microsFromRevenue(0.0015)` both give `"1500"` without multiplying a float; `adFormatFrom` maps a mediation format name. |
| `rs.setAttribution({ source, network, campaign, adset, creative, touchTime })` | One `attribution` event per device id; every later call returns `false`, across restarts. In a browser the SDK sends one for you on the first load of a new device id when the landing URL has a UTM parameter. |
| `await rs.flush()` | Sends what is queued now and resolves with `{ sent, queued }`. Concurrent calls are safe. It cuts a backoff wait short, never a server `Retry-After`. |
| `await rs.submitFeedback(message, category?, rating?)` | Sends player feedback. `category` is one of the values below, exported as `FEEDBACK_CATEGORIES`. `rating` is an integer from 1 to 5. Leave either out with `undefined`, `null` or an empty string. Anything else is invalid and throws before any request is made, with code `invalid_category` or `invalid_rating`; an empty message throws `empty_message`. |
| `rs.setEnabled(bool)` | Local opt in and opt out. `false` stops sending and clears anything queued. The SDK does not store the choice: keep it in your own settings and call this before the first event on every launch. |
| `await rs.setDeviceId(id)` | Changes the device id, for example after a player signs in on a shared machine. The switch is immediate: nothing is flushed or waited for. The new id is stored and its session opens on the next flush. Events already queued keep the id they were tracked under and go out under that id's own session, so nothing is ever sent under the wrong id. Resolves with `{ previousId, queuedUnderPreviousId }`. Setting the current id again changes nothing. |
| `await rs.resetDeviceId()` | The same with a fresh random id, which it resolves with. Use it for a reset analytics id button. |
| `rs.joinSession(token, { deviceId }?)` | Joins a session opened elsewhere, normally the browser's `rs.sessionToken`, so the next session opened for `deviceId` (default: the client's own id) shares its analytics session. Any session already cached for that id is dropped, and the token is used once. See Joining the browser's session below. |
| `await rs.dispose({ flush = true, timeoutMs = 2000 })` | Shuts the client down and resolves with `{ sent, dropped, kept }`. The timer and page listeners stop at once and `track()` returns `false` from that moment. The queue is then flushed by default, bounded by `timeoutMs`, even if `init()` was never called; in a browser, whatever is still queued after that goes out in one last keepalive or beacon request. With the persisted queue on, anything left stays stored for the next launch and is counted as `kept`; with `persistQueue: false` it is counted as dropped. Events in a request that timed out are counted as dropped, even if it later lands. Pass `{ flush: false }` to discard the queue. After dispose, `setDeviceId()` and `resetDeviceId()` reject with code `disposed`. |
| `await rs.fetchSuggestions()` | Experimental. The AI-generated design suggestions for your game, empty until a weekly digest has run. The shape may change, so do not build game logic on it. |

## Why a session is not ready

| Reason | Meaning |
| --- | --- |
| `invalid_key` | The key was refused (`401`, or a `403` other than the kill switch) by the settings check or `POST /session`. The run ends, because a retry cannot fix a revoked, rotated or wrong key: the queue is cleared, the timer stops, `track()` returns `false`, and `init()` and `flush()` do not try the key again. It warns once on the console. |
| `tracking_disabled` | Tracking is switched off for this game. Nothing is sent. |
| `disabled` | The client is opted out (`enabled: false` or `setEnabled(false)`). `init()` makes no network call. Call `setEnabled(true)` and then `init()` to start. |
| `offline` | No answer from the network. Retried with backoff. |
| `rate_limited` | `429`. Retried after `Retry-After`. |
| `session_failed` | Any other answer. Retried with backoff. |

`rs.stats.lastError` holds the last failed request as `{ code, status, at }`, from the session, settings or batch requests, or `null`. Read it when events are not arriving. It can show `session_expired` after a routine `401` the SDK has already recovered from, so read it together with whether the queue is draining.

## Feedback categories

| Category | Use it for |
| --- | --- |
| `bug` | Something is broken. |
| `suggestion` | An idea or a change the player wants. |
| `complaint` | Something the player dislikes. |
| `praise` | Something the player enjoyed. |
| `playtest` | Notes from a playtest session. |
| `other` | Anything else. |

## How delivery works

- **Batches of 50.** The server's limit per request. A flush keeps sending batches until the queue drains.
- **Persisted queue.** On by default. In a browser the queue lives in one `localStorage` entry per ingest key; in Node it is one file per key under `~/.ravensight` (or `queueDir`), written through a temporary file and a rename. It is read back once at start. At most 500 events are kept, the oldest go first, and anything older than 89 days is dropped at start. Two tabs of the same game share one entry, so the last tab to write wins.
- **Removed only once delivered.** An event leaves the queue only after a `2xx`, or a `400` that names it by `index`. Each event remembers the `origin` of the session it was tracked under, so an event sent on a later launch is stored under the session, build and platform it happened in. Timestamps are unix milliseconds of the moment it was tracked.
- **Errors behind gameplay.** Gameplay events go ahead of queued automatic error captures. In a full queue an incoming capture evicts the oldest capture, or is dropped, and never evicts gameplay. `rs_trail` is never written to storage, and `resetDeviceId()` and an opt-out delete persisted captures.
- **One device per batch.** Each request carries the leading run of queued events that share one device id, under that id's own session, then the next run.
- **Answers.** A `400` with `index` drops that event and resends the rest; `400 batch_too_large` halves the batch; any other `400` drops the request's events. A `401` opens one new session for that device and resends; a second `401` in a row waits for the backoff. A `403` on a batch keeps the events and stops sending until the next launch. `413` splits the batch, `415` resends once uncompressed, and `429`, or `503` with `Retry-After`, waits exactly the server's time.
- **Backoff.** From 10 seconds, doubling to 5 minutes, each wait multiplied by a random factor between 0.5 and 1. `flush()` cuts a backoff short; nothing cuts a `Retry-After` short.
- **Compression and signing.** A request body of 1,024 bytes or more is sent gzip compressed; page-hide sends never are. When `POST /session` answers with `signing` ([public keys](https://ravensight.io/docs/public-builds/)), every batch carries `X-Ravensight-Timestamp` and `X-Ravensight-Signature`, an HMAC-SHA256 over the uncompressed body. The secret is kept in memory only; a beacon carries a signed body envelope instead.
- **Page hide.** When the page goes hidden the SDK sends one last batch, preferring `fetch` with `keepalive`. Where that is unavailable it falls back to `navigator.sendBeacon`, which cannot set headers, so the session token travels in the JSON body as `sessionToken`, never in the URL. Those events stay in the persisted queue marked unconfirmed; the next launch resends them if it comes within 23 hours, inside the server's 24 hour duplicate window.
- **No re-send while in flight.** The SDK never sends a batch again while it is still in flight, so a batch cut off by a real page unload can be lost rather than counted twice. A batch whose response is lost, from a network error or a 5xx after the server already stored it, can be sent again on the next flush, and ingest does not remove duplicates.

Session creation and tracked events are rate limited per game, not per client. See [Usage, billing and limits](https://ravensight.io/docs/limits/).

## What the dashboard reads

The dashboard gives meaning to some fields and event names. Name your events with these in mind.

- **One place per event.** `level`, `location` and `track` in the event data fold into one place, and the first non-empty one wins, in that order. The level funnel, per-level deaths and journeys only see events that have a place.
- **Event names.** A name containing `start`, `begin` or `enter` is a level start; `complet`, `finish`, `win` or `clear` is a completion; `died`, `destroyed` or `killed` is a death. These are lowercase substring matches.
- **`rs_kind` overrides the name.** Set `rs_kind` in the event data to `level_start`, `level_complete`, `death` or `none` and it is read before the name. `none` opts an event out, so `checkout_started` is not a level start. An unknown value falls through to the name match. Keys that start with `rs_` are reserved for Ravensight. The SDK exports the four values as `RS_KINDS`, and with `debug: true` it warns once per event and key about an `rs_kind` outside that list or an `rs_` key Ravensight does not read. It never throws and still sends the event. The server counts the same two mistakes on the Implementation health card.
- **Potentially stuck** is one event repeated 10 or more times at the same level in a session of fewer than 20 events. The same event at a new level each time is movement, not stuck. Events with no place are grouped together, so ten repeats of a placeless event in a short session count; send a place or accept it.

```
rs.track('boss_phase_begin', { level: 'castle', rs_kind: 'none' });
rs.track('run_over', { level: 'castle', rs_kind: 'death' });
```

The full rules, including the player flags, are in [how the built-in detections read your events](https://ravensight.io/docs/dashboard/#detection-rules).

## Node servers with many players

The server takes the device id from the session, so every device needs its own session. The SDK keeps one per device id for you. On a game server, create one client and pass each player's id as the third argument to `track()`: a pseudonymous id your game generates, never an email or account name. Node has no `localStorage`, so pass an explicit `MemoryStorage` to keep the server's own id out of any shared storage.

```
import Ravensight, { MemoryStorage } from 'ravensight';

const rs = new Ravensight({
  ingestKey: process.env.RAVENSIGHT_KEY,
  gameVersion: '1.4.0',
  platform: 'dedicated-server',
  storage: new MemoryStorage(),
});
await rs.init();

function onMatchFinished(player, match) {
  rs.track('match_finished', { mode: match.mode, seconds: match.seconds }, { deviceId: player.analyticsId });
}

// On shutdown, the last flush for every player at once.
process.on('SIGTERM', async () => {
  await rs.dispose({ timeoutMs: 5000 });
  process.exit(0);
});
```

- **One request is one device.** A flush sends the run of queued events that share the device id at the head of the queue, up to 50, then the next run. Interleaved players cost more requests than one player, but nothing is ever sent under the wrong id.
- **Sessions are cached per id**, up to `maxSessions`. Past that the least recently used is dropped and reopens on that player's next event. Raise it if more players than that are active at once.
- **Limits are per game, shared by every player** on the client: 60 session creations and 600 tracked events a minute. A burst past that gets a `429`, and the SDK holds the events and retries. See [Usage, billing and limits](https://ravensight.io/docs/limits/).
- **`dispose()` is the last flush.** Call it on shutdown. Anything it cannot send inside `timeoutMs` stays in the queue file for the next start and is counted as `kept`, or as dropped with `persistQueue: false`.

## Joining the browser's session

When the same player also runs the browser SDK, the browser can hand its session to your server, so server-side events land in the same analytics session as the player's own, under the browser's device id.

```
// Browser: send the token to your server with your own request.
await fetch('/api/link-analytics', {
  method: 'POST',
  body: JSON.stringify({ rsToken: rs.sessionToken }),
});

// Server: one call per player, before that player's next event.
rs.joinSession(body.rsToken, { deviceId: player.analyticsId });
rs.track('purchase_verified', { sku: 'gold_pack' }, { deviceId: player.analyticsId });
```

The next session opened for that id sends the token once as `joinToken`. The server answers with a session of its own that shares the browser's session id and device id, and never lives longer than the browser's. The local id is only the key the SDK caches that session under. If the server refuses the token, the SDK opens a plain session instead and records `invalid_join_token` in `stats.lastError`. Only a live session of the same game can be joined. A join from a playtest session stays synthetic, so the game server's events are marked as the playtest's too.

## Campaign links

A [campaign link](https://ravensight.io/docs/campaign-links/) that points at a web page adds `rs_link` to the address. From 0.8.0, the SDK reads it from `location.search` once, when it starts, and sends it with the first session it opens, so the Campaign links page can count the players and sessions each link brought. There is nothing to call. Later sessions do not send it, nothing is stored, the page address is left as it is, and consent applies as to everything else.

## Privacy

The SDK generates a random device id and stores it under `ravensight_device_id`. It collects no hardware identifier, advertising id or personal data, only the events you send. If you pass your own `deviceId`, as on a server, make it a pseudonymous player id your game generates, never an email or account name. The row by row answers for the App Store and Google Play forms are in [what your privacy label can say](https://ravensight.io/docs/platform-support/#privacy-label).

Source: https://ravensight.io/docs/javascript-sdk/
Last updated: 2026-11-15
