@billdog.io/analytics
v1.2.0-beta.1
Published
BillDog Analytics SDK - Mixpanel-like event tracking and user analytics
Maintainers
Readme
@billdog.io/analytics
BillDog Analytics SDK v2.0.0 - Industry-standard event tracking like Mixpanel.
Server-authoritative audience
Analytics records customer events and attributes used by server-side segmentation. Report filtering can consume segment IDs, but the Analytics SDK does not import or evaluate @billdog.io/segments or @billdog.io/targeting at runtime.
Installation
npm install @billdog.io/analytics
# or
yarn add @billdog.io/analyticsClient integration (3 steps)
A complete integration is: configure once at startup, identify on login, and let auto-tracking do the rest. Add custom track() calls only for the business events you care about.
import { analytics } from '@billdog.io/analytics';
// 1. Configure ONCE, as early as possible in your app's startup.
// `apiKey` is the only required field — the ingest endpoint is resolved
// from the key. Use a PUBLIC key (bd_public_*) in browser code.
analytics.configure({
apiKey: import.meta.env.VITE_BILLDOG_KEY, // your public key, from env
autoTrack: { pageViews: true, sessions: true },
autocapture: { enabled: true }, // auto-capture clicks/submits (optional)
exceptionAutocapture: true, // capture uncaught errors (optional)
});
// 2. Identify the user when they log in (use YOUR app's user id).
analytics.identify(user.id, { email: user.email, plan: user.plan });
// On logout:
analytics.reset();
// 3. Track custom business events wherever they happen.
analytics.track('Subscription Started', { plan: 'premium', price: 9.99 });That's the whole integration. With autoTrack on, page views and sessions are recorded automatically — you do not need to instrument every page. identify() attributes all events to the user.
Framework notes
- React — call
configure()once in your entry file (or a mounted-once provider), andidentify()/reset()from your auth state. To capture React render errors (whichwindow.onerrorcan't see), wrap your tree in an error boundary whosecomponentDidCatchcallsanalytics.captureException(error, { componentStack }). - Vue / Svelte / Angular —
configure()in the app entry;identify()/reset()from your auth store. - Vanilla JS —
configure()in a<script>on load;identify()after your login flow resolves.
Choosing the identify id. Pass a stable, unique id for the user (your app's user id, or their email). Any non-UUID string is auto-created as a person/customer and counted as a unique user.
Core Features
Event Tracking
// Track any event with properties
analytics.track('Purchase Completed', {
product_id: 'premium_monthly',
price: 9.99,
currency: 'USD'
});
// Track screen views
analytics.trackScreen('Onboarding');
// Track revenue (high priority - flushes immediately)
analytics.trackRevenue(9.99, 'USD', {
product_id: 'premium_monthly',
payment_method: 'credit_card'
});
// Time an event (measure duration)
analytics.timeEvent('Checkout');
// ... later
analytics.track('Checkout'); // Includes $duration propertyUser Properties
// Set a single property
analytics.setUserProperty('plan', 'premium');
// Set multiple properties
analytics.setUserProperties({
plan: 'premium',
region: 'US',
signup_date: '2024-01-15'
});
// Increment numeric properties
analytics.incrementUserProperty('login_count');
analytics.incrementUserProperty('purchases', 2);
// Append to array properties
analytics.appendToUserProperty('interests', 'music');Super Properties
Super properties are attached to every event automatically.
// Set super properties
analytics.setSuperProperty('app_version', '2.1.0');
analytics.setSuperProperties({
platform: 'ios',
environment: 'production'
});
// Get current super properties
const props = analytics.getSuperProperties();
// Clear all super properties
analytics.clearSuperProperties();Groups (B2B Analytics)
// Associate user with a group
analytics.setGroup('company', 'acme-corp');
// Set group properties
analytics.setGroupProperties('company', 'acme-corp', {
name: 'Acme Corporation',
industry: 'Technology',
employee_count: 500
});Identity Management
// Identify a user
analytics.identify('user123', { email: '[email protected]' });
// Alias (link anonymous ID to user ID)
analytics.alias('user123', 'anon_abc123');
// Reset (logout)
analytics.reset();
// Get IDs
analytics.getUserId(); // 'user123' or undefined
analytics.getAnonymousId(); // 'anon_...'
analytics.getSessionId(); // 'sess_...'Attribution
// Set attribution context (attached to revenue events)
analytics.setAttributionContext({
notification_id: 'notif_123',
campaign_id: 'summer_sale',
source: 'email',
medium: 'newsletter'
});
// Get current attribution
const attr = analytics.getAttributionContext();
// Clear attribution
analytics.clearAttributionContext();Control
// Force flush events to server
await analytics.flush();
// GDPR: Opt out (stops all tracking, resets data)
analytics.optOut();
// GDPR: Opt back in
analytics.optIn();Auto-Tracking
By default, the SDK automatically tracks:
| Event | Description |
|-------|-------------|
| $session_start | New session started |
| $session_end | Session ended (page unload) |
| $pageview | Page/screen view |
| $app_foregrounded | App became visible |
| $app_backgrounded | App went to background |
| $first_open | First time user opened app |
| $deep_link | UTM parameters detected |
Configure Auto-Tracking
analytics.configure({
apiKey: '...',
autoTrack: {
pageViews: true, // Track page views
sessions: true, // Track session start/end
appLifecycle: true, // Track foreground/background
attribution: true, // Track UTM parameters
deepLinks: true, // Track deep links
scrollDepth: false, // Track scroll depth (opt-in)
}
});
// Or disable all auto-tracking
analytics.configure({
apiKey: '...',
autoTrack: false
});Autocapture & error tracking
Both are opt-in flags on configure().
analytics.configure({
apiKey: '...',
// Auto-capture clicks / form submits / input changes (input VALUES are masked).
autocapture: { enabled: true },
// Capture uncaught errors + unhandled promise rejections as `$exception`.
exceptionAutocapture: true,
});
// Manually report a caught error at any time (works without exceptionAutocapture):
try {
doRiskyThing();
} catch (err) {
analytics.captureException(err, { where: 'checkout' });
}$exception events are flushed immediately (an error often precedes a crash or navigation, so they are never held in the batch).
Advanced Usage
Offline Support
Events are automatically queued to IndexedDB when offline and synced when back online.
Compression
All events are compressed (40-55% smaller) before sending to minimize bandwidth.
Screen Tracker
import { ScreenTracker } from '@billdog.io/analytics';
const screenTracker = new ScreenTracker(analytics, {
trackTiming: true,
trackScrollDepth: true,
screenNameResolver: (path, title) => customScreenName
});
screenTracker.autoTrack();Attribution Tracker
import { AttributionTracker } from '@billdog.io/analytics';
const attrTracker = new AttributionTracker(analytics, {
attributionWindow: 30, // days
firstTouch: true, // use first-touch attribution
persist: true // persist across sessions
});
attrTracker.initialize();API Reference
AnalyticsSDK
| Method | Description |
|--------|-------------|
| configure(config) | Initialize the SDK |
| identify(userId, properties?) | Identify a user |
| alias(newId, previousId) | Link two IDs |
| reset() | Reset user state |
| track(event, properties?) | Track an event |
| trackScreen(name, properties?) | Track a screen view |
| captureException(error, properties?) | Report an error as $exception |
| trackRevenue(amount, currency, properties?) | Track revenue |
| timeEvent(event) | Start timing an event |
| setUserProperty(key, value) | Set user property |
| setUserProperties(props) | Set multiple user properties |
| incrementUserProperty(key, amount?) | Increment user property |
| appendToUserProperty(key, value) | Append to array property |
| setSuperProperty(key, value) | Set super property |
| setSuperProperties(props) | Set multiple super properties |
| getSuperProperties() | Get all super properties |
| clearSuperProperties() | Clear super properties |
| setAttributionContext(ctx) | Set attribution context |
| getAttributionContext() | Get attribution context |
| clearAttributionContext() | Clear attribution context |
| setGroup(type, id) | Set group membership |
| setGroupProperties(type, id, props) | Set group properties |
| flush() | Force send events |
| optOut() | Stop tracking (GDPR) |
| optIn() | Resume tracking |
| getUserId() | Get current user ID |
| getAnonymousId() | Get anonymous ID |
| getSessionId() | Get session ID |
License
MIT
