GameCraftGameCraft

Analytics Integration

Learn how to integrate Google Analytics and Microsoft Clarity into ProductReady

Analytics Integration

ProductReady comes with built-in support for Google Analytics and Microsoft Clarity. These integrations are designed to be minimal, production-ready, and require only environment variable configuration.

Zero configuration required: Simply add your tracking IDs as environment variables, and analytics will automatically be enabled. No code changes needed!


Supported Analytics Platforms

Google Analytics (GA4)

Google Analytics helps you understand user behavior, track conversions, and measure marketing ROI.

Features:

  • 📊 Page view tracking
  • 🎯 Event tracking
  • 👥 User demographics
  • 📈 Conversion tracking
  • 🔍 Real-time analytics

Best for: Understanding user behavior, marketing attribution, and conversion optimization.

Microsoft Clarity

Microsoft Clarity provides session recordings and heatmaps to visualize how users interact with your application.

Features:

  • 🎥 Session recordings
  • 🔥 Heatmaps (click, scroll, area)
  • 📱 Mobile & desktop insights
  • ⚡ Performance metrics
  • 🆓 100% free (no limits)

Best for: UX optimization, identifying usability issues, and understanding user frustration points.


Quick Start

Get Your Tracking IDs

  1. Go to Google Analytics
  2. Create a new property (or use existing)
  3. Set up a GA4 Data Stream for your website
  4. Copy your Measurement ID (format: G-XXXXXXXXXX)

Example: G-ABC123XYZ

  1. Go to Microsoft Clarity
  2. Click Add new project
  3. Enter your website URL
  4. Copy your Project ID (alphanumeric string)

Example: abc123xyz

Add Environment Variables

Add the following to your .env file:

# Google Analytics (optional)
NEXT_PUBLIC_GA_MEASUREMENT_ID="G-XXXXXXXXXX"

# Microsoft Clarity (optional)
NEXT_PUBLIC_CLARITY_PROJECT_ID="your-clarity-project-id"

Important: Use NEXT_PUBLIC_ prefix to make these variables available in the browser (required for client-side tracking).

Deploy & Verify

Local development:

pnpm dev

Open your browser's DevTools Console and Network tab to verify:

  • Google Analytics: Look for requests to https://www.googletagmanager.com/gtag/js
  • Microsoft Clarity: Look for requests to https://www.clarity.ms/tag/

Production: Deploy your app and check your analytics dashboards after 24-48 hours for initial data.


Configuration Details

Google Analytics

ProductReady uses Next.js's built-in @next/third-parties/google package for optimal performance.

Key features:

  • ✅ Server-side rendering compatible
  • ✅ Automatic page view tracking (App Router)
  • ✅ Performance optimized (lazy loading)
  • ✅ TypeScript support

Component location: src/components/analytics/google-analytics.tsx

Integration point: src/app/layout.tsx (root layout)

Tracking behavior:

  • Automatic: Page views are tracked on every route change
  • Manual events: Use gtag() function for custom event tracking

Custom event tracking example:

// In any client component
'use client';

import { useEffect } from 'react';

export function MyComponent() {
  const handleClick = () => {
    // Track custom event
    if (typeof window !== 'undefined' && window.gtag) {
      window.gtag('event', 'button_click', {
        button_name: 'cta_button',
        page_path: window.location.pathname,
      });
    }
  };

  return <button onClick={handleClick}>Click Me</button>;
}

TypeScript support:

// Add to your global.d.ts or env.d.ts
interface Window {
  gtag: (
    command: 'config' | 'event' | 'set',
    targetId: string,
    config?: Record<string, unknown>
  ) => void;
}

Microsoft Clarity

Clarity is integrated using Next.js's <Script> component with strategy="afterInteractive".

Key features:

  • ✅ Session recordings
  • ✅ Heatmaps (click, scroll, area)
  • ✅ No impact on page load performance
  • ✅ Privacy-focused (GDPR compliant)
  • ✅ Free forever

Component location: src/components/analytics/microsoft-clarity.tsx

Integration point: src/app/layout.tsx (root layout)

What Clarity tracks:

  • Mouse movements & clicks
  • Scroll behavior
  • Rage clicks (user frustration)
  • Page performance metrics
  • Dead clicks (clicks with no effect)

Privacy & GDPR Compliance

