# Google Analytics 4 (GA4) Setup Guide for RateRight

## Overview
This guide provides a complete implementation of Google Analytics 4 for RateRight, including Next.js App Router integration, event tracking for the $50 hire fee conversion, and Australian privacy compliance considerations.

## Research Summary

### Next.js App Router Integration Methods

1. **@next/third-parties/google** (Recommended)
   - Official Next.js library
   - Optimized for performance
   - Built-in support for GA4 and GTM
   - Automatic script loading optimization

2. **Manual gtag.js Implementation**
   - Direct control over the tracking code
   - More flexible for custom implementations
   - Requires manual route change handling

3. **Google Tag Manager**
   - Best for marketing teams who need to manage tags
   - Requires additional GTM container setup
   - More complex for basic GA4 tracking

**Recommendation**: Use `@next/third-parties/google` for simplicity and performance.

### Key Events to Track for RateRight

1. **Page Views** (Automatic)
2. **User Signup** - When a new user creates an account
3. **Job Posted** - When a contractor posts a new job
4. **Worker Hired** - THE KEY EVENT: $50 conversion tracking
5. **Payment Completed** - Transaction details for revenue tracking

### Australian Privacy Considerations

- **No cookie banner required** under Australian law (Privacy Act 1988)
- **Privacy policy required** - Must disclose GA usage
- **Consent Mode v2** - Not mandatory for AU-only businesses
- **Best practice**: Include GA disclosure in privacy policy

## Implementation Guide

### Step 1: Create GA4 Property

