⚛️
React & Next.js Analytics
Complete guide to analytics for React applications and Next.js sites
Popular Solutions
Google Analytics 4
Easy Setup
Standard web analytics with React integration via gtag or react-ga4.
Free
Mixpanel
Medium Setup
Event-based analytics perfect for tracking user interactions in React apps.
Free / $25+/month
Developer-Friendly
Plausible Analytics
Easy Setup
Privacy-focused, lightweight analytics with simple script integration.
$9+/month
Fathom Analytics
Easy Setup
Simple, privacy-focused analytics without cookies or personal data.
$14+/month
PostHog
Medium Setup
Open-source product analytics with feature flags and A/B testing.
Free / $0.00045/event
Advanced Solutions
Segment
Medium Setup
Customer data platform with React SDK for unified analytics.
$120+/month
Amplitude
Medium Setup
Digital optimization platform with React SDK and advanced analytics.
Free / $61+/month
Adobe Analytics
Advanced Setup
Enterprise analytics with custom implementation for React apps.
Enterprise pricing
Implementation Examples
Google Analytics 4 with Next.js
// pages/_app.js
import { useEffect } from 'react'
import { useRouter } from 'next/router'
import Script from 'next/script'
const GA_TRACKING_ID = 'G-XXXXXXXXXX'
function MyApp({ Component, pageProps }) {
const router = useRouter()
useEffect(() => {
const handleRouteChange = (url) => {
gtag('config', GA_TRACKING_ID, {
page_path: url,
})
}
router.events.on('routeChangeComplete', handleRouteChange)
return () => {
router.events.off('routeChangeComplete', handleRouteChange)
}
}, [router.events])
return (
<>
<Script
src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
strategy="afterInteractive"
/>
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_TRACKING_ID}');
`}
</Script>
<Component {...pageProps} />
</>
)
}Mixpanel with React
// utils/analytics.js
import mixpanel from 'mixpanel-browser'
mixpanel.init('YOUR_PROJECT_TOKEN')
export const trackEvent = (eventName, properties = {}) => {
mixpanel.track(eventName, properties)
}
// Component usage
import { trackEvent } from '../utils/analytics'
function ProductCard({ product }) {
const handleAddToCart = () => {
trackEvent('Product Added to Cart', {
product_id: product.id,
product_name: product.name,
price: product.price,
category: product.category
})
// Add to cart logic
}
return (
<button onClick={handleAddToCart}>
Add to Cart
</button>
)
}React-Specific Analytics Patterns
🔄 Single Page Application (SPA) Tracking
- Challenge: Route changes don't trigger page views
- Solution: Track route changes with useEffect and useRouter
- Tools: All analytics tools need custom route tracking
- Implementation: Listen to router events and send page views
📊 Component-Level Event Tracking
- Pattern: Track interactions within React components
- Events: Button clicks, form submissions, modal opens
- Best Practice: Create reusable tracking hooks
- Context: Use React Context for analytics provider
⚡ Performance Tracking
- Metrics: Component render times, bundle size
- Tools: React DevTools, Web Vitals API
- Tracking: useEffect with performance.now()
- Optimization: Code splitting and lazy loading metrics
🎯 User Journey Tracking
- Flow: Track multi-step processes and funnels
- State: Use Redux or Context for journey state
- Events: Step completion, abandonment, errors
- Analysis: Identify drop-off points and optimize
React Analytics Best Practices
🏗️ Architecture & Setup
- • Create a centralized analytics service/hook
- • Use environment variables for tracking IDs
- • Implement analytics as a React Context provider
- • Load analytics scripts with Next.js Script component
- • Use TypeScript for event tracking type safety
📈 Event Tracking
- • Track user interactions, not just page views
- • Use descriptive event names and consistent naming
- • Include relevant context in event properties
- • Track errors and exceptions with error boundaries
- • Implement funnel tracking for key user flows
⚡ Performance
- • Load analytics scripts asynchronously
- • Debounce rapid event tracking (scrolling, typing)
- • Use React.memo for analytics components
- • Batch events when possible to reduce network calls
- • Monitor bundle size impact of analytics libraries
🔒 Privacy & Compliance
- • Implement cookie consent before loading analytics
- • Use privacy-focused alternatives when possible
- • Anonymize or hash personal data before tracking
- • Respect Do Not Track browser settings
- • Provide opt-out mechanisms for users