Skip to Content
TrichiDataTrichiData

Browser SDK

Track events from vanilla JavaScript and browser frameworks with @trichidata/browser.

Use this guide for browser applications — vanilla JavaScript and frameworks like Vue, Svelte, and Angular.

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

Install

npm install @trichidata/browser

@trichidata/browser provides TrichiDataClient configured for browser environments. The client uses credentials: 'include' so the browser stores the sdk_session cookie automatically after init().

Usage

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

const client = new TrichiDataClient({
  apiKey: 'prj_ak_xxxxxxxxxxxx',
});

await client.init(); // device + tracking cookies under the hood

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

await client.page(); // page context filled from window/document
await client.productViewed({ productId: 'sku_1', name: 'Shoes', price: 99, currency: 'USD' });
await client.trackCustom('promo_banner_click', { slot: 'hero' });

init() collects device info and tracking automatically: _ga / _fbp / _fbc / fbclid when present; otherwise the SDK generates a GA-like clientId. You can override with init({ device, tracking }).

What is new in 0.6.0

  • Queue and retry. Track methods return { eventId } immediately. Events are persisted in localStorage (in memory when localStorage is unavailable, for example in some private modes), sent in batches (every 5 s or 20 events) with retry and backoff, and flushed with keepalive when the page is hidden. Call await client.flush() to send now.
  • Anonymous id and sessions. A persistent anonymousId and a clientSessionId (new after 30 minutes of inactivity) are attached to every event. Call await client.reset() on logout to clear the identity.
  • Safari ITP friendly. The session id is also sent as the X-TrichiData-Session header; the cookie keeps working.
  • Automatic pageviews. init() tracks a page event, and so does every SPA navigation (history.pushState, replaceState, popstate, de-duplicated by URL). Set autoPageviews: false if you already call client.page() on each route change.
  • Automatic attribution. UTM parameters, click ids (gclid, gbraid, wbraid, fbclid, ttclid, msclkid), referrer and landing page are captured automatically (first touch once per device, last touch per session).
  • Consent. With requireConsent: true nothing is sent until await client.setConsent({ analytics: true }). setConsent({ analytics: false }) clears the queue, removes the stored anonymous id and stops tracking. Page views before consent are dropped; the current page is sent once consent is given.
  • The device IP is no longer sent from the browser; the server uses the request IP.
const client = new TrichiDataClient({
  apiKey: 'prj_ak_xxxxxxxxxxxx',
  autoPageviews: true, // default
  requireConsent: false, // default
  flushAt: 20, // default
  flushIntervalMs: 5000, // default
  sessionTimeoutMs: 30 * 60 * 1000, // default
});
// after login
await client.identify({ userId: 'usr_7f3a9b2c' });

// on logout
await client.reset();

Options and errors

OptionDefaultDescription
autoPageviewstrueTrack page on init and on every SPA navigation
requireConsentfalseSend nothing until setConsent({ analytics: true })
flushAt20Send as soon as this many events are queued
flushIntervalMs5000Send queued events at this interval
sessionTimeoutMs1800000 (30 min)Start a new clientSessionId after this much inactivity
maxQueueSize500Maximum stored events; the oldest are dropped first
retryBaseMs / retryMaxMs1000 / 60000Bounds of the exponential retry backoff
onError—Called when a batch is dropped or a background operation fails

Track calls do not throw on network errors; failures are reported to onError. SDK-level problems arrive as 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
import { TrichiDataClient, TrichiDataError } from '@trichidata/browser';

const client = new TrichiDataClient({
  apiKey: 'prj_ak_xxxxxxxxxxxx',
  maxQueueSize: 500, // default
  onError: (error) => {
    if (error instanceof TrichiDataError) {
      console.warn('[trichidata]', error.code, error.count ?? '');
    }
  },
});

To stop the client (for example before tearing down a micro-frontend), call await client.shutdown(). It stops timers and navigation tracking and flushes once without retry. The client stays stopped until init() is called again.

Helpers

HelperDescription
getPageContext()Current page title, url, referrer

Client methods

MethodDescription
init(params?)Start a session (init_sdk)
flush()Send queued events now
shutdown()Stop timers and auto pageviews, then flush once
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