Day 23: Analytics & Tracking

Overview

Implemented comprehensive Google Analytics 4 (GA4) tracking for shikadigital.co.jp with custom event tracking, environment-aware configuration, and E2E test isolation to ensure analytics never fire during automated testing.

Implementation Details

GA4 Integration

  • Conditional Loading: GoogleAnalytics.astro component only loads GA4 script in production
  • Measurement ID: G-LLMSLHNT7W configured via environment-aware component

Custom Event Tracking (src/utils/analytics.ts)

EventCategoryDescription
assessment_startengagementUser begins assessment form
assessment_step_completeengagementStep completed with question ID and path
assessment_submitconversionForm submitted with selected path
cta_clickengagementCTA button clicks with name and location
scroll_depthengagementMilestones at 25%, 50%, 75%, 100%
results_page_viewconversionResults page viewed with assessment path
case_study_clickengagementCase study card interactions
external_link_clickengagementOutbound link tracking
page_not_founderror404 page views with attempted path

Environment Detection (src/utils/environment.ts)

Three-tier environment detection with priority order:

  1. Playwright marker (window.__PLAYWRIGHT_TEST__) → test
  2. Vitest (process.env.VITEST) → test
  3. import.meta.env.MODE → production/development

Tracking only fires in production unless explicitly opted-in via PUBLIC_ENABLE_DEV_ANALYTICS=true.

E2E Test Isolation

Custom Playwright fixtures (src/__tests__/e2e/fixtures.ts) provide automatic analytics isolation:

  • Network blocking: Routes abort all google-analytics.com, googletagmanager.com, analytics.google.com requests
  • Runtime marker: Injects __PLAYWRIGHT_TEST__ flag before navigation
  • All test files updated to use custom fixtures instead of base @playwright/test

Components Updated

  • Assessment.tsx: Tracks start, step completion, and submission
  • Hero.astro: CTA click tracking
  • ClosingCTA.astro: CTA click tracking with location
  • CaseStudyCard.astro: Case study click tracking
  • BaseLayout.astro: Scroll depth and external link initialization
  • ResultsLayout.astro: Results page view tracking

Test Coverage

  • Unit tests: analytics.test.ts (258 lines) - All tracking functions
  • Property-based tests: analytics.property.test.ts - Guards and edge cases
  • Environment tests: environment.test.ts, environment.property.test.ts
  • E2E verification: analytics-blocking.spec.ts - Confirms no GA requests during tests

Key Bug Fixes

  • Prevented duplicate scroll tracking listeners on page transitions
  • Deferred submission tracking to avoid race conditions
  • Added memory leak protection with active handler cleanup