Analytics Integration

From Zero to Full Implementation

Microsoft Clarity • Google Analytics 4 • Google Tag Manager

Navigate: Space or | Overview: ESC | Fullscreen: F

🎯 What You'll Learn Today

Build a complete analytics system that tracks every meaningful user interaction

📚 Concepts

  • Why analytics matter for your product
  • Choosing the right analytics tools
  • Event tracking fundamentals
  • Custom properties and dimensions
  • Data pipeline architecture

🛠️ Implementation

  • Setting up Microsoft Clarity
  • Implementing Google Analytics 4
  • Configuring Google Tag Manager
  • Writing tracking utilities
  • Testing and debugging
📦 Repository: All code is from our working implementation at github.com/ChakshuGautam/telemetry-ga-clarity

Why Do We Need Analytics?

Without data, you're just another person with an opinion

❌ Without Analytics

  • "I think users like this feature"
  • "The checkout seems broken"
  • "Traffic feels lower lately"
  • "Users probably want X"

Decisions based on assumptions

✅ With Analytics

  • "87% of users engage with this feature"
  • "23% drop at payment (3.2s load)"
  • "2,341 DAU, down 5% WoW"
  • "Users who want X: 12 of 2,000"

Data-driven decisions

🔍

Part 1

Start with Microsoft Clarity

See exactly what your users are doing

What is Microsoft Clarity?

It's like having a camera on every user's screen
Watch exactly how users interact with your app

🎥 Features

  • Session Recordings
    Watch real user sessions
  • Heatmaps
    See where users click/scroll
  • Insights
    Rage clicks, dead clicks, errors

💰 Why Start Here?

  • 100% Free
    No credit card, no limits
  • 5 Minute Setup
    Just add one script
  • Instant Value
    See problems immediately
💡 Pro Tip: Install Clarity first to understand user behavior visually, then add GA4 for quantitative metrics

Setting Up Clarity in 3 Steps

1 Go to clarity.microsoft.com → Sign in → Create new project

2 Enter your website URL → Get your unique project ID

3 Add this script to your HTML <head>:

<script type="text/javascript">
  (function(c,l,a,r,i,t,y){
    c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
    t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
    y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
  })(window, document, "clarity", "script", "YOUR_PROJECT_ID");
</script>
Done! Clarity starts recording sessions immediately

Our Clarity Implementation

<!-- telemetry-demo/index.html -->
<script type="text/javascript">
  (function(c,l,a,r,i,t,y){
    c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
    t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
    y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
  })(window, document, "clarity", "script", "t1ori1zqey");
</script>
View in GitHub →

Key Points

  • Project ID: t1ori1zqey - unique to each project
  • Loads asynchronously - won't slow down your page
  • GDPR compliant - no cookies by default

Adding Custom Tags to Sessions

Why Custom Tags? Filter recordings by user type, feature usage, or any custom criteria
// src/utils/tracking.ts
export const trackClarityCustomEvent = (
  eventName: string,
  customTag?: Record<string, any>
) => {
  if (typeof window !== 'undefined' && window.clarity) {
    window.clarity('set', eventName, customTag);
    console.log('🔍 Clarity Event:', eventName, customTag);
  }
};
View in GitHub →
Example Use Cases:
  • Tag premium vs free users
  • Mark sessions with errors
  • Identify feature usage patterns

Real Example: Tracking Sign-ups

// src/pages/HomePage.tsx
const handleSignupClick = () => {
  // Send to Google Analytics
  trackGTMEvent('sign_up', {
    method: 'email',
    event_category: 'engagement',
  });
  
  // Tag this Clarity session
  trackClarityCustomEvent('SignupAttempt', { 
    page: 'home',
    method: 'email' 
  });
};
View in GitHub →

In Clarity Dashboard

Filter: SignupAttempt = true

→ See only users who tried to sign up

What You Learn

• What did they do before?

• Did they complete it?

• Where did they struggle?

📊

Part 2

Add Google Analytics 4

Measure everything with numbers

Why Add Google Analytics?

