Client-Side Event Tracking

Complete guide to implementing automatic event tracking in web browsers with the Appizer Web SDK

Learn how to implement automatic event tracking in web browsers using the Appizer Web SDK. This guide covers automatic user identification, page view tracking, and custom event tracking.

TL;DR

  • Drop in the Web SDK script and initialize with your App ID
  • Automatic user ID generation and persistence via localStorage
  • Automatic page view tracking on every page load
  • Simple API for tracking custom events
  • No manual user identification required
  • Domain-based authentication - no API keys needed in browser

Overview

The Appizer Web SDK provides a complete solution for client-side analytics tracking in web browsers. It automatically handles:

  • User Identification: Generates and persists unique user IDs using browser fingerprinting
  • Page View Tracking: Automatically tracks page views with URL, title, and referrer
  • Custom Events: Simple API for tracking any custom user interaction
  • Session Management: Maintains user identity across page loads and sessions

Quick Setup

1. Include the SDK

Add the SDK script to your website's <head> or before the closing </body> tag:

<script src="https://cdn.appizer.com/js/appizer-web.js"></script>

2. Initialize with Your Credentials

<script>
  AppizerWeb.init({
    appId: "YOUR_APP_ID",
    autoEvents: true, // Automatic page view tracking (including SPAs)
    autoHook: true,   // Automatic form submission tracking
    debug: false      // Set to true during development
  });
</script>

That's it!

The SDK is now tracking page views automatically and ready to track custom events. User IDs are generated and persisted automatically. No API keys needed - authentication is handled via domain validation.

Automatic User Identification

How It Works

The SDK automatically generates a unique user ID using browser fingerprinting when a user first visits your site. This ID is stored in localStorage and reused for all subsequent visits.

Fingerprint Components:

  • User agent string
  • Screen resolution and color depth
  • Timezone offset
  • Hardware concurrency
  • Platform information
  • Timestamp and random component

Generated ID Format: anon_[hash]_[timestamp]

Example: anon_abc123def_xyz789

Getting the User ID

// Get the current user ID
const userId = AppizerWeb.getUserId();
console.log('Current user ID:', userId);

Setting a Custom User ID

When a user logs in or you want to identify them with your own ID:

// After user login
AppizerWeb.setUserId('user_12345');

// All subsequent events will use this ID
AppizerWeb.trackEvent('user_logged_in', {
  method: 'email',
  timestamp: new Date().toISOString()
});

Best Practice

Use setUserId() to link anonymous sessions with known user identities after login. This creates a complete user journey from anonymous visitor to authenticated user.

Automatic Page View Tracking

When autoEvents: true (default), the SDK automatically tracks a page_view event on every page load.

Page View Event Structure

{
  "event_name": "page_view",
  "user_id": "anon_abc123_xyz789",
  "properties": {
    "url": "https://yoursite.com/products/premium",
    "path": "/products/premium",
    "title": "Premium Plan - Your Site",
    "referrer": "https://google.com/search?q=premium+plans"
  },
  "timestamp": "2024-01-15T10:30:00.000Z",
  "ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36..."
}

Disabling Automatic Page Views

If you want to track page views manually:

AppizerWeb.init({
  appId: "YOUR_APP_ID",
  autoEvents: false // Disable automatic tracking
});

Custom Event Tracking

Track any user interaction or custom event using the trackEvent() method.

Basic Event Tracking

// Track a simple event
AppizerWeb.trackEvent('button_clicked');

// Track an event with properties
AppizerWeb.trackEvent('video_played', {
  video_id: 'intro_video',
  duration: 120,
  quality: '1080p'
});

Common Event Examples

E-commerce Events

// Product viewed
AppizerWeb.trackEvent('product_viewed', {
  product_id: 'prod_123',
  product_name: 'Premium Plan',
  category: 'subscription',
  price: 29.99,
  currency: 'USD'
});

