Skip to content
Documentation

SDK, CLI, and platform reference

Install and configure @eventra_dev/eventra-sdk and @eventra_dev/eventra-cli. Runtime ingest, catalog sync, and dashboard concepts in one place.

Node 18+ESM + CJSTypeScript

Runtime SDK for browser, Node, Edge, and serverless. Track events with track() - batching, retries, and delivery are handled automatically.

Install

Add the Eventra SDK to your application.

npm
npm i @eventra_dev/eventra-sdk
pnpm
pnpm add @eventra_dev/eventra-sdk
yarn
yarn add @eventra_dev/eventra-sdk

Quick start

Only apiKey is required. The SDK handles batching, retries, queueing, flushing, and runtime adaptation automatically.

TypeScript
import { Eventra } from "@eventra_dev/eventra-sdk";

const tracker = new Eventra({
  apiKey: "YOUR_PROJECT_API_KEY",
});

tracker.track("checkout.completed", {
  userId: "user_123",
});

Default endpoint: https://api.eventra.dev/api/v1/ingest/batch

Identify users

Unique users, the Users page and per-user numbers (Top users, users on Declining) need to know whose event it is. Without a user ID events still count as uses (dead, new and declining features work as before), but nothing can be counted per user. The overview shows a notice when most events of the last 7 days have none. Already pass userId to every track()? Nothing to change: it still works and can be mixed with the methods below.

Browser: call identify() once after sign-in (and when a page loads with a signed-in user), and reset() on sign-out. Every following track() gets that user.

Browser
tracker.identify(user.id);
tracker.track("export.clicked"); // sent with userId = user.id

// in your sign-out handler (not while auth is still loading)
tracker.reset();
  • The user is kept in localStorage (in memory with persistQueue: false), so the first events after a reload carry it too, and identify() and reset() reach every open tab
  • The stored user, like the pending events, belongs to your API key: another Eventra project on the same site (a third-party widget, say) never sees or sends them
  • getUserId() returns the current user. In React Native identify() works in memory. In Next.js and other SSR apps, call it in client code (an effect), not while rendering on the server

Everywhere else (Node, serverless, edge, Deno, Cloudflare Workers) one instance may serve many users at once, so identify() is ignored there with one warning. Use withUser() for each request: a light tracker over the same queue, cheap to make per request.

Server
// in a request handler (Express, Nest, a serverless function);
// req.user is set by your auth middleware
app.post("/invoices", (req: Request & { user?: { id: string } }, res) => {
  // undefined: no user
  tracker.withUser(req.user?.id).track("invoice.created", { properties: { plan: "pro" } });
  res.sendStatus(201);
});
  • Which user an event gets: the userId passed to track() first (null sends it without a user, an empty one counts as not given), then the user of withUser() (withUser(null) means no user), then the one of identify(). The user is fixed when track() is called
  • Call withUser() where you track, or keep the scope in a typed variable: the CLI finds tracker.withUser(id).track("x"), but not a scope stored on an untyped object such as req.tracker
  • The SDK warns once when none of the first 50 events has a user ID: in a browser bundle that is not built for production, and on a server only when NODE_ENV is development (never in test runs). identifyHint: false turns it off for an app without signed-in users

Runtime behavior

No extra config - the SDK detects the environment and adapts delivery.

EnvironmentBehavior
Browserbatching + persistence + retry
Node.jsbatching + retry
AWS Lambdaimmediate flush + retry. Other serverless hosts (Vercel, Netlify) are treated as Node: call await tracker.flush() before the response ends
Edge (Vercel Edge, Next.js Edge)batching + retry
Anything else (Cloudflare Workers, Deno, Bun)not detected as a separate runtime: the same batching + retry as Node.js. Deno and Bun are not tested yet

Event properties

Attach JSON data to any event. Validated at track() time (UTF-8 byte limits).

TypeScript
tracker.track("feature.used", {
  userId: "user_123",
  properties: {
    feature: "dashboard",
    plan: "pro",
  },
});

tracker.track("app.loaded");
  • Event name - trimmed, cut to 64 characters (never in the middle of an emoji) and trimmed again, so it is the name the CLI catalog holds
  • userId - cut to 120 characters. A number is written out as text; null or an object means no user id (null also overrides a user set by identify() or withUser())
  • properties - max depth 8, max about 32 KB (32,000 bytes, UTF-8). The SDK copies them when you call track(), so changing the object afterwards does not change the event
  • Batch payload - max 60 KB by default (maxPayloadBytes)

