@trace-x/sdk-browser
v0.1.6
Published
TraceX Analytics SDK for Browser
Readme
TraceX JavaScript SDK
A lightweight browser analytics SDK for tracking user behaviour, page views, and errors in single-page applications.
Installation
npm / yarn / pnpm
npm install @trace-x/sdk-browser
# or
yarn add @trace-x/sdk-browser
# or
pnpm add @trace-x/sdk-browserCDN (ESM)
<script type="module">
import { analytics } from "https://cdn.jsdelivr.net/npm/@trace-x/sdk-browser/dist/tracex.esm.js";
analytics.init({ endpoint: "https://your-tracex-server" });
</script>Quick Start
import { analytics } from "@trace-x/sdk-browser";
// Initialize once (e.g. in main.ts / index.ts)
analytics.init({
endpoint: "https://your-tracex-server",
appVersion: "1.0.0",
autoPageView: true, // automatically track page_view on navigation
autoError: true, // automatically capture unhandled errors
});
// Identify the logged-in user
analytics.identify("user_123");
// Track a custom event
analytics.track("button_click", {
button: "buy",
page: "/trading",
symbol: "AAPL",
});
// Track a page view manually (if autoPageView is false)
analytics.trackPageView({ section: "dashboard" });
// Force-flush before a critical navigation (awaitable)
await analytics.flush();
// Clean up (removes event listeners, stops timers)
analytics.destroy();React Integration
// src/analytics.ts
import { analytics } from "@trace-x/sdk-browser";
analytics.init({
endpoint: import.meta.env.VITE_TRACEX_ENDPOINT,
appVersion: import.meta.env.VITE_APP_VERSION,
autoPageView: true,
autoError: true,
});
export { analytics };
// src/main.tsx
import "./analytics";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>,
);// Track events from a component
import { analytics } from "./analytics";
function BuyButton({ symbol }: { symbol: string }) {
return (
<button onClick={() => analytics.track("trade.buy_clicked", { symbol })}>
Buy {symbol}
</button>
);
}Configuration Reference
| Option | Type | Default | Description |
| ---------------- | ------------- | --------- | ------------------------------------------------- |
| endpoint | string | — | Required. TraceX server base URL |
| appVersion | string | "" | Application version tag |
| platform | string | "web" | Platform label |
| batchSize | number | 50 | Events per HTTP request |
| flushInterval | number (ms) | 30000 | Auto-flush interval |
| maxQueueSize | number | 10000 | Max queued events before oldest are dropped |
| maxRetries | number | 3 | HTTP retry attempts on failure |
| sessionTimeout | number (ms) | 1800000 | Idle timeout before a new session starts |
| autoPageView | boolean | true | Track page_view on pushState / popstate |
| autoError | boolean | true | Capture window.onerror and unhandled rejections |
API Reference
analytics.init(options)
Initialize the SDK. Must be called before any other method.
analytics.identify(userId: string)
Associate the current user identity with subsequent events.
analytics.track(eventName: string, properties?: Record<string, unknown>)
Queue a custom event. The event is sent in the next flush batch.
analytics.trackPageView(properties?: Record<string, unknown>)
Queue a page_view event enriched with url, path, title, and referrer.
analytics.flush(): Promise<void>
Drain the queue immediately. Useful before critical navigation or logout.
analytics.destroy()
Stop the flush timer, send any pending events via sendBeacon, and reset state.
Event Schema
Each event sent to the server includes:
| Field | Source |
| ------------- | -------------------------------------- |
| eventName | Argument to track |
| timestamp | ISO-8601 string at enqueue time |
| sessionId | Managed internally; rotates on timeout |
| userId | Set by identify |
| anonymousId | Persisted in localStorage |
| platform | From options (default "web") |
| appVersion | From options |
| os | Inferred from navigator.userAgent |
| page | window.location.pathname |
| properties | Custom payload passed to track |
Automatic Events
When enabled, the SDK tracks the following events without extra code:
| Event | Trigger | Auto-enabled by |
| ----------- | ------------------------------- | -------------------- |
| page_view | pushState, popstate, init | autoPageView: true |
| error | window.onerror | autoError: true |
| error | unhandledrejection | autoError: true |
Building from Source
cd src/TraceX.Sdk.JavaScript
npm install
npm run build # outputs to dist/
npm run testRequirements
- Modern browser with
localStorage,fetch, and Web Crypto support for UUID generation throughuuid - Node.js 20+ for building from source
License
MIT
