|
| 1 | +# Mixpanel Integration Guide for Next.js Projects |
| 2 | + |
| 3 | +This guide explains how to integrate Mixpanel analytics with Session Replay functionality into a Next.js project using the App Router architecture. |
| 4 | + |
| 5 | +## Overview |
| 6 | + |
| 7 | +This integration provides: |
| 8 | +- **Analytics tracking** for user events and page views |
| 9 | +- **Session Replay** to record and review user interactions |
| 10 | +- **Automatic page view tracking** when users navigate |
| 11 | +- **Client-side implementation** compatible with static site generation |
| 12 | + |
| 13 | +## Installation |
| 14 | + |
| 15 | +Install the Mixpanel browser package: |
| 16 | + |
| 17 | +```bash |
| 18 | +npm install mixpanel-browser |
| 19 | +``` |
| 20 | + |
| 21 | +## File Structure |
| 22 | + |
| 23 | +``` |
| 24 | +src/ |
| 25 | +├── lib/ |
| 26 | +│ └── mixpanelClient.js # Mixpanel configuration and initialization |
| 27 | +└── components/ |
| 28 | + └── MixpanelProvider.jsx # Provider component for app-wide integration |
| 29 | +``` |
| 30 | + |
| 31 | +## Implementation |
| 32 | + |
| 33 | +### 1. Create Mixpanel Client Configuration |
| 34 | + |
| 35 | +Create `src/lib/mixpanelClient.js`: |
| 36 | + |
| 37 | +```javascript |
| 38 | +import mixpanel from 'mixpanel-browser'; |
| 39 | + |
| 40 | +// Replace with your Mixpanel project token |
| 41 | +const MIXPANEL_TOKEN = 'your_mixpanel_project_token_here'; |
| 42 | + |
| 43 | +/** |
| 44 | + * Initialize Mixpanel with Session Replay configuration |
| 45 | + * - Session Replay records user interactions for later review |
| 46 | + * - Configured for optimal recording with privacy considerations |
| 47 | + */ |
| 48 | +export const initMixpanel = () => { |
| 49 | + mixpanel.init(MIXPANEL_TOKEN, { |
| 50 | + // Automatically track page views |
| 51 | + track_pageview: true, |
| 52 | + |
| 53 | + // Storage configuration |
| 54 | + persistence: 'localStorage', // Use 'cookie' for cross-subdomain tracking |
| 55 | + // cross_subdomain_cookie: true, // Uncomment if needed |
| 56 | + |
| 57 | + // Session Replay settings |
| 58 | + record_sessions_percent: 100, // Record 100% of sessions |
| 59 | + record_block_selector: "", // CSS selector for elements to block from recording |
| 60 | + record_mask_text_selector: ".sensitive-data", // Mask sensitive data |
| 61 | + record_collect_fonts: true, // Include font information |
| 62 | + record_idle_timeout_ms: 600000, // 10 minutes idle timeout |
| 63 | + record_min_ms: 3000, // Minimum session length to record |
| 64 | + }); |
| 65 | + |
| 66 | + // Make mixpanel available globally |
| 67 | + window.mixpanel = mixpanel; |
| 68 | + |
| 69 | + // Set flag for other scripts that depend on Mixpanel |
| 70 | + window.mixpanelLoaded = true; |
| 71 | +}; |
| 72 | + |
| 73 | +/** |
| 74 | + * Export mixpanel instance for direct use in components |
| 75 | + */ |
| 76 | +export default mixpanel; |
| 77 | +``` |
| 78 | + |
| 79 | +### 2. Create Mixpanel Provider Component |
| 80 | + |
| 81 | +Create `src/components/MixpanelProvider.jsx`: |
| 82 | + |
| 83 | +```javascript |
| 84 | +'use client'; |
| 85 | + |
| 86 | +import { useEffect } from 'react'; |
| 87 | +import { usePathname } from 'next/navigation'; |
| 88 | +import { initMixpanel } from '@/lib/mixpanelClient'; |
| 89 | +import mixpanel from '@/lib/mixpanelClient'; |
| 90 | + |
| 91 | +/** |
| 92 | + * Client component that initializes Mixpanel and tracks page navigation |
| 93 | + * Must be a client component due to browser-specific APIs |
| 94 | + */ |
| 95 | +export default function MixpanelProvider() { |
| 96 | + const pathname = usePathname(); |
| 97 | + |
| 98 | + // Initialize Mixpanel once when component mounts |
| 99 | + useEffect(() => { |
| 100 | + console.log('Initializing Mixpanel with Session Replay...'); |
| 101 | + initMixpanel(); |
| 102 | + }, []); |
| 103 | + |
| 104 | + // Track page views when pathname changes |
| 105 | + useEffect(() => { |
| 106 | + if (pathname) { |
| 107 | + mixpanel.track('Page View', { |
| 108 | + url: pathname, |
| 109 | + page: pathname |
| 110 | + }); |
| 111 | + } |
| 112 | + }, [pathname]); |
| 113 | + |
| 114 | + // This component doesn't render any UI |
| 115 | + return null; |
| 116 | +} |
| 117 | +``` |
| 118 | + |
| 119 | +### 3. Add Provider to Your App |
| 120 | + |
| 121 | +In your root layout (`src/app/layout.js` or `src/app/layout.jsx`): |
| 122 | + |
| 123 | +```javascript |
| 124 | +import MixpanelProvider from '@/components/MixpanelProvider'; |
| 125 | + |
| 126 | +export default function RootLayout({ children }) { |
| 127 | + return ( |
| 128 | + <html lang="en"> |
| 129 | + <body> |
| 130 | + {/* Add Mixpanel provider at the top level */} |
| 131 | + <MixpanelProvider /> |
| 132 | + {children} |
| 133 | + </body> |
| 134 | + </html> |
| 135 | + ); |
| 136 | +} |
| 137 | +``` |
| 138 | + |
| 139 | +## Usage Examples |
| 140 | + |
| 141 | +### Track Custom Events |
| 142 | + |
| 143 | +In any component, import and use mixpanel directly: |
| 144 | + |
| 145 | +```javascript |
| 146 | +import mixpanel from '@/lib/mixpanelClient'; |
| 147 | + |
| 148 | +export default function MyComponent() { |
| 149 | + const handleButtonClick = () => { |
| 150 | + // Track custom events |
| 151 | + mixpanel.track('Button Click', { |
| 152 | + button_name: 'signup', |
| 153 | + page: 'homepage' |
| 154 | + }); |
| 155 | + }; |
| 156 | + |
| 157 | + return ( |
| 158 | + <button onClick={handleButtonClick}> |
| 159 | + Sign Up |
| 160 | + </button> |
| 161 | + ); |
| 162 | +} |
| 163 | +``` |
| 164 | + |
| 165 | +### Identify Users |
| 166 | + |
| 167 | +```javascript |
| 168 | +import mixpanel from '@/lib/mixpanelClient'; |
| 169 | + |
| 170 | +// When user logs in |
| 171 | +mixpanel.identify('user_id_123'); |
| 172 | + |
| 173 | +// Set user properties |
| 174 | +mixpanel.people.set({ |
| 175 | + |
| 176 | + '$name': 'John Doe', |
| 177 | + 'plan_type': 'premium' |
| 178 | +}); |
| 179 | +``` |
| 180 | + |
| 181 | +### Track Form Submissions |
| 182 | + |
| 183 | +```javascript |
| 184 | +import mixpanel from '@/lib/mixpanelClient'; |
| 185 | + |
| 186 | +const handleFormSubmit = (formData) => { |
| 187 | + mixpanel.track('Form Submitted', { |
| 188 | + form_type: 'contact', |
| 189 | + fields_completed: Object.keys(formData).length |
| 190 | + }); |
| 191 | +}; |
| 192 | +``` |
| 193 | + |
| 194 | +## Configuration Options |
| 195 | + |
| 196 | +### Session Replay Settings |
| 197 | + |
| 198 | +| Option | Description | Default | |
| 199 | +|--------|-------------|---------| |
| 200 | +| `record_sessions_percent` | Percentage of sessions to record (0-100) | 100 | |
| 201 | +| `record_mask_text_selector` | CSS selector for elements to mask | ".sensitive-data" | |
| 202 | +| `record_block_selector` | CSS selector for elements to exclude | "" | |
| 203 | +| `record_collect_fonts` | Include font information in recordings | true | |
| 204 | +| `record_idle_timeout_ms` | Idle timeout before stopping recording | 600000 (10 min) | |
| 205 | +| `record_min_ms` | Minimum session length to save | 3000 (3 sec) | |
| 206 | + |
| 207 | +### Privacy Considerations |
| 208 | + |
| 209 | +To protect sensitive data: |
| 210 | + |
| 211 | +1. **Mask sensitive elements** by adding the `sensitive-data` class: |
| 212 | + ```html |
| 213 | + <input type="password" class="sensitive-data" /> |
| 214 | + <div class="sensitive-data">Credit card info</div> |
| 215 | + ``` |
| 216 | + |
| 217 | +2. **Block entire sections** by updating `record_block_selector`: |
| 218 | + ```javascript |
| 219 | + record_block_selector: ".private-section, .admin-panel" |
| 220 | + ``` |
| 221 | + |
| 222 | +3. **Reduce recording percentage** for production: |
| 223 | + ```javascript |
| 224 | + record_sessions_percent: 10 // Only record 10% of sessions |
| 225 | + ``` |
| 226 | + |
| 227 | +## Best Practices |
| 228 | + |
| 229 | +1. **Environment-based configuration**: Use environment variables for tokens: |
| 230 | + ```javascript |
| 231 | + const MIXPANEL_TOKEN = process.env.NEXT_PUBLIC_MIXPANEL_TOKEN; |
| 232 | + ``` |
| 233 | + |
| 234 | +2. **Conditional initialization**: Only initialize in production: |
| 235 | + ```javascript |
| 236 | + if (process.env.NODE_ENV === 'production') { |
| 237 | + initMixpanel(); |
| 238 | + } |
| 239 | + ``` |
| 240 | + |
| 241 | +3. **Error handling**: Wrap tracking calls in try-catch blocks: |
| 242 | + ```javascript |
| 243 | + try { |
| 244 | + mixpanel.track('Event Name', properties); |
| 245 | + } catch (error) { |
| 246 | + console.warn('Mixpanel tracking failed:', error); |
| 247 | + } |
| 248 | + ``` |
| 249 | + |
| 250 | +4. **Performance**: Initialize Mixpanel after critical app functionality loads |
| 251 | + |
| 252 | +## Troubleshooting |
| 253 | + |
| 254 | +### Common Issues |
| 255 | + |
| 256 | +1. **Build errors with useSearchParams**: This setup avoids `useSearchParams` to prevent build issues with static generation |
| 257 | + |
| 258 | +2. **Mixpanel not loading**: Check browser console for initialization logs and verify your project token |
| 259 | + |
| 260 | +3. **Events not appearing**: Ensure you're looking at the correct Mixpanel project and that events aren't being filtered |
| 261 | + |
| 262 | +### Debug Mode |
| 263 | + |
| 264 | +Enable debug mode during development: |
| 265 | + |
| 266 | +```javascript |
| 267 | +mixpanel.init(MIXPANEL_TOKEN, { |
| 268 | + debug: true, |
| 269 | + // ... other options |
| 270 | +}); |
| 271 | +``` |
| 272 | + |
| 273 | +## Getting Your Mixpanel Token |
| 274 | + |
| 275 | +1. Log in to your Mixpanel account |
| 276 | +2. Go to Settings → Project Settings |
| 277 | +3. Copy your Project Token |
| 278 | +4. Replace `your_mixpanel_project_token_here` in the configuration |
| 279 | + |
| 280 | +## Static Site Compatibility |
| 281 | + |
| 282 | +This implementation is fully compatible with Next.js static site generation (`output: 'export'`) since: |
| 283 | +- All Mixpanel functionality runs client-side |
| 284 | +- No server-side API routes are required |
| 285 | +- The provider component uses only client-side hooks |
| 286 | + |
| 287 | +--- |
| 288 | + |
| 289 | +This setup provides comprehensive analytics and session replay functionality while maintaining compatibility with static deployments and modern Next.js patterns. |
0 commit comments