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.astrocomponent only loads GA4 script in production - Measurement ID: G-LLMSLHNT7W configured via environment-aware component
Custom Event Tracking (src/utils/analytics.ts)
| Event | Category | Description |
|---|---|---|
assessment_start | engagement | User begins assessment form |
assessment_step_complete | engagement | Step completed with question ID and path |
assessment_submit | conversion | Form submitted with selected path |
cta_click | engagement | CTA button clicks with name and location |
scroll_depth | engagement | Milestones at 25%, 50%, 75%, 100% |
results_page_view | conversion | Results page viewed with assessment path |
case_study_click | engagement | Case study card interactions |
external_link_click | engagement | Outbound link tracking |
page_not_found | error | 404 page views with attempted path |
Environment Detection (src/utils/environment.ts)
Three-tier environment detection with priority order:
- Playwright marker (
window.__PLAYWRIGHT_TEST__) → test - Vitest (
process.env.VITEST) → test - 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.comrequests - 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 submissionHero.astro: CTA click trackingClosingCTA.astro: CTA click tracking with locationCaseStudyCard.astro: Case study click trackingBaseLayout.astro: Scroll depth and external link initializationResultsLayout.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