// Add to cart
AppizerWeb.trackEvent('add_to_cart', {
  product_id: 'prod_123',
  quantity: 1,
  price: 29.99
});

// Purchase completed
AppizerWeb.trackEvent('purchase_completed', {
  order_id: 'order_789',
  total: 99.99,
  currency: 'USD',
  items: 3,
  payment_method: 'credit_card'
});

User Engagement Events

// Form submission
AppizerWeb.trackEvent('form_submitted', {
  form_id: 'contact_form',
  form_name: 'Contact Us'
});

// CTA clicked
AppizerWeb.trackEvent('cta_clicked', {
  cta_text: 'Get Started',
  cta_location: 'hero_section',
  page: window.location.pathname
});

// Content engagement
AppizerWeb.trackEvent('article_read', {
  article_id: 'blog_post_123',
  reading_time: 180, // seconds
  scroll_depth: 85 // percentage
});

Navigation Events

// Search performed
AppizerWeb.trackEvent('search_performed', {
  query: 'premium plans',
  results_count: 12
});

// Filter applied
AppizerWeb.trackEvent('filter_applied', {
  filter_type: 'price',
  filter_value: '0-50'
});

Event with Custom User ID

Override the automatic user ID for a specific event:

AppizerWeb.trackEvent('admin_action', {
  action: 'user_deleted',
  target_user: 'user_456'
}, {
  userId: 'admin_123' // Override automatic user ID
});

Advanced Usage

Tracking User Interactions

Track scroll depth:

let maxScrollDepth = 0;

