Skip to content

setup-analytics

Integrate Cloudflare Analytics for comprehensive application monitoring.

Overview

The setup-analytics command configures Cloudflare Analytics, Web Analytics, and custom event tracking to monitor your application's performance, usage patterns, and business metrics.

Usage

bash
/template setup-analytics [options]

Options

  • --web-analytics - Enable Cloudflare Web Analytics (default: true)
  • --rum - Enable Real User Monitoring
  • --custom-events - Set up custom event tracking
  • --dashboard - Create analytics dashboard endpoint

Examples

Basic Analytics Setup

bash
/template setup-analytics

Full Analytics Suite

bash
/template setup-analytics --rum --custom-events --dashboard

Custom Events Only

bash
/template setup-analytics --web-analytics false --custom-events

What It Creates

Analytics Configuration

  • Web Analytics beacon setup
  • Custom event tracking utilities
  • Analytics middleware
  • Dashboard API endpoints

Generated Structure

src/
├── analytics/
│   ├── config.ts          # Analytics configuration
│   ├── events.ts          # Custom event definitions
│   ├── tracker.ts         # Event tracking utilities
│   ├── middleware.ts      # Request tracking middleware
│   └── dashboard.ts       # Analytics dashboard API

Example Event Tracking

typescript
// src/analytics/tracker.ts
export class Analytics {
  constructor(private env: Env) {}

  async track(event: string, properties?: Record<string, any>) {
    await this.env.ANALYTICS.writeDataPoint({
      blobs: [event],
      doubles: properties?.value ? [properties.value] : [],
      indexes: [event],
    });
  }

  async trackPageView(url: string, referrer?: string) {
    await this.track('page_view', {
      url,
      referrer,
      timestamp: Date.now(),
    });
  }

  async trackApiCall(endpoint: string, duration: number, status: number) {
    await this.track('api_call', {
      endpoint,
      duration,
      status,
      success: status < 400,
    });
  }
}

Example Middleware

typescript
// src/analytics/middleware.ts
export function analyticsMiddleware(): MiddlewareHandler {
  return async (c, next) => {
    const start = Date.now();
    const analytics = new Analytics(c.env);
    
    // Track request
    await next();
    
    // Track response
    const duration = Date.now() - start;
    await analytics.trackApiCall(
      c.req.path,
      duration,
      c.res.status
    );
  };
}

Web Analytics Setup

Beacon Installation

html
<!-- Automatically injected into HTML responses -->
<script 
  defer 
  src='https://static.cloudflareinsights.com/beacon.min.js'
  data-cf-beacon='{"token": "YOUR_TOKEN"}'
></script>

Custom Properties

typescript
// Track custom dimensions
window.cfBeacon = {
  userId: currentUser.id,
  plan: currentUser.plan,
  feature: 'dashboard',
};

Custom Event Types

Business Events

typescript
// E-commerce events
await analytics.track('purchase', {
  orderId: order.id,
  amount: order.total,
  currency: 'USD',
  items: order.items.length,
});

// Subscription events
await analytics.track('subscription_created', {
  plan: subscription.plan,
  interval: subscription.interval,
  amount: subscription.amount,
});

Performance Events

typescript
// API performance
await analytics.track('api_latency', {
  endpoint: '/api/users',
  p50: 45,
  p95: 120,
  p99: 250,
});

// Database performance
await analytics.track('db_query', {
  table: 'users',
  operation: 'select',
  duration: 15,
  rows: 100,
});

User Behavior

typescript
// Feature usage
await analytics.track('feature_used', {
  feature: 'export_pdf',
  userId: user.id,
  success: true,
});

// Search analytics
await analytics.track('search', {
  query: searchTerm,
  results: resultCount,
  clicked: clickedResult,
});

Dashboard API

Metrics Endpoint

typescript
// src/analytics/dashboard.ts
app.get('/api/analytics/metrics', async (c) => {
  const timeRange = c.req.query('range') || '24h';
  
  const metrics = await c.env.ANALYTICS.query({
    metric: ['page_views', 'unique_visitors', 'api_calls'],
    timeRange,
    dimensions: ['country', 'device_type'],
  });
  
  return c.json(metrics);
});

Real-time Stats

typescript
app.get('/api/analytics/realtime', async (c) => {
  const stats = await getRealTimeStats(c.env.ANALYTICS);
  return c.json({
    activeUsers: stats.activeUsers,
    requestsPerSecond: stats.rps,
    errorRate: stats.errorRate,
  });
});

Best Practices

  1. Privacy First: Don't track PII without consent
  2. Sampling: Use sampling for high-traffic events
  3. Batching: Batch events for efficiency
  4. Naming Convention: Use consistent event names
  5. Documentation: Document all custom events

Integration Examples

With Authentication

typescript
// Track login success/failure
await analytics.track('auth_attempt', {
  method: 'password',
  success: true,
  mfa: false,
});

With Queues

typescript
// Track queue processing
await analytics.track('queue_processed', {
  queue: 'email',
  messages: batch.messages.length,
  duration: processingTime,
});

With R2 Storage

typescript
// Track file uploads
await analytics.track('file_uploaded', {
  bucket: 'user-uploads',
  size: file.size,
  type: file.type,
  duration: uploadTime,
});

Performance Monitoring

Core Web Vitals

typescript
// Automatic tracking with Web Analytics
// LCP, FID, CLS tracked automatically

Custom Performance Metrics

typescript
// Track custom timing
await analytics.track('custom_metric', {
  name: 'time_to_interactive',
  value: tti,
  page: window.location.pathname,
});

Alerting and Monitoring

Threshold Alerts

typescript
// Set up alerts for metrics
if (errorRate > 0.05) {
  await sendAlert('High error rate detected', {
    rate: errorRate,
    threshold: 0.05,
  });
}

Anomaly Detection

typescript
// Detect unusual patterns
const baseline = await getBaselineMetrics();
if (currentMetric > baseline * 2) {
  await analytics.track('anomaly_detected', {
    metric: 'api_calls',
    expected: baseline,
    actual: currentMetric,
  });
}

Privacy and Compliance

  • No cookies by default
  • IP anonymization
  • GDPR compliant
  • User consent management
  • Data retention policies

Built with ❤️ for the AI Coding community, by Praney Behl