npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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 localStorage if the user is offline or a request fails, preventing data loss.
  • 🔄 Auto-Flush Sync: Automatically listens to browser connectivity transitions (online event) 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 sessionStorage with 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.history monkeypatching.
  • 📈 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 (default false) — Logs SDK actions to the developer console.
  • autoTrackPageViews: boolean (default false) — Automatically hooks into browser navigation/history to log page views.
  • userId: string | (() => string | null | undefined) — Required if autoTrackPageViews is enabled. A string or function returning the active user ID.
  • enableErrors: boolean (default true) — Automatically catches unhandled browser errors, promise rejections, and enables manual error reporting.
  • enableAPM: boolean (default true) — Captures web performance metrics and Core Web Vitals (LCP, CLS, INP, FID).
  • captureConsole: boolean (default false) — Monopoles console.error calls 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:

  1. All events (trackPageView, trackEvent, captureException) are serialized and buffered in localStorage under the key socio_telemetry_queue_[apiKey].
  2. A queue buffer holds up to 500 events using First-In-First-Out eviction.
  3. The SDK hooks into the browser online window 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 (default 30).
  • theme: dark or light (default auto-detects browser/system theme).
  • accent-color: Hex color overriding the primary purple style (e.g. #ff007a for 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.