window.addEventListener('scroll', function() {
  const scrollPercentage = Math.round(
    (window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100
  );
  
  if (scrollPercentage > maxScrollDepth) {
    maxScrollDepth = scrollPercentage;
    
    // Track milestones
    if ([25, 50, 75, 100].includes(scrollPercentage)) {
      AppizerWeb.trackEvent('scroll_depth', {
        depth: scrollPercentage,
        page: window.location.pathname
      });
    }
  }
});

Track time on page:

const pageLoadTime = Date.now();

window.addEventListener('beforeunload', function() {
  const timeOnPage = Math.round((Date.now() - pageLoadTime) / 1000);
  
  AppizerWeb.trackEvent('page_exit', {
    time_on_page: timeOnPage,
    page: window.location.pathname
  });
});

Track outbound link clicks:

document.querySelectorAll('a[href^="http"]').forEach(link => {
  link.addEventListener('click', function(e) {
    const href = this.getAttribute('href');
    const isExternal = !href.includes(window.location.hostname);
    
    if (isExternal) {
      AppizerWeb.trackEvent('outbound_link_clicked', {
        url: href,
        text: this.textContent,
        from_page: window.location.pathname
      });
    }
  });
});

Single Page Applications (SPAs)

The SDK automatically detects navigation in Single Page Applications—no manual tracking needed!

Supported Frameworks:

  • ✅ React (React Router)
  • ✅ Vue.js (Vue Router)
  • ✅ Angular (Angular Router)
  • ✅ Next.js (App Router & Pages Router)
  • ✅ Svelte (SvelteKit)
  • ✅ Any framework using History API

How it works: The SDK intercepts history.pushState(), history.replaceState(), and browser navigation events to automatically track page views on route changes.

Manual tracking (optional): If you need to manually trigger page views for custom scenarios:

// Manually track a page view
AppizerWeb.trackEvent('page_view', {
  url: window.location.href,
  path: window.location.pathname,
  title: document.title
});

Error Tracking

Track JavaScript errors:

window.addEventListener('error', function(event) {
  AppizerWeb.trackEvent('javascript_error', {
    message: event.message,
    filename: event.filename,
    line: event.lineno,
    column: event.colno,
    page: window.location.pathname
  });
});

Configuration Reference

Initialization Options

AppizerWeb.init({
  // Required
  appId: "YOUR_APP_ID",
  
  // Optional - Event Tracking
  autoEvents: true, // Enable automatic page view tracking
  eventsEndpoint: "/v1/website/events", // Override events endpoint
  
  // Optional - User Identification
  userIdStorageKey: "appizer_user_id", // localStorage key
  
  // Optional - Form Tracking
  autoHook: true, // Auto-register forms with email fields
  emailField: "email", // Custom email field name
  emailSelectors: ["input[type=email]"], // Custom email selectors
  
  // Optional - API Configuration
  apiBase: "https://api.appizer.com", // API base URL
  endpoint: "/v1/website/users", // Form submission endpoint
  websiteUrl: window.location.origin, // Origin for validation
  
  // Optional - Development
  debug: false // Enable verbose console logging
});

API Methods

// Initialize SDK
AppizerWeb.init(options)

// Track custom event
AppizerWeb.trackEvent(eventName, properties, options)

// Get current user ID
AppizerWeb.getUserId(options)

// Set custom user ID
AppizerWeb.setUserId(userId, options)

// Register form manually
AppizerWeb.registerForm(formElement, options)

// Send user data manually
AppizerWeb.sendUser(options, payload)

Privacy & Compliance

Data Collection

The SDK collects:

  • Browser fingerprint: User agent, screen properties, timezone (no PII)
  • Page views: URL, title, referrer
  • Custom events: Event names and properties you define
  • IP address: Captured server-side for analytics (not in fingerprint)
  • Origin domain: Validated against authorized domains for security

User Privacy

Privacy Compliance

Ensure your privacy policy discloses:

  • Analytics tracking is active on your site
  • Data is stored in localStorage
  • Users can clear localStorage to reset their ID
  • No personally identifiable information is collected without consent
  • Domain validation is used for authentication (no API keys in browser)

GDPR Compliance

// Disable tracking based on user consent
if (!userHasConsented()) {
  AppizerWeb.init({
    appId: "YOUR_APP_ID",
    autoEvents: false // Disable until consent given
  });
}

// Enable tracking after consent
function enableTracking() {
  AppizerWeb.init({
    appId: "YOUR_APP_ID",
    autoEvents: true
  });
}

Data Deletion

Users can clear their tracking data by clearing localStorage:

// Clear Appizer user ID
localStorage.removeItem('appizer_user_id');

Troubleshooting

Events Not Appearing

  1. Check App ID: Ensure your App ID is correct
  2. Check Console: Enable debug: true to see detailed logs
  3. Check Network: Look for failed requests in browser DevTools (should be POST to /v1/website/events)
  4. Verify Authorized Domains: Ensure your website domain is configured in App Settings under authorized domains

Debug Mode

Enable debug mode during development:

AppizerWeb.init({
  appId: "YOUR_APP_ID",
  debug: true // Logs all SDK activity to console
});

Common Issues

localStorage not available:

  • SDK will still work but won't persist user IDs across sessions
  • Common in private browsing mode

CORS errors:

  • Ensure your website domain is in the authorized domains list in App Settings
  • Check that you're using the correct API base URL
  • Verify the Origin header matches your configured domain

Events not tracking:

  • Verify App ID is correct in initialization
  • Check that autoEvents is not set to false if you expect automatic tracking
  • Ensure your domain is in the authorized domains list in App Settings

Best Practices

  1. Initialize Early: Add the SDK script in your <head> tag for earliest tracking
  2. Use Meaningful Event Names: Use descriptive, consistent naming (e.g., product_viewed, not pv)
  3. Include Relevant Properties: Add context to events with properties
  4. Link Anonymous to Known: Use setUserId() after login to connect sessions
  5. Track Key Conversions: Focus on events that matter to your business
  6. Test Thoroughly: Use debug: true during development
  7. Respect Privacy: Implement proper consent mechanisms
  8. Monitor Performance: SDK is lightweight but verify it doesn't impact page load
  9. Configure Authorized Domains: Set up your authorized domains in App Settings for security
  10. No API Keys in Browser: Never expose API keys - domain validation handles authentication

Next Steps