Tips & Tricks

How to Implement Analytics with Claude Code

Learn how to implement analytics using Claude Code. Includes practical code examples and step-by-step guidance.

The Challenges of Analytics Implementation

Measuring user behavior is the foundation of product improvement, but supporting multiple analytics services, respecting privacy, and keeping performance impact low is not trivial. With Claude Code, you can rapidly build an extensible analytics foundation.

A Unified Event Tracking Layer

> Build a unified tracking layer that supports multiple analytics providers.
> It should be able to fan out to Google Analytics, Mixpanel, and a custom API at the same time.
interface TrackingEvent {
  name: string;
  properties?: Record<string, any>;
  timestamp?: Date;
}

interface AnalyticsProvider {
  name: string;
  track(event: TrackingEvent): void;
  pageView(path: string, title: string): void;
  identify(userId: string, traits?: Record<string, any>): void;
}

class AnalyticsManager {
  private providers: AnalyticsProvider[] = [];
  private queue: TrackingEvent[] = [];
  private isReady = false;

  addProvider(provider: AnalyticsProvider) {
    this.providers.push(provider);
  }

  track(name: string, properties?: Record<string, any>) {
    const event: TrackingEvent = { name, properties, timestamp: new Date() };

    if (!this.isReady) {
      this.queue.push(event);
      return;
    }

    this.providers.forEach((p) => {
      try { p.track(event); }
      catch (e) { console.warn(`Tracking error from ${p.name}:`, e); }
    });
  }

  pageView(path: string, title: string) {
    this.providers.forEach((p) => p.pageView(path, title));
  }

  identify(userId: string, traits?: Record<string, any>) {
    this.providers.forEach((p) => p.identify(userId, traits));
  }

  flush() {
    this.isReady = true;
    this.queue.forEach((event) => this.track(event.name, event.properties));
    this.queue = [];
  }
}

export const analytics = new AnalyticsManager();

A Google Analytics Provider

class GAProvider implements AnalyticsProvider {
  name = 'Google Analytics';

  track(event: TrackingEvent) {
    window.gtag?.('event', event.name, event.properties);
  }

  pageView(path: string, title: string) {
    window.gtag?.('event', 'page_view', { page_path: path, page_title: title });
  }

  identify(userId: string) {
    window.gtag?.('set', { user_id: userId });
  }
}

Using It From React Hooks

import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

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

  useEffect(() => {
    analytics.pageView(location.pathname, document.title);
  }, [location.pathname]);
}

export function useTrackEvent() {
  return (name: string, properties?: Record<string, any>) => {
    analytics.track(name, properties);
  };
}

// Usage example
function ProductPage({ product }: { product: Product }) {
  const trackEvent = useTrackEvent();

  const handleAddToCart = () => {
    trackEvent('add_to_cart', {
      productId: product.id,
      price: product.price,
      category: product.category,
    });
  };

  return <button onClick={handleAddToCart}>Add to cart</button>;
}
class ConsentManager {
  private consent: Record<string, boolean> = {};

  setConsent(category: string, allowed: boolean) {
    this.consent[category] = allowed;
    localStorage.setItem('analytics_consent', JSON.stringify(this.consent));
  }

  isAllowed(category: string): boolean {
    return this.consent[category] ?? false;
  }

  loadSavedConsent() {
    const saved = localStorage.getItem('analytics_consent');
    if (saved) this.consent = JSON.parse(saved);
  }
}

Summary

With Claude Code, you can build an analytics foundation that covers unified tracking across multiple providers, React hooks, and privacy handling all in one coherent package. For A/B testing integration, see the A/B testing implementation guide, and for performance measurement, see the performance optimization guide.

For Google Analytics setup, see the GA4 official documentation.

#Claude Code #analytics #tracking #React #TypeScript

Level up your Claude Code workflow

50 battle-tested prompt templates you can copy-paste into Claude Code right now.

Free

Free PDF: Claude Code Cheatsheet in 5 Minutes

Key commands, shortcuts, and prompt examples on a single printable page.

Download PDF
M

About the Author

Masa

Engineer obsessed with Claude Code. Runs claudecode-lab.com, a 10-language tech media with 2,000+ pages.