Legal disclaimer: Consult with legal counsel to ensure compliance with privacy laws in your jurisdiction.

Google Analytics

Data collected:

  • IP addresses (can be anonymized)
  • User agent strings
  • Page URLs
  • Referrer information
  • User interactions

GDPR considerations:

  • Enable IP anonymization: Add anonymize_ip: true in GA4 settings
  • Update your Privacy Policy
  • Consider cookie consent banner for EU users
  • Provide opt-out mechanism

IP Anonymization example:

// Modify google-analytics.tsx if needed
import { GoogleAnalytics as NextGoogleAnalytics } from "@next/third-parties/google";

export const GoogleAnalytics = () => {
  const gaId = process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID;
  if (!gaId) return null;

  return (
    <NextGoogleAnalytics 
      gaId={gaId}
      dataLayerName="dataLayer"
    />
  );
};

Microsoft Clarity

Data collected:

  • Session recordings (visual representation)
  • Mouse movements
  • Scroll depth
  • Click patterns

GDPR considerations:

  • Clarity automatically masks sensitive data (passwords, credit cards)
  • Can configure additional masking via Clarity dashboard
  • No personally identifiable information (PII) is stored by default
  • Update Privacy Policy to mention session recording

Testing & Debugging

Verify Google Analytics

1. Real-time reports:

  • Go to GA4 dashboard → Reports → Realtime
  • Open your app in a new tab
  • You should see your session appear in real-time

2. Browser DevTools:

// Check if gtag is loaded (in browser console)
console.log(typeof window.gtag); // Should output "function"

// Manually trigger test event
window.gtag('event', 'test_event', { test: 'value' });

3. Chrome Extension:


Verify Microsoft Clarity

1. Clarity Dashboard:

  • Go to Clarity Dashboard
  • Select your project
  • Check "Recordings" tab (data appears within minutes)

2. Browser DevTools:

// Check if Clarity is loaded (in browser console)
console.log(typeof window.clarity); // Should output "function"

// Check Clarity queue
console.log(window.clarity?.q);

3. Network Tab:

  • Open DevTools → Network tab
  • Filter by "clarity.ms"
  • You should see requests to Clarity's tracking endpoint

Environment-Specific Configuration

Development vs Production

Development (.env.local):

# Optional: Use test/development tracking IDs
NEXT_PUBLIC_GA_MEASUREMENT_ID="G-DEV123TEST"
NEXT_PUBLIC_CLARITY_PROJECT_ID="devtestproject"

Production (Vercel/hosting platform):

# Use production tracking IDs
NEXT_PUBLIC_GA_MEASUREMENT_ID="G-PROD123REAL"
NEXT_PUBLIC_CLARITY_PROJECT_ID="prodproject"

Tip: Use separate tracking IDs for development and production to avoid polluting production analytics with development traffic.

Conditional Loading

Both integrations automatically check for environment variables and only load when IDs are present. No additional configuration needed!

// Built-in behavior (no changes needed)
export const GoogleAnalytics = () => {
  const gaId = process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID;
  if (!gaId) return null; // ✅ Won't load if not configured
  return <NextGoogleAnalytics gaId={gaId} />;
};

Performance Impact

Google Analytics

  • Script size: ~28KB gzipped
  • Load strategy: Lazy loaded after page interactive
  • Performance score impact: < 1 point on Lighthouse
  • First Contentful Paint (FCP): No impact
  • Time to Interactive (TTI): Minimal (~50ms)

Microsoft Clarity

  • Script size: ~45KB gzipped
  • Load strategy: After interactive (strategy="afterInteractive")
  • Performance score impact: < 2 points on Lighthouse
  • First Contentful Paint (FCP): No impact
  • Time to Interactive (TTI): Minimal (~100ms)

Optimized: Both integrations use Next.js's built-in optimization strategies to minimize performance impact.


Advanced Usage

Custom Event Tracking (GA4)

Track specific user actions:

'use client';

export function PricingCard() {
  const handlePurchase = (plan: string) => {
    // Track purchase intent
    window.gtag?.('event', 'begin_checkout', {
      currency: 'USD',
      value: 99.00,
      items: [{ item_id: plan, item_name: plan }],
    });
  };

  return <button onClick={() => handlePurchase('pro')}>Buy Pro</button>;
}

Clarity Custom Tags

