1.0.1 â€Ē Published 11 months ago

@domino-run/analytics-js v1.0.1

Weekly downloads
-
License
-
Repository
github
Last release
11 months ago

@domino-run/analytics-js

Client-side analytics tracking library for Domino Analytics. Track user behavior, page views, custom events, and referrals with ease.

Features

  • ðŸŠķ Lightweight - Zero dependencies, just native fetch
  • 📊 Optional Page Tracking - Configurable automatic page view tracking
  • 🔄 Session Management - Browser session-based tracking
  • ðŸ‘Ī User Identification - Easy user identity management
  • ðŸŽŊ Custom Events - Track any custom event with properties
  • 🔗 Referral System - Built-in referral system with wallet support
  • ðŸ“ą Browser Support - Works in all modern browsers
  • 🔒 Type Safe - Written in TypeScript with full type definitions

Installation

npm install @domino-run/analytics-js
# or
yarn add @domino-run/analytics-js
# or
pnpm add @domino-run/analytics-js

Quick Start

import { DominoAnalytics } from '@domino-run/analytics-js';

// Initialize with your API key
const analytics = new DominoAnalytics({
  apiKey: 'your-api-key',
  // Optional: enable automatic page tracking
  pageTracking: {
    enabled: true,
    trackHistory: true // also track history changes (back/forward)
  },
  // Optional: specify referral type
  referralType: 'user_id' // or 'wallet' for crypto applications
});

// Track a custom event
analytics.track({
  eventType: 'button_click',
  properties: {
    buttonId: 'signup-button',
    buttonText: 'Sign Up Now'
  }
});

// Identify a user
analytics.identify({
  externalId: 'user-123', // or wallet address for crypto apps
  properties: {
    name: 'John Doe',
    email: 'john@example.com',
    plan: 'premium'
  }
});

Configuration

Page Tracking

Page tracking is disabled by default. To enable it, use the pageTracking configuration:

const analytics = new DominoAnalytics({
  apiKey: 'your-api-key',
  pageTracking: {
    enabled: true,     // Enable automatic page view tracking
    trackHistory: true // Optional: track history changes (back/forward navigation)
  }
});

When enabled, it will automatically track:

  • Initial page load (enabled: true)
  • Browser history changes if trackHistory: true (back/forward navigation)

You can also manually track page views:

analytics.track({
  eventType: 'page_view',
  pageUrl: window.location.href,
  referrer: document.referrer
});

Session Management

The library uses browser session storage for managing sessions:

  • Each browser session gets a unique session ID
  • Session persists across page refreshes
  • Session is cleared when the browser/tab is closed
  • New session is created when browser is reopened
  • Sessions are automatically managed, no configuration needed

Referral System

The library includes a built-in referral system that supports both traditional user IDs and crypto wallet addresses.

Referral Types

There are two types of referral systems:

  1. User ID Based (referralType: 'user_id'):

    • Default referral system
    • Uses internal or external user IDs for referrals
    • Validates referrer exists in the system
  2. Wallet Based (referralType: 'wallet'):

    • Designed for crypto applications
    • Uses wallet addresses as referral IDs
    • Validates wallet address format (0x...)
    • Automatically creates user records for new wallet addresses

Referral Flow

  1. Generating Referral Links
// After identifying a user
const referralLink = analytics.getReferralLink();
// Or with custom base URL
const customLink = analytics.getReferralLink('https://example.com/signup');
  1. Handling Referrals
  • Referral data is automatically detected from URL parameters
  • Referral info is stored until the referred user identifies
  • Referral relationship is created upon user identification
  • Referral data persists across sessions until used

Example flow:

// User A: Generate referral link
await analytics.identify({ externalId: 'user_a' });
const link = analytics.getReferralLink(); // https://example.com?ref=user_a

// User B: Clicks link and later identifies
await analytics.identify({
  externalId: 'user_b',
  properties: { name: 'User B' }
}); // Referral is automatically tracked

API Reference

Initialization

const analytics = new DominoAnalytics({
  apiKey: string;           // Required: Your API key
  endpoint?: string;        // Optional: Custom API endpoint
  referralType?: 'wallet' | 'user_id'; // Optional: Referral system type
  pageTracking?: {         // Optional: Automatic page view tracking
    enabled: boolean;      // Enable/disable page tracking
    trackHistory?: boolean;// Track history changes (back/forward)
  };
});

Tracking Events

analytics.track({
  eventType: string;           // Required: Event name
  properties?: {              // Optional: Event properties
    [key: string]: any;
  };
  pageUrl?: string;          // Optional: Override page URL
  referrer?: string;         // Optional: Override referrer
});

Identifying Users

analytics.identify({
  externalId: string;         // Required: User ID or wallet address
  properties?: {             // Optional: User properties
    [key: string]: any;
  };
});

Best Practices

Event Naming

  • Use snake_case for event names
  • Be consistent with naming conventions
  • Use descriptive but concise names

Example events:

analytics.track({ eventType: 'page_view' });
analytics.track({ eventType: 'button_click' });
analytics.track({ eventType: 'form_submit' });
analytics.track({ eventType: 'purchase_complete' });

Properties

  • Include relevant context in properties
  • Avoid sensitive information
  • Use consistent property names

Example:

analytics.track({
  eventType: 'button_click',
  properties: {
    button_id: 'signup-cta',
    button_text: 'Start Free Trial',
    page_section: 'hero',
    variant: 'A'
  }
});