1. Go to [Google Analytics](https://analytics.google.com/)
2. Click "Admin" → "Create Property"
3. Enter property name: "RateRight"
4. Select timezone: Australia/Sydney
5. Select currency: AUD
6. Click "Next" and complete property setup
7. When prompted to add a data stream, select "Web"
8. Enter website URL: `https://rivet.rateright.com.au`
9. Stream name: "RateRight Production"
10. **Copy the Measurement ID** (format: G-XXXXXXXXXX)

### Step 2: Install Dependencies

```bash
npm install @next/third-parties/google
```

### Step 3: Environment Variables

Add to `.env.local`:

```env
# Google Analytics
NEXT_PUBLIC_GA_MEASUREMENT_ID=G-XXXXXXXXXX
```

### Step 4: Create GA4 Components

#### `components/google-analytics.tsx`

```tsx
'use client';

import { GoogleAnalytics as NextGoogleAnalytics } from '@next/third-parties/google';

export function GoogleAnalytics() {
  const gaId = process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID;
  
  if (!gaId) {
    console.warn('Google Analytics ID not found');
    return null;
  }

  return <NextGoogleAnalytics gaId={gaId} />;
}
```

#### `lib/gtag.ts`

```typescript
declare global {
  interface Window {
    gtag: (...args: any[]) => void;
    dataLayer: any[];
  }
}

export const GA_MEASUREMENT_ID = process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID;

// Initialize gtag if it doesn't exist
export const initGA = (): void => {
  if (typeof window !== 'undefined' && !window.gtag) {
    window.dataLayer = window.dataLayer || [];
    window.gtag = function gtag() {
      window.dataLayer.push(arguments);
    };
    window.gtag('js', new Date());
    window.gtag('config', GA_MEASUREMENT_ID, {
      send_page_view: false, // We'll handle page views manually
    });
  }
};

// Page view tracking
export const pageview = (url: string): void => {
  if (typeof window !== 'undefined' && window.gtag) {
    window.gtag('config', GA_MEASUREMENT_ID as string, {
      page_path: url,
    });
  }
};

// Event tracking
interface EventProps {
  action: string;
  category: string;
  label?: string;
  value?: number;
}

export const event = ({ action, category, label, value }: EventProps): void => {
  if (typeof window !== 'undefined' && window.gtag) {
    window.gtag('event', action, {
      event_category: category,
      event_label: label,
      value: value,
    });
  }
};

// Ecommerce purchase tracking
interface PurchaseData {
  transaction_id: string;
  value: number;
  currency: string;
  items: Array<{
    item_id: string;
    item_name: string;
    price: number;
    quantity: number;
  }>;
}

export const trackPurchase = (purchaseData: PurchaseData): void => {
  if (typeof window !== 'undefined' && window.gtag) {
    window.gtag('event', 'purchase', {
      transaction_id: purchaseData.transaction_id,
      value: purchaseData.value,
      currency: purchaseData.currency,
      items: purchaseData.items,
    });
  }
};

// Signup tracking
export const trackSignup = (method: string = 'direct'): void => {
  event({
    action: 'sign_up',
    category: 'engagement',
    label: method,
  });
};

// Job posted tracking
export const trackJobPosted = (jobId: string): void => {
  event({
    action: 'job_posted',
    category: 'job',
    label: jobId,
  });
};

// Worker hired tracking (THE KEY CONVERSION EVENT)
export const trackWorkerHired = (jobId: string, workerId: string, hireFee: number = 50): void => {
  // Track as custom event
  event({
    action: 'worker_hired',
    category: 'conversion',
    label: `job_${jobId}_worker_${workerId}`,
    value: hireFee,
  });
  
  // Track as purchase for revenue reporting
  trackPurchase({
    transaction_id: `hire_${jobId}_${workerId}_${Date.now()}`,
    value: hireFee,
    currency: 'AUD',
    items: [{
      item_id: 'worker_hire_fee',
      item_name: 'Worker Hire Fee',
      price: hireFee,
      quantity: 1,
    }],
  });
};

// Payment completed tracking
export const trackPaymentCompleted = (paymentData: {
  paymentId: string;
  amount: number;
  currency?: string;
  jobId: string;
  workerId: string;
}): void => {
  trackPurchase({
    transaction_id: paymentData.paymentId,
    value: paymentData.amount,
    currency: paymentData.currency || 'AUD',
    items: [{
      item_id: 'worker_hire_fee',
      item_name: 'Worker Hire Fee',
      price: paymentData.amount,
      quantity: 1,
    }],
  });
};
```

### Step 5: Add GA to Root Layout

#### `app/layout.tsx`

```tsx
import { GoogleAnalytics } from '@/components/google-analytics';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <head>
        {/* Other head elements */}
      </head>
      <body>
        {children}
        <GoogleAnalytics />
      </body>
    </html>
  );
}
```

### Step 6: Track Page Views

#### `app/page.tsx` and other pages

```tsx
'use client';

import { useEffect } from 'react';
import { usePathname } from 'next/navigation';
import { pageview } from '@/lib/gtag';

export default function HomePage() {
  const pathname = usePathname();

  useEffect(() => {
    if (pathname) {
      pageview(pathname);
    }
  }, [pathname]);

  // Rest of your page component
}
```

Or create a client component for automatic tracking:

#### `components/analytics-provider.tsx`

```tsx
'use client';

import { useEffect } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
import { initGA, pageview } from '@/lib/gtag';

export function AnalyticsProvider({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    initGA();
  }, []);

  useEffect(() => {
    if (pathname) {
      const url = pathname + searchParams.toString();
      pageview(url);
    }
  }, [pathname, searchParams]);

  return <>{children}</>;
}
```

Then wrap your app in `providers.tsx`:

```tsx
'use client';

import { AnalyticsProvider } from '@/components/analytics-provider';

export function Providers({ children }: { children: React.ReactNode }) {
  return <AnalyticsProvider>{children}</AnalyticsProvider>;
}
```

### Step 7: Implement Event Tracking

#### Signup Tracking

```tsx
// In your signup form/component
import { trackSignup } from '@/lib/gtag';

const handleSignup = async (formData: FormData) => {
  // ... signup logic
  
  // Track successful signup
  trackSignup('email'); // or 'google', 'facebook', etc.
};
```

#### Job Posted Tracking

```tsx
// In your job posting form
import { trackJobPosted } from '@/lib/gtag';

const handleJobPost = async (jobData: JobData) => {
  // ... job posting logic
  
  // Track successful job post
  trackJobPosted(jobData.id);
};
```

#### Worker Hired Tracking (KEY CONVERSION)

```tsx
// In your hire worker flow
import { trackWorkerHired } from '@/lib/gtag';

const handleHireWorker = async (jobId: string, workerId: string) => {
  // ... hiring logic
  
  // Track the $50 conversion
  trackWorkerHired(jobId, workerId, 50);
};
```

#### Payment Tracking

```tsx
// In your payment completion flow
import { trackPaymentCompleted } from '@/lib/gtag';

const handlePaymentSuccess = async (paymentData: PaymentData) => {
  // ... payment processing
  
  // Track payment
  trackPaymentCompleted({
    paymentId: paymentData.id,
    amount: paymentData.amount,
    currency: 'AUD',
    jobId: paymentData.jobId,
    workerId: paymentData.workerId,
  });
};
```

## Testing & Verification

### 1. Real-Time Reports

1. Go to GA4 → Reports → Real-time
2. Open your website in a new tab
3. You should see active users appearing

### 2. Debug View

1. Install [Google Analytics Debugger](https://chrome.google.com/webstore/detail/google-analytics-debugger/jnkmfdileelhofjcijamephohjechhna) Chrome extension
2. Open DevTools → Console
3. Perform actions on your site
4. Check for gtag events firing

### 3. Test Events

Run these commands in the browser console:

```javascript
// Test if gtag is loaded
typeof gtag

// Test page view
gtag('event', 'page_view', { page_path: '/test' })

// Test custom event
gtag('event', 'test_event', { event_category: 'test', event_label: 'console_test' })
```

## Privacy Policy Update

Add this section to your privacy policy:

```markdown
## Google Analytics

We use Google Analytics 4 to understand how visitors interact with our website. Google Analytics collects information such as how often users visit the site, what pages they visit, and what other sites they used prior to coming to our site. We use this information to improve our website and services.

Google Analytics collects only the IP address assigned to you on the date you visit this site, rather than your name or other identifying information. We do not combine the information collected through the use of Google Analytics with personally identifiable information.

Google Analytics plants a permanent cookie on your web browser to identify you as a unique user the next time you visit this site. This cookie cannot be used by anyone but Google, Inc.

For more information on Google Analytics' privacy practices, please visit: https://support.google.com/analytics/answer/6004245
```

## Troubleshooting

### Common Issues

1. **Events not appearing**
   - Check if GA_MEASUREMENT_ID is set correctly
   - Verify events are firing in browser console
   - Wait 24-48 hours for data to appear in standard reports

2. **Duplicate page views**
   - Ensure you're not tracking both automatically and manually
   - Check for multiple gtag initializations

3. **Ecommerce data not showing**
   - Verify purchase events are properly formatted
   - Check currency codes are valid
   - Ensure transaction IDs are unique

### Debug Mode

Enable debug mode by adding to your GA component:

```tsx
<NextGoogleAnalytics gaId={gaId} debugMode />
```

## Next Steps

1. Set up conversion goals in GA4 for the worker_hired event
2. Create custom reports for job posting and hiring metrics
3. Set up audience segmentation for contractors vs workers
4. Configure Google Ads integration if running paid campaigns
5. Set up automated alerts for significant changes in conversion rates

## Support

For issues or questions:
- Google Analytics Help Center: https://support.google.com/analytics
- Next.js Documentation: https://nextjs.org/docs/messages/next-script-for-ga
- RateRight Development Team: development@rateright.com.au