Clarity shows HOW users behave
GA4 shows HOW MANY and WHEN
Question Clarity Answer GA4 Answer
User confusion? Watch recording of rage clicks 15% drop-off at step 3
Feature popular? See heatmap of button 2,341 clicks this week (+12%)
Performance issue? User waiting on slow page Avg load: 3.2s (P95: 7.1s)
Together = Complete Picture: Visual behavior + Quantitative metrics

Three Ways to Implement GA4

1️⃣ Direct gtag.js

✅ Simple and direct | ❌ Code changes for updates

window.gtag('event', 'purchase', {...})

2️⃣ Google Tag Manager (Recommended)

✅ No-code updates | ✅ Marketing autonomy | ✅ Multiple tools

window.dataLayer.push({event: 'purchase', ...})

3️⃣ React-GA4 Library

✅ Type-safe | ✅ React hooks | ❌ Only for React

ReactGA.event('purchase', {...})
Our Approach: We use GTM + direct gtag for maximum flexibility

Setting Up Google Tag Manager

<!-- Add to <head> -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;
f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');</script>

<!-- Add after <body> -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>

Our Implementation

  • Container ID: GTM-MT9MWSLQ
  • Location: index.html lines 9-15 and 27-30
  • Creates global dataLayer array
View in GitHub →

Our Tracking Implementation

// src/utils/tracking.ts
export const trackGTMEvent = (
  eventName: string,
  parameters?: Record<string, any>
) => {
  if (typeof window !== 'undefined') {
    // Send to GTM via dataLayer
    if (window.dataLayer) {
      window.dataLayer.push({
        event: eventName,
        ...parameters
      });
      console.log('GTM Event:', eventName, parameters);
    }
    
    // Also send directly to GA4
    if (window.gtag) {
      window.gtag('event', eventName, parameters);
      console.log('GA4 Direct:', eventName, parameters);
    }
  }
};
View in GitHub →
🎯

Part 3

Custom Properties & Events

Turn raw data into business insights

Anatomy of a Good Event

{
  // What happened?
  event_name: "button_click",
  
  // Standard GA4 parameters
  event_category: "engagement",
  event_label: "hero_cta",
  value: 1,
  
  // Your custom properties
  button_text: "Get Started",
  page_section: "hero",
  user_type: "free",
  ab_test_variant: "variant_b",
  session_duration_seconds: 145
}
Rule of Thumb:
Events answer "what happened"
Properties answer "under what conditions"

Example: Enhanced Button Tracking

// src/pages/HomePage.tsx
const handleButtonClick = () => {
  const newCount = clickCount + 1;
  setClickCount(newCount);
  
  trackGTMEvent('button_click', {
    // Standard parameters
    event_category: 'engagement',
    event_label: 'home_page_button',
    value: newCount,
    
    // Custom business context
    button_text: 'Track Engagement Event',
    page_section: 'hero',
    click_count: newCount,
    session_duration: Math.floor((Date.now() - startTime) / 1000),
    viewport_width: window.innerWidth,
    is_mobile: window.innerWidth < 768
  });
};
View in GitHub →

Example: E-commerce Events

// src/pages/HomePage.tsx
trackGTMEvent('purchase', {
  // Standard GA4 e-commerce parameters
  transaction_id: `order_${Date.now()}`,
  value: 99.99,
  currency: 'USD',
  items: [{
    item_id: 'SKU123',
    item_name: 'Premium Plan',
    item_category: 'Subscription',
    price: 99.99,
    quantity: 1
  }],
  
  // Custom business properties
  payment_type: 'credit_card',
  coupon_code: 'SAVE20',
  is_first_purchase: true,
  referral_source: 'email_campaign',
  checkout_duration_seconds: 45
});
💡 Tip: GA4 automatically processes standard e-commerce parameters for built-in reports

The Power of Custom Properties

Without Custom Properties

"1,000 button clicks happened"

  • Basic event counts
  • Limited segmentation
  • No context

With Custom Properties

"Premium users on mobile clicked 3x more than free users on desktop"

  • User segmentation
  • Behavior patterns
  • Business insights
Real Example from Our Data:
"Users who see variant_b convert 23% better on mobile devices when session duration exceeds 2 minutes"
🛠️

Part 4

Implementation Patterns

Production-ready code patterns

Automatic Page View Tracking

