Skip to Content
TrichiDataTrichiData

Node SDK

Install and set up @trichidata/node for server-side event tracking.

Use this guide when tracking events from a Node.js server — API routes, background jobs, webhooks.

For session flow and event schemas, see the REST API. For a guided first integration, see Quickstart.

Installation

npm install @trichidata/node

Requires Node.js >= 18.

Setup

@trichidata/node provides TrichiDataClient configured for server environments. The client parses the session cookie from init_sdk and sends it on subsequent requests — Node.js does not use a browser cookie jar.

import { TrichiDataClient } from '@trichidata/node';

const client = new TrichiDataClient({
  apiKey: process.env.TRICHIDATA_API_KEY!,
});

await client.init({
  device: {
    ip: '203.0.113.42',
    userAgent: 'MyService/1.0 (Node)',
    locale: 'en-US',
    timezone: 'UTC',
  },
  // optional: pass GA/Meta IDs from the incoming request
  tracking: {
    ga4: { clientId: '717831353.1785147356' },
  },
});

await client.identify({ userId: 'usr_7f3a9b2c', appVersion: '2.4.1' });

await client.orderCompleted({
  orderId: 'ord_123',
  total: 49.9,
  currency: 'USD',
  items: [{ productId: 'p1', name: 'Widget', price: 49.9, quantity: 1 }],
});

What is new in 0.6.0

Track calls no longer wait for the network. They enqueue the event, resolve with { eventId }, and a background timer sends batches (every 5 s or 20 events) with retry and exponential backoff. Because the queue lives in memory, flush before the process exits:

// serverless handler / job / script
await client.trackCustom('job_finished', { jobId });
await client.flush(); // send everything queued now

// on graceful shutdown (SIGTERM, end of script)
await client.shutdown(); // stop timers, then flush once (no retry)

Because the default storage is in memory, events that shutdown() cannot deliver are lost. Pass onError to find out:

import { TrichiDataClient, TrichiDataError } from '@trichidata/node';

const client = new TrichiDataClient({
  apiKey: process.env.TRICHIDATA_API_KEY!,
  onError: (error) => {
    if (error instanceof TrichiDataError && error.code === 'SHUTDOWN_UNDELIVERED') {
      console.error(`${error.count} analytics event(s) lost on shutdown`);
    }
  },
});
  • device.ip is now optional. When omitted, the server uses the request IP. Set it only if you proxy requests on behalf of an end user.
  • Each client instance is one anonymous identity (anonymousId) and session, and identify() stores the user id on that client. Use one client per end user or job. Do not share one client across concurrent requests for different users: their identities would overwrite each other. await client.reset() starts a new identity.
  • Storage defaults to memory. Pass storage (a StorageAdapter) if the queue and ids must survive restarts.
  • Consent: requireConsent: true holds back all traffic until await client.setConsent({ analytics: true }).
  • Timers are unref'd, so an idle client never keeps the process alive.

Options and errors

The client accepts flushAt (default 20), flushIntervalMs (5000), sessionTimeoutMs (30 minutes), maxQueueSize (500, oldest events are dropped first), retryBaseMs / retryMaxMs (1000 / 60000) and onError. onError receives a TrichiDataError with one of these codes:

CodeWhen
AUTH_FAILEDSending stopped after 3 consecutive 401/403 responses. Check the API key. count is the number of queued events
QUEUE_OVERFLOWThe queue reached maxQueueSize and the oldest events were dropped. count is the number dropped
SHUTDOWN_UNDELIVEREDshutdown() could not deliver everything and the storage is not persistent, so those events are lost. count is the number lost
CONSENT_ENDPOINT_MISSINGThe API has no /consent endpoint (404) when setConsent() notifies the server

Node-specific notes

Device info

You must provide device.userAgent explicitly in the init() payload; locale and timezone are optional. The SDK does not detect them automatically. device.ip is optional (see above).

Tracking context

Pass tracking when you have GA4 / Meta identifiers from the client request (cookies or known IDs). There is no automatic browser cookie parsing on Node. If omitted, the SDK generates a GA-like clientId and sends an empty metaPixel object so init_sdk validation still passes.

Typical use cases

  • API route handlers that track server-side conversions
  • Background jobs and cron tasks
  • Webhook processors forwarding business events

Client methods

MethodDescription
init({ device, tracking? })Start a session (init_sdk)
flush()Send queued events now
shutdown()Stop timers, then flush once (no retry)
reset()Clear identity and start a new anonymous id and session
setConsent({ analytics })Allow or stop tracking (use with requireConsent)
identify({ userId?, appVersion? })Associate session context — at least one field required
page / productViewed / …Typed helpers for reserved event names
trackCustom(name, properties?)Custom (non-reserved) event

See REST API for reserved eventName values and properties schemas.

See also

On this page