Google Analytics 4 (GA4) has been integrated into the grwm.dev website to track visitor behavior and engagement.
- Go to Google Analytics Admin
- Create a new property (if you don't have one)
- Copy your Measurement ID (format:
G-XXXXXXXXXX)
Add your tracking ID to .env.local:
VITE_GA_TRACKING_ID=G-XXXXXXXXXXNote: Replace G-XXXXXXXXXX with your actual tracking ID.
npm run devPage views are automatically tracked whenever users navigate to a different route. This is handled by the useGoogleAnalyticsPageView hook in the root route.
Track custom events anywhere in your components:
import { trackGAEvent } from '@/shared/hooks/useGoogleAnalytics'
const handleCtaClick = (): void => {
trackGAEvent('engagement', 'cta_button_click', 'homepage_hero', 1)
}
return <button onClick={handleCtaClick}>Get Started</button>Event Parameters:
category(required): Event category (e.g., 'engagement', 'form')action(required): Event action (e.g., 'click', 'submit')label(optional): Event label for more detailvalue(optional): Numeric value associated with the event
src/shared/hooks/useGoogleAnalytics.ts— GA initialization and tracking functionssrc/shared/hooks/useGoogleAnalytics.test.ts— Tests for GA hookssrc/router.tsx— GA initialization on app startupsrc/routes/__root.tsx— Page view tracking on route changes.env.example— Example environment variables.env.local— Local environment configuration (not committed to git)
- Initialization: When the app starts, the tracking ID is read from environment variables and GA is initialized
- Page Views: Every time the user navigates to a new route,
useGoogleAnalyticsPageViewsends a page view event with the current pathname - Custom Events: Components can use
trackGAEvent()to track specific user actions
GA functions are fully tested with mocked react-ga4:
npm run test:run -- useGoogleAnalytics- Ensure your privacy policy mentions Google Analytics
- Consider GDPR compliance if targeting EU users
- Configure Google Analytics to respect user consent settings
To debug GA in development:
- Install the Google Analytics Debugger Chrome Extension
- Open Chrome DevTools and check the Real-time view in Google Analytics
- Look for page views and events being logged
- Add consent banner — Implement a cookie consent banner to comply with privacy regulations
- Track form submissions — Add event tracking to CTA and contact form submissions
- Track video engagement — If you add video content, track play/pause events
- Track scroll depth — Measure how far users scroll on pages
- User ID tracking — Track authenticated users (if applicable)