socio-dau-tracker-sdk
v1.0.3
Published
Client SDK for the DAU Tracker
Downloads
375
Readme
Socio DAU Tracker SDK
A lightweight, performance-optimized, and privacy-preserving Web Analytics, Daily Active User (DAU) tracking, and Observability library, complete with an offline-first buffering engine and embeddable analytics UI widget.
Designed for decentralized apps (dApps) to easily record active user metrics, sessions, custom events, campaign UTM parameters, Core Web Vitals, exceptions, and securely embed verified analytics charts for public display.
Key Features
- ⚡ Lightweight: Minimal dependencies, keeping your bundle sizes ultra-small.
- 📶 Offline-First Buffering: Telemetry data (page views, events, exceptions) is safely queued in
localStorageif the user is offline or a request fails, preventing data loss. - 🔄 Auto-Flush Sync: Automatically listens to browser connectivity transitions (
onlineevent) to seamlessly flush buffered logs to the registry database. - 🐞 Error & Exception Tracker: Capture uncaught runtime exceptions and promise rejections with auto-collected breadcrumbs.
- 🕒 Session Lifecycle Manager: Automatically maintains sessions in
sessionStoragewith a 30-minute idle inactivity timeout. - 🏷️ UTM & Referrer Tracking: Automatically parses and reports campaign sources (
utm_source,utm_medium,utm_campaign) and traffic referrers. - ⚙️ Automatic Page View Tracking: Listeners to automatically track route changes in single-page apps (SPA) using
window.historymonkeypatching. - 📈 Core Web Vitals Observer: Natively tracks performance metrics (Page Load Time, Largest Contentful Paint, Cumulative Layout Shift, and Interaction to Next Paint).
- 🎯 Custom Event Logging: Track arbitrary user actions, conversions, goals, and interactions.
- 📱 Demographic Parsing: Automatically parses device type (Mobile, Tablet, Desktop), browser, and OS without heavy external libraries.
- 📊 Embeddable Chart Widget: A responsive, framework-agnostic Custom Element Web Component
<socio-dau-widget>to show user metrics.
Installation
Install the package via your preferred package manager:
npm install socio-dau-tracker-sdk
# or
yarn add socio-dau-tracker-sdk
# or
pnpm add socio-dau-tracker-sdk🚀 Usage
1. Initialization Config
Configure the tracker by passing your API Key and optional configuration attributes:
import { SocioDauTracker } from 'socio-dau-tracker-sdk';
const tracker = new SocioDauTracker('YOUR_API_KEY', {
debug: false, // Enable console logs for debugging
autoTrackPageViews: true, // Automatically listen to SPA route changes
userId: () => getCurrentUid(), // Dynamic getter to retrieve the current user's ID
enableErrors: true, // Automatically capture uncaught errors & unhandled rejections
enableAPM: true, // Track network request durations and Page Vitals
captureConsole: false // Capture console.error statements as breadcrumbs
});Configuration Options
debug:boolean(defaultfalse) — Logs SDK actions to the developer console.autoTrackPageViews:boolean(defaultfalse) — Automatically hooks into browser navigation/history to log page views.userId:string | (() => string | null | undefined)— Required ifautoTrackPageViewsis enabled. A string or function returning the active user ID.enableErrors:boolean(defaulttrue) — Automatically catches unhandled browser errors, promise rejections, and enables manual error reporting.enableAPM:boolean(defaulttrue) — Captures web performance metrics and Core Web Vitals (LCP, CLS, INP, FID).captureConsole:boolean(defaultfalse) — Monopolesconsole.errorcalls and appends them as diagnostic breadcrumbs.
2. Manual Tracking APIs
A. Track Page Views (with Performance Vitals)
Manually track page views. The SDK automatically appends page load speeds and Web Vitals if observed:
tracker.trackPageView('user_wallet_address', {
path: '/marketplace', // Defaults to window.location.pathname
title: 'NFT Marketplace', // Defaults to document.title
referrer: 'https://google.com' // Defaults to document.referrer
});B. Track Custom Events
Log custom interaction metrics, user goals, or conversion triggers:
tracker.trackEvent('user_wallet_address', 'swap_completed', {
pair: 'ICP-USDT',
amount: 250.0,
slippage: 0.005
});C. Deduplicated Active User Ping
Pings the server once per day per user (automatically cached and deduplicated in localStorage to save network bandwidth):
tracker.track('user_wallet_address');3. Error & Exception Handling APIs
You can capture exceptions manually in try/catch blocks or hook them into framework-level error boundaries.
A. Capture Exception
Send a standard Error object or string description with optional contextual metadata:
try {
executeContractCall();
} catch (error) {
tracker.captureException(error, {
gasLimit: 3000000,
canisterId: 'ryjl3-tyaaa-aaaaa-aaaba-cai'
});
}B. Capture Message
Log arbitrary log events, warning states, or telemetry markers:
tracker.captureMessage('Transaction took longer than expected', 'warning', {
durationMs: 8200
});C. React Query / TanStack Query Global Integration
Catch all queries and mutation exceptions automatically by initializing hooks in your Query Cache:
import { QueryClient, QueryCache, MutationCache } from '@tanstack/react-query';
const queryClient = new QueryClient({
queryCache: new QueryCache({
onError: (error, query) => {
tracker.captureException(error, {
queryKey: query.queryKey,
type: 'query'
});
}
}),
mutationCache: new MutationCache({
onError: (error, variables, context, mutation) => {
tracker.captureException(error, {
mutationKey: mutation.options.mutationKey,
variables,
type: 'mutation'
});
}
})
});4. Offline-First Queuing Engine
If a user's device loses internet connection, the SDK ensures no analytics or crash data is lost:
- All events (
trackPageView,trackEvent,captureException) are serialized and buffered inlocalStorageunder the keysocio_telemetry_queue_[apiKey]. - A queue buffer holds up to
500events using First-In-First-Out eviction. - The SDK hooks into the browser
onlinewindow event. When the internet connection returns, it automatically flushes all buffered events sequentially in the background.
📊 Part 2: Public Analytics Widget Embed
Embed the responsive <socio-dau-widget> Custom Element to display active metrics charts and demographics.
Widget Properties
api-key: (Required) Your registered app's API key.days: Number of days of history to display on the SVG chart (default30).theme:darkorlight(default auto-detects browser/system theme).accent-color: Hex color overriding the primary purple style (e.g.#ff007afor pink).
1. React SPA (Vite / CRA)
import { useEffect } from 'react';
export default function VerifiedAnalytics() {
useEffect(() => {
// Loads custom element client-side
import('socio-dau-tracker-sdk/widget');
}, []);
return (
<div style={{ width: '100%', maxWidth: '600px' }}>
{/* @ts-ignore */}
<socio-dau-widget api-key="YOUR_API_KEY" days="30" theme="dark" />
</div>
);
}2. Next.js (SSR with Dynamic Import)
To prevent server-side custom element rendering warnings and hydration mismatches, wrap the widget in a client component and load it dynamically with ssr: false:
Step 1: Create a client component wrapper (e.g. WidgetWrapper.tsx)
'use client';
import { useEffect } from 'react';
export default function WidgetWrapper() {
useEffect(() => {
import('socio-dau-tracker-sdk/widget');
}, []);
return <socio-dau-widget api-key="YOUR_API_KEY" days="30" theme="dark" />;
}Step 2: Load with dynamic import in your page
import dynamic from 'next/dynamic';
const PublicWidget = dynamic(() => import('./WidgetWrapper'), {
ssr: false,
loading: () => <p>Loading Analytics Widget...</p>,
});3. HTML / CDN Embed
<!-- Load the widget Custom Element script -->
<script type="module" src="https://esm.sh/[email protected]/dist/widget.js"></script>
<!-- Embed the custom element -->
<socio-dau-widget api-key="YOUR_API_KEY" days="30" theme="dark"></socio-dau-widget>TypeScript JSX Declarations
Add this interface to your global.d.ts or type declaration file to prevent JSX compilation element errors:
declare namespace JSX {
interface IntrinsicElements {
'socio-dau-widget': React.DetailedHTMLProps<
React.HTMLAttributes<HTMLElement> & {
'api-key': string;
days?: string | number;
theme?: 'dark' | 'light';
'accent-color'?: string;
},
HTMLElement
>;
}
}License
MIT License.