User Properties

  • Include business-relevant user data
  • Update properties when they change
  • Avoid sensitive data

Example:

analytics.identify({
  externalId: 'user_123',
  properties: {
    name: 'John Doe',
    email: 'john@example.com',
    plan: 'premium',
    company: 'Acme Inc'
  }
});

Referral Best Practices

  • Generate referral links only after user identification
  • Use descriptive base URLs for referral links
  • Add UTM parameters for better tracking
  • Test referral flows in incognito mode

Example with UTM parameters:

const baseUrl = 'https://example.com/special-offer';
const referralLink = analytics.getReferralLink(baseUrl);
const trackingUrl = new URL(referralLink);
trackingUrl.searchParams.append('utm_source', 'referral');
trackingUrl.searchParams.append('utm_medium', 'user_share');

Error Handling

The library includes built-in error handling with typed errors:

try {
  await analytics.track({
    eventType: 'purchase',
    properties: { amount: 99.99 }
  });
} catch (error) {
  if (error.status === 401) {
    // Handle unauthorized error
  }
}

Browser Support

Supports all modern browsers with Fetch API:

  • Chrome 42+
  • Firefox 39+
  • Safari 10.1+
  • Edge 14+

Framework Integration

React

// src/lib/analytics.ts
import { DominoAnalytics } from '@domino-run/analytics-js';

export const analytics = new DominoAnalytics({
  apiKey: process.env.REACT_APP_ANALYTICS_KEY!,
  pageTracking: {
    enabled: true,
    trackHistory: true
  }
});

// Optional: Create hooks for easier usage
import { useEffect } from 'react';

export function usePageTracking() {
  useEffect(() => {
    analytics.track({
      eventType: 'page_view',
      pageUrl: window.location.href
    });
  }, []);
}

export function useIdentify(userId: string, properties?: Record<string, any>) {
  useEffect(() => {
    if (userId) {
      analytics.identify({
        externalId: userId,
        properties
      });
    }
  }, [userId, properties]);
}

Usage in components:

// src/App.tsx
import { analytics, usePageTracking } from './lib/analytics';

function App() {
  // Track page views automatically
  usePageTracking();

  return (
    <div>
      <button onClick={() => {
        analytics.track({
          eventType: 'button_click',
          properties: { buttonId: 'signup' }
        });
      }}>
        Sign Up
      </button>
    </div>
  );
}

// src/UserProfile.tsx
import { useIdentify } from './lib/analytics';

function UserProfile({ user }) {
  // Identify user when component mounts
  useIdentify(user.id, {
    name: user.name,
    email: user.email
  });

  return <div>Welcome, {user.name}!</div>;
}

Vue

// src/plugins/analytics.ts
import { DominoAnalytics } from '@domino-run/analytics-js';
import type { App } from 'vue';

export const analytics = new DominoAnalytics({
  apiKey: import.meta.env.VITE_ANALYTICS_KEY,
  pageTracking: {
    enabled: true,
    trackHistory: true
  }
});

// Create Vue plugin
export const analyticsPlugin = {
  install: (app: App) => {
    app.config.globalProperties.$analytics = analytics;
    
    // Optional: Create composables
    app.provide('analytics', analytics);
  }
};

// Optional: Create composables
import { onMounted, watch } from 'vue';

export function usePageTracking() {
  onMounted(() => {
    analytics.track({
      eventType: 'page_view',
      pageUrl: window.location.href
    });
  });
}

export function useIdentify(userId: string, properties?: Record<string, any>) {
  watch(() => userId, (newId) => {
    if (newId) {
      analytics.identify({
        externalId: newId,
        properties
      });
    }
  }, { immediate: true });
}

Usage in components:

<!-- src/App.vue -->
<script setup lang="ts">
import { analytics, usePageTracking } from './plugins/analytics';

// Track page views automatically
usePageTracking();

const handleClick = () => {
  analytics.track({
    eventType: 'button_click',
    properties: { buttonId: 'signup' }
  });
};
</script>

<template>
  <button @click="handleClick">Sign Up</button>
</template>

<!-- src/UserProfile.vue -->
<script setup lang="ts">
import { useIdentify } from './plugins/analytics';

const props = defineProps<{
  user: {
    id: string;
    name: string;
    email: string;
  }
}>();

// Identify user when component mounts or user changes
useIdentify(props.user.id, {
  name: props.user.name,
  email: props.user.email
});
</script>

<template>
  <div>Welcome, {{ user.name }}!</div>
</template>

Using with Router

For both React and Vue, you can integrate with the router for better page tracking:

React Router

import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { analytics } from './lib/analytics';

export function useRouteTracking() {
  const location = useLocation();

  useEffect(() => {
    analytics.track({
      eventType: 'page_view',
      pageUrl: window.location.href,
      properties: {
        path: location.pathname,
        search: location.search
      }
    });
  }, [location]);
}

Vue Router

import { useRoute } from 'vue-router';
import { watch } from 'vue';
import { analytics } from './plugins/analytics';

export function useRouteTracking() {
  const route = useRoute();

  watch(
    () => route.fullPath,
    () => {
      analytics.track({
        eventType: 'page_view',
        pageUrl: window.location.href,
        properties: {
          path: route.path,
          params: route.params,
          query: route.query
        }
      });
    },
    { immediate: true }
  );
}

Contributing

We welcome contributions! Please see our Contributing Guide.

License

MIT ÂĐ Domino Analytics

1.0.1

11 months ago

1.0.0

11 months ago

0.1.0

1 year ago