Add custom tags to organize recordings:

'use client';

import { useEffect } from 'react';

export function DashboardPage() {
  useEffect(() => {
    // Tag sessions with custom metadata
    if (typeof window !== 'undefined' && window.clarity) {
      window.clarity('set', 'user_type', 'premium');
      window.clarity('set', 'feature', 'dashboard');
    }
  }, []);

  return <div>Dashboard content</div>;
}

Troubleshooting

Google Analytics Not Working

Problem: No data appearing in GA4 dashboard

Solutions:

  1. ✅ Verify NEXT_PUBLIC_GA_MEASUREMENT_ID is set correctly
  2. ✅ Check measurement ID format: G-XXXXXXXXXX
  3. ✅ Wait 24-48 hours for initial data (not real-time by default)
  4. ✅ Check GA4 → Admin → Data Streams → Ensure stream is active
  5. ✅ Verify requests in Network tab: Look for google-analytics.com/g/collect

Debug mode:

# Add to .env for verbose logging (development only)
NEXT_PUBLIC_GA_DEBUG=true

Microsoft Clarity Not Recording

Problem: No session recordings appearing

Solutions:

  1. ✅ Verify NEXT_PUBLIC_CLARITY_PROJECT_ID is correct
  2. ✅ Check project status in Clarity dashboard (must be active)
  3. ✅ Ensure project is set for the correct domain
  4. ✅ Disable ad blockers/privacy extensions (they may block Clarity)
  5. ✅ Check browser console for script errors

Common issues:

  • Ad blockers: Clarity may be blocked by privacy extensions
  • Content Security Policy: Ensure script-src allows clarity.ms
  • Same-origin errors: Make sure domain matches Clarity project settings

Best Practices

1. Use Separate Tracking IDs per Environment

# .env.local (development)
NEXT_PUBLIC_GA_MEASUREMENT_ID="G-DEV123"

# .env.production (production)
NEXT_PUBLIC_GA_MEASUREMENT_ID="G-PROD456"

2. Privacy First

  • ✅ Add analytics disclosure to Privacy Policy
  • ✅ Implement cookie consent banner for EU users
  • ✅ Enable IP anonymization in GA4
  • ✅ Configure Clarity data masking for sensitive fields

3. Monitor Performance

  • ✅ Regularly check Lighthouse scores
  • ✅ Use Next.js Analytics (Vercel) to monitor real-user metrics
  • ✅ Monitor Core Web Vitals impact

4. Test Before Production

  • ✅ Test analytics in staging environment first
  • ✅ Verify event tracking works as expected
  • ✅ Check that both platforms receive data correctly

Migration from Other Analytics

From Google Universal Analytics (UA)

Universal Analytics stopped processing data on July 1, 2023. Migrate to GA4 immediately.

Steps:

  1. Create new GA4 property in Google Analytics
  2. Update NEXT_PUBLIC_GA_MEASUREMENT_ID to GA4 measurement ID (starts with G-)
  3. Remove any old Universal Analytics tracking code (starts with UA-)

From PostHog

PostHog is already supported! See .env.example:

NEXT_PUBLIC_POSTHOG_KEY="your-posthog-key"
NEXT_PUBLIC_POSTHOG_HOST="https://app.posthog.com"

You can use PostHog alongside GA and Clarity.


Adding Other Analytics Platforms

Want to add another analytics platform? Follow this pattern:

Create Component

// src/components/analytics/my-analytics.tsx
import Script from "next/script";

export const MyAnalytics = () => {
  const trackingId = process.env.NEXT_PUBLIC_MY_ANALYTICS_ID;
  if (!trackingId) return null;

  return (
    <Script
      id="my-analytics"
      strategy="afterInteractive"
      src={`https://example.com/script.js?id=${trackingId}`}
    />
  );
};

Export from Index

// src/components/analytics/index.ts
export { MyAnalytics } from "./my-analytics";

Add to Layout

// src/app/layout.tsx
import { MyAnalytics } from "~/components/analytics";

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        <MyAnalytics />
      </body>
    </html>
  );
}

Update .env.example

# My Analytics (optional)
# NEXT_PUBLIC_MY_ANALYTICS_ID="your-tracking-id"

Further Reading


You're all set! Your analytics are now tracking user behavior and helping you make data-driven decisions. 🎉

On this page