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 inlocalStorage(in memory whenlocalStorageis unavailable, for example in some private modes), sent in batches (every 5 s or 20 events) with retry and backoff, and flushed withkeepalivewhen the page is hidden. Callawait client.flush()to send now. - Anonymous id and sessions. A persistent
anonymousIdand aclientSessionId(new after 30 minutes of inactivity) are attached to every event. Callawait client.reset()on logout to clear the identity. - Safari ITP friendly. The session id is also sent as the
X-TrichiData-Sessionheader; the cookie keeps working. - Automatic pageviews.
init()tracks apageevent, and so does every SPA navigation (history.pushState,replaceState,popstate, de-duplicated by URL). SetautoPageviews: falseif you already callclient.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: truenothing is sent untilawait 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
| Option | Default | Description |
|---|---|---|
autoPageviews | true | Track page on init and on every SPA navigation |
requireConsent | false | Send nothing until setConsent({ analytics: true }) |
flushAt | 20 | Send as soon as this many events are queued |
flushIntervalMs | 5000 | Send queued events at this interval |
sessionTimeoutMs | 1800000 (30 min) | Start a new clientSessionId after this much inactivity |
maxQueueSize | 500 | Maximum stored events; the oldest are dropped first |
retryBaseMs / retryMaxMs | 1000 / 60000 | Bounds 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:
| Code | When |
|---|---|
AUTH_FAILED | Sending stopped after 3 consecutive 401/403 responses. Check the API key. count is the number of queued events |
QUEUE_OVERFLOW | The queue reached maxQueueSize and the oldest events were dropped. count is the number dropped |
SHUTDOWN_UNDELIVERED | shutdown() could not deliver everything and the storage is not persistent, so those events are lost. count is the number lost |
CONSENT_ENDPOINT_MISSING | The 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
| Helper | Description |
|---|---|
getPageContext() | Current page title, url, referrer |
Client methods
| Method | Description |
|---|---|
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
- Quickstart — track your first event
- REST API — event schemas and HTTP reference
- React SDK — if you use React