// src/App.tsx
function AppContent() {
  const location = useLocation();
  
  useEffect(() => {
    const pageTitles: Record<string, string> = {
      '/': 'Home',
      '/about': 'About',
      '/custom-properties': 'Custom Properties'
    };
    
    const pageTitle = pageTitles[location.pathname] || 'Unknown';
    
    // Track page view with context
    trackPageView(location.pathname, pageTitle);
  }, [location]); // Runs on every route change
  
  return <Routes>...</Routes>;
}
View in GitHub →
Result: Every navigation is automatically tracked with page title and path

Production-Safe Implementation

export const safeTrackEvent = (
  eventName: string, 
  properties?: any
) => {
  try {
    // Check environment
    if (typeof window === 'undefined') return;
    
    // Check if scripts loaded
    if (!window.dataLayer && !window.gtag) {
      console.warn('Analytics not loaded');
      return;
    }
    
    // Send event
    trackGTMEvent(eventName, {
      ...properties,
      timestamp: new Date().toISOString(),
      page_url: window.location.href
    });
    
  } catch (error) {
    // Never break the app for analytics
    console.error('Tracking failed:', error);
  }
};
Key Principle: Analytics should never break user experience

Testing Your Implementation

🔍 Clarity Testing

  1. Install and browse your site
  2. Go to Clarity dashboard
  3. See sessions in real-time
  4. Check custom tags

📊 GA4 Testing

  1. Open GA4 DebugView
  2. Browse your site
  3. See events instantly
  4. Verify parameters

🛠️ Browser Console

// Check if loaded
console.log(window.dataLayer);  // GTM events
console.log(window.clarity);    // Clarity object
console.log(window.gtag);       // GA4 function

// Manual test
window.dataLayer.push({
  event: 'test_event',
  test_param: 'test_value'
});

Common Mistakes to Avoid

Mistake Problem Solution
Tracking before load Events lost Check if (window.gtag)
Too many properties GA4 limit: 25 per event Send only essential data
PII in events Privacy violations Hash/remove emails, names
No error handling App crashes Wrap in try-catch
Duplicate tracking Inflated metrics Centralize tracking calls
Remember: Test in development, verify in staging, monitor in production
🔗

Part 5

Data Pipeline & Analysis

From events to insights

Exporting to BigQuery

Setup Process

  1. GA4 Admin → BigQuery Links → Link
  2. Select Google Cloud Project
  3. Choose daily export (free) or streaming (paid)
  4. Data appears within 24 hours
-- Query your custom properties in BigQuery
SELECT 
  event_name,
  (SELECT value.string_value 
   FROM UNNEST(event_params) 
   WHERE key = 'button_text') as button_text,
  (SELECT value.int_value 
   FROM UNNEST(event_params) 
   WHERE key = 'click_count') as clicks,
  COUNT(*) as total_events
FROM `project.analytics_123456.events_*`
WHERE event_name = 'button_click'
  AND _TABLE_SUFFIX BETWEEN '20240101' AND '20240131'
GROUP BY event_name, button_text, clicks;
Power Move: Your custom properties become SQL-queryable columns!

Our Implementation Structure

telemetry-demo/
├── index.html                    # Analytics scripts
├── src/
│   ├── utils/
│   │   ├── tracking.ts          # Core tracking functions
│   │   └── tracking-comparison.ts # All approaches
│   ├── pages/
│   │   ├── HomePage.tsx         # Basic events
│   │   ├── AboutPage.tsx        # Content tracking
│   │   └── CustomPropertiesPage.tsx # Advanced examples
│   └── App.tsx                  # Route tracking
└── public/
    └── docs/                    # This presentation

Live Demo

Visit any page and open console to see events being tracked in real-time

Key Takeaways

1. Start Simple

Begin with Clarity for visual insights, then add GA4 for metrics

2. Track Everything Meaningful

If it affects business decisions, track it with proper context

3. Use Custom Properties

Transform generic events into specific business insights

4. Test Thoroughly

Use DebugView, console logs, and test environments

5. Never Break UX

Analytics should fail silently, not crash your app

Resources & Links

Thank You! 🙏

Questions?

Repository: github.com/ChakshuGautam/telemetry-ga-clarity

Contact: chakshu@samagragovernance.in

Press ESC for slide overview