Product Analytics (Client SDKs)
Client-Side Product Analytics
The @billdog.io/analytics client SDK gives you full product analytics from the browser: manual event capture, element-level autocapture, identity resolution, and person/event properties. Events are validated, batched, gzip-compressed, and shipped to the ingest-events endpoint. This page closes the parity gap with PostHog-style instrumentation and is grounded entirely in the real SDK surface.
Client-side analytics is opt-in & privacy-aware
configure(). Input values are masked by default when autocapture is on, and optOut() stops this SDK recording or sending anything new and resets local identity. Session replay started through configure() stops too, in every open tab of your site, and its frames that have not been uploaded yet are discarded rather than sent. That replay also follows the replay consent purpose: it does not record until replay is permitted, and withdrawing it discards unsent frames the same way. optOut() also stops a recorder started with startSessionReplay from @billdog.io/web, which that package’s configure() also starts when enableSessionReplay is set, and discards what it has not uploaded (see Session Replay). The server further enforces IP-tracking and GeoIP-resolution privacy controls.1. Capturing Events
Configure the SDK once with your API key, then call track() to capture a custom event with optional properties. The SDK automatically merges your registered super properties and attaches $distinct_id and $device_id to every event.
import { analytics } from '@billdog.io/analytics';
// Configure once at app startup
analytics.configure({
apiKey: 'bd_public_test_yourApiKey',
enableLogging: true, // verbose console output (see §8)
batchSize: 10, // flush after N events (default 10)
flushInterval: 30000, // background flush every 30s
});
// Capture a custom event ("object verb" naming convention)
analytics.track('checkout_completed', {
amount: 49.99,
items_count: 3,
plan: 'pro',
});
// Screen / page views have a dedicated helper ($screen event)
analytics.trackScreen('Pricing', { referrer: 'homepage' });
// Revenue is a first-class, high-priority event (flushes immediately)
analytics.trackRevenue(49.99, 'USD', {
$product_id: 'pro_monthly',
$quantity: 1,
});
// Force a flush (e.g. before navigating away)
await analytics.flush();Transaction-Backed Revenue Attribution
trackRevenue for telemetry, the Revenue report and per-offering revenue in the BillDog dashboard come from store and Stripe transactions (Apple, Google, Amazon, Roku, Stripe). Offering revenue is attributed by product-to-offering membership. Paywall and placement revenue and all conversion figures come from SDK purchase events, so store renewals are not attributed to a paywall.2. Automatic Tracking
With autoTrack enabled the SDK records page views and sessions for you — no per-page code. In single-page apps the History API is patched, so route changes emit $pageview automatically.
analytics.configure({
apiKey: 'bd_public_test_yourApiKey',
autoTrack: {
pageViews: true, // $pageview on load + SPA route changes
sessions: true, // $session_start / $session_end
},
});
// Every page/route view and session is now tracked with no extra code.3. Error Tracking
Enable exceptionAutocapture to capture uncaught errors and unhandled promise rejections as $exception events, or report caught errors manually with captureException(). Exceptions flush immediately — an error often precedes a crash or navigation.
analytics.configure({
apiKey: 'bd_public_test_yourApiKey',
exceptionAutocapture: true, // window.onerror + unhandledrejection -> $exception
});
// Report a caught error manually (works even without autocapture):
try {
doRiskyThing();
} catch (err) {
analytics.captureException(err, { where: 'checkout' });
}4. Autocapture
With autocapture enabled, the SDK attaches global click / submit / change listeners and emits standard events automatically — no manual instrumentation. It also detects frustration signals and applies privacy masking before anything is sent.
Auto-emitted events
$autocapture — every interaction, with $event_type of click/submit/change plus element props ($el_tag_name, $el_text, $el_classes, $el_href, $el_attr_id, $elements_chain).$rageclick — 3+ clicks within 1s in a ~30px radius (carries $click_count).$dead_click — a click with no DOM mutation or navigation within 1s.analytics.configure({
apiKey: 'bd_public_test_yourApiKey',
// Element-level autocapture is OPT-IN (default OFF)
autocapture: {
enabled: true,
maskAllText: false, // default false: $el_text captured (trimmed, max 255 chars)
maskAllInputs: true, // default TRUE when enabled: input values redacted to "***"
ignoreClasses: ['internal-widget'], // extra classes to skip, like bd-no-capture
},
});
// Once enabled, clicks/submits/changes emit $autocapture automatically.
// You can still mix manual analytics.track(...) calls alongside it.5. Identifying Users
Before login a visitor is tracked under a persistent anonymous ID (anon_…, stored in localStorage). The active $distinct_id is the user ID once identified, otherwise the anonymous ID. Calling identify() promotes the visitor to a known user and links their prior anonymous activity.
// On login/signup, identify the user. distinct_id becomes this userId.
// An $identify event is emitted carrying $user_id + $device_id (the
// anonymous id), which merges the pre-login anonymous timeline.
analytics.identify('user_9928', {
email: 'user@gmail.com',
plan: 'pro',
});
// Invalid IDs are rejected (empty, "undefined", "null", "anonymous",
// "guest", "0", > 255 chars, whitespace-only) and logged as a warning.
analytics.getDistinctId(); // 'user_9928'
analytics.getAnonymousId(); // 'anon_...' (still the device id)If you sign people in with BillDog Auth
Signing in does not switch the SDK’s current customer. The session is separate from analytics identity, so $distinct_id stays the anonymous ID until you call identify() yourself. Identify with the token’s sub claim — the user who signed in — so events resolve to the same customer that holds the entitlements. The cus claim beside it is that customer’s id. See Sessions & Tokens for the full claim set.
// 'auth' is your createBillDogAuth(...) client from '@billdog.io/auth'.
// A correct password against an account with a second factor issues NO
// session — finish the second factor first, then identify once.
const { session } = await auth.attempt({
identifier: 'ada@example.com',
strategy: 'password',
password,
});
// 'sub' is the USER who signed in; 'cus' is the id of the CUSTOMER they own.
// Reading claims here is for wiring identity only — your server still
// verifies the token against the JWKS.
const b64 = session.token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
const claims = JSON.parse(atob(b64.padEnd(b64.length + ((4 - (b64.length % 4)) % 4), '=')));
analytics.identify(claims.sub);
// On sign-out, tear down both sides — auth alone leaves analytics identified.
await auth.signOut();
analytics.reset();6. User (Person) Properties
Event properties describe a single event and are immutable once sent. Person properties live on the user profile and reflect the latest known state. Person updates are debounced (~1s) and POSTed to /user-properties using Mixpanel-style operations.
set vs set_once
$set overwrites the value every time (use for mutable traits like plan or last_seen). $set_once only writes if the key is not already present (use for first-touch traits like initial_referrer or signup_date).// $set — overwrite (single key or bulk object)
analytics.setUserProperty('plan', 'pro');
analytics.setUserProperties({ plan: 'pro', seats: 5 });
// $set_once — only writes if the key doesn't exist yet
analytics.setUserPropertyOnce('signup_date', '2026-06-19');
analytics.setUserPropertyOnce('initial_referrer', document.referrer);
// You can also attach person properties inline via identify():
analytics.identify('user_9928', { email: 'user@gmail.com' });7. Direct HTTP Ingest API (no SDK)
For platforms without a BillDog client SDK, POST events directly to the ingest-events endpoint. Authenticate with your API key, batch up to 2,000 events per request, and optionally gzip the body. The endpoint maps SDK field names to the internal schema (e.g. name → event_name, timestamp → event_timestamp).
curl -X POST https://api.billdog.io/v1/ingest-events \
-H "Content-Type: application/json" \
-H "X-BillDog-API-Key: bd_public_test_yourApiKey" \
-d '{
"api_key": "bd_public_test_yourApiKey",
"platform": "web",
"sdk_version": "1.0.0",
"events": [
{
"name": "checkout_completed",
"timestamp": 1718800000000,
"session_id": "sess_abc",
"anonymous_id": "anon_123",
"properties": {
"$user_id": "user_9928",
"amount": 49.99,
"$currency": "USD",
"$insert_id": "01J0X8Z9K3..."
}
}
]
}'8. Debug Mode
Pass enableLogging: true to surface verbose console output while integrating — confirm the SDK configured, watch flush batch sizes, and see validation warnings as events flow.
What logging surfaces
Flushed N events (compressed) on each successful batch, offline-queue activity, and property-limit warnings (too many keys, oversized arrays, exceeded nesting depth, dropped oversized events).analytics.configure({
apiKey: 'bd_public_test_yourApiKey',
enableLogging: true,
batchSize: 1, // flush after every event while debugging
});
analytics.track('debug_ping', { hello: 'world' });
// Console output, e.g.:
// [BillDog Analytics] SDK configured with auto-tracking: true
// [BillDog Analytics] Flushed 1 events (compressed)
//
// Warnings you may see (validation is non-throwing):
// [BillDog Analytics] Too many property keys (300), limiting to 255
// [BillDog Analytics] Array too long (400), limiting to 255
// [BillDog Analytics] Max nesting depth exceeded, truncating
// [BillDog Analytics] Event too large (... bytes), droppingWas this page helpful?
Or rate this page: