All files / lib/analytics track.ts

100% Statements 36/36
87.5% Branches 7/8
100% Functions 2/2
100% Lines 36/36

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 521x               21x 21x 21x 21x 21x 21x   21x 21x 3x 21x 2x 2x 2x   19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 21x 21x 21x   21x 21x 21x   2x 2x 21x         1x 2x 2x  
'use client';
 
import type { EventType } from '@/types/database';
 
/**
 * Track an analytics event
 * This is a client-side function that sends events to the API
 */
export async function trackEvent(
  profileId: string,
  eventType: EventType,
  meta?: Record<string, unknown>
): Promise<void> {
  try {
    // Don't track in development unless explicitly enabled
    if (
      process.env.NODE_ENV === 'development' &&
      process.env.NEXT_PUBLIC_ENABLE_DEV_ANALYTICS !== 'true'
    ) {
      console.warn('[Analytics]', eventType, profileId, meta);
      return;
    }
 
    await fetch('/api/analytics/track', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        profile_id: profileId,
        event_type: eventType,
        meta: {
          ...meta,
          referrer: typeof document !== 'undefined' ? document.referrer : undefined,
        },
      }),
      // Don't wait for response, fire and forget
      keepalive: true,
    });
  } catch (error) {
    // Silently fail - analytics should never break the user experience
    console.error('[Analytics] Failed to track event:', error);
  }
}
 
/**
 * Track page view on mount
 */
export function trackPageView(profileId: string): void {
  trackEvent(profileId, 'profile_view');
}