Configuration

Optional tuning for batching, retries, and error callbacks. endpoint is optional - omit it to use the production ingest URL.

TypeScript
const tracker = new Eventra({
  apiKey: "YOUR_PROJECT_API_KEY",
  flushInterval: 2000,
  maxBatchSize: 50,
  maxQueueSize: 10000,
  maxRetries: 3,
  retryBaseDelayMs: 300,
  maxPayloadBytes: 60000,
  onEventsDropped: (count) => {
    console.warn(`Dropped ${count} event(s)`);
  },
  onDeliveryFailed: ({ status, events }) => {
    console.error(`Ingest rejected batch (${status})`, events.length);
  },
});
OptionDescription
apiKeyProject API key (required). Create it with SDK access: a key made for the CLI is refused.
endpointIngest batch URL. Defaults to production. Use https: plain http to a remote host logs a warning.
flushIntervalPeriodic flush interval (ms, default 2000).
maxBatchSizeMax events per outgoing batch (default 50, at most 500, the most the API accepts in one request).
maxQueueSizeMax pending events before the oldest are dropped (default 10000).
maxRetriesTotal delivery attempts per batch (default 3).
retryBaseDelayMsBase delay for exponential backoff (ms, default 300).
maxPayloadBytesMax serialized batch size (default 60 000).
fetchImplCustom fetch (older Node, tests).
autoFlushOnExitNode and serverless, default true: flush what is queued when the script ends by itself and on SIGINT/SIGTERM. process.exit() and a crash do not run it, so await tracker.shutdown() first.
disableTimerDisable periodic flush timer.
onEventsDroppedCalled with a count when events are dropped (queue full, invalid event, or one event above maxPayloadBytes).
onDeliveryFailedCalled on permanent ingest errors (4xx except 429) with status and the rejected events. The whole batch is dropped, because the server does not say which event it refused.
multiTabModeBrowser only. "independent" (default): open tabs share their pending events and each may deliver them; the idempotency key is the same, so an event is counted once, but requests grow with the number of tabs. "leader": one tab sends for all.
persistQueueBrowser only, default true. Saves the pending queue (including userId and properties, unencrypted) to localStorage, at most about 1 MB of it (the newest events; the rest stay in memory). Set false for memory only.
identifyHintDefault true. Warn once when none of the first 50 events has a user ID: in a browser bundle not built for production, on a server only with NODE_ENV=development, never in test runs. false for an app without signed-in users. See Identify users.
diagnosticsDefault true. Sends numbers-only delivery counters (dropped, failed, by reason) with the next successful batch. Never billed; no names, user ids or properties. false disables it.
shutdownTimeoutMsMax time shutdown() spends flushing (default 10000).
exitOnSignalNode only, default true: after the flush, re-raise SIGINT/SIGTERM when nothing else listens to it, so the process ends as it would without the SDK (a container stops on docker stop). With your own signal handler the SDK only flushes. false: flush only.

An option with an invalid value (for example maxBatchSize: 0, NaN or an empty endpoint) is ignored with one console warning and the default is used. A callback you pass can throw or reject without affecting the SDK.

Manual flush

TypeScript
await tracker.flush();

flush() also waits for a send that is already running, so awaiting it in a serverless handler is enough. While the circuit breaker is open or a Retry-After wait is active it resolves without sending, and the events stay queued.

Shutdown

Graceful shutdown - flush first, then cleanup. For Node and serverless, prefer explicit shutdown over relying on process signals.

TypeScript
await tracker.flush();
await tracker.shutdown();

destroy() stops timers and listeners immediately without flushing. On Node a script that simply ends also flushes what is queued (within shutdownTimeoutMs); a process.exit() or a crash does not, and track() after shutdown() is ignored without a callback.

Usage examples

One tab per runtime or framework. Each example is copy-ready: a single Eventra instance, track() calls, and shutdown or flush() where the environment requires it (Node, Edge, serverless).

Batching, localStorage persistence, retry, flush on tab close (keepalive). identify() once after sign-in.

Browser
import { Eventra } from "@eventra_dev/eventra-sdk";

const tracker = new Eventra({
  apiKey: "YOUR_PROJECT_API_KEY",
});

// once you know who is signed in (after sign-in, or when a page loads for a
// signed-in user): every following event carries the user
function onSignedIn(user: { id: string }) {
  tracker.identify(user.id);
}

// on sign-out, so the next person on this device is not counted as them
function onSignedOut() {
  tracker.reset();
}

tracker.track("page.viewed");

// optional - attach context
tracker.track("page.viewed", {
  properties: { path: window.location.pathname },
});

// optional - single sender across tabs (browser only)
// const tracker = new Eventra({ apiKey: "YOUR_PROJECT_API_KEY", multiTabMode: "leader" });

Common patterns

Typical event shapes - same API as in Quick start above.

TypeScript
import { Eventra } from "@eventra_dev/eventra-sdk";

const tracker = new Eventra({ apiKey: "YOUR_PROJECT_API_KEY" });

// feature usage
tracker.track("feature.used", {
  userId: "user_123",
  properties: { feature: "dashboard" },
});

// page view (browser)
tracker.track("page.viewed", {
  properties: { path: window.location.pathname },
});

// API call
tracker.track("api.request", {
  properties: { endpoint: "/checkout", method: "POST", status: 200 },
});

// error
tracker.track("error.occurred", {
  properties: { message: "Payment failed", code: "PAYMENT_ERROR" },
});

Event format

This is what the SDK sends to /api/v1/ingest/batch. You never construct it by hand - the SDK handles batching, idempotency keys, and runtime detection.

JSON
{
  "sentAt": "2026-03-12T10:00:00Z",
  "sdk": {
    "name": "@eventra_dev/eventra-sdk",
    "version": "<sdk-version>",
    "runtime": "browser"
  },
  "events": [
    {
      "idempotencyKey": "550e8400-e29b-41d4-a716-446655440000",
      "name": "user_signup",
      "userId": "user_123",
      "timestamp": "2026-03-12T10:00:00Z",
      "properties": {}
    }
  ]
}

Limits enforced by the SDK at track() time:

FieldLimit
nametrimmed, ≤ 64 chars
userId≤ 120 chars
properties≤ 32,000 bytes (JSON serialized)
Property nesting depth≤ 8
Batch payload≤ maxPayloadBytes (default 60,000)
Fetch timeout5,000 ms
Circuit breakeropens after 5 consecutive failed batches, cools down 5 s, doubling on each repeat up to 60 s

Reliability

  • Idempotency (UUID v4 per event, stable across retries)
  • Retry with exponential backoff + jitter (capped)
  • Circuit breaker with half-open recovery
  • Queue-based delivery (all runtimes)
  • Safe dequeue (events removed only after successful ingest)
  • Queue persistence (browser) with merge + cross-tab sync
  • Multi-tab leader election with re-election
  • fetch + keepalive on tab close (with x-api-key, size-checked)
  • pagehide + visibilitychange flush hooks
  • Property validation at track() (depth + size)
  • Payload byte limits per batch
  • Permanent error handling via onDeliveryFailed (401, 422, etc.)
  • Automatic requeue on network errors and 429 / 5xx
  • Redirects are never followed (the key must not be forwarded); the events stay queued and Node logs one warning to check the endpoint URL
  • Oversize single events dropped via onDeliveryFailed(413)

Platform concepts

Terms used across the dashboard, API, and documentation.

Workspace

Top-level organization that owns billing, members, and projects. The plan sets how many workspaces an owner can have, and how many projects, API keys and members fit inside them.

Project

Isolated analytics environment with its own event catalog, API keys, rollups, and dashboard views. One workspace can contain multiple projects on paid tiers.

API key

Project-scoped secret sent as the x-api-key header on SDK and CLI requests. A key has an access level: SDK keys send events, CLI keys upload the catalog. Rotate keys from the dashboard without affecting other projects.

Feature

A tracked product capability derived from your event catalog. Rollups aggregate raw events into per-feature adoption and lifecycle signals.

Lifecycle state

Where a feature stands, judged against per-project thresholds (7 days for new, 14 for dead by default). A single feature can have its own dead threshold, or be marked never dead, in the settings on its page. New: first event within the new threshold. Active: used within the dead threshold. Declining: still used, but at half or less of the previous window of the same length (at least 10 uses before). Dead: used before, silent past the threshold. Never seen: found in code by the CLI, no event ever received.

Event

A single recorded usage signal, delivered at runtime via the SDK (billable). The CLI catalog sync registers features found in code without recording any usage (non-billable), which is how never-seen features are detected.

Function wrapper

A helper function that calls Eventra.track() internally. The CLI registers wrappers and resolves propagation chains across files.

External links

API reference for authenticated dashboard routes is available via the running ingest API Swagger UI in development (/api/docs). Production ingest endpoint: https://api.eventra.dev/api/v1/ingest/batch.