Mixpanel Browser SDK
The `mixpanel-browser` library is the official JavaScript browser client for Mixpanel, enabling web applications to send analytics data, capture user events, perform session replay, manage feature flags, and track network telemetry. Currently at version 2.78.0, the library receives frequent updates, typically on a weekly or bi-weekly cadence, reflecting active development and the introduction of new features such as enhanced session recording capabilities (cross-origin iframe support, network recording, event-triggered recording), a refined masking API for sensitive data, and advanced autocapture options. Key differentiators include its comprehensive feature set for client-side analytics, robust session replay with masking and console recording, and a flexible module loading system allowing for optimized bundle sizes by excluding session recording components when not needed. It provides first-party TypeScript types and supports modern ESM import patterns.
Common errors
-
ReferenceError: mixpanel is not defined
cause The Mixpanel SDK script has not loaded, or the `mixpanel` object was not correctly imported or initialized before being accessed. This often happens if an `import` statement is missing or `mixpanel.init()` is called too late.fixEnsure that `import mixpanel from 'mixpanel-browser';` is at the top of your module and `mixpanel.init('YOUR_TOKEN');` is called before any other Mixpanel methods. If using a `<script>` tag, ensure it loads before your application code. -
TypeError: mixpanel.track is not a function
cause The `mixpanel` object might not be the correct instance or was not properly initialized. This can occur if a CommonJS `require` statement is used in a browser context where an ESM `import` is expected, or if `mixpanel.init()` failed.fixVerify that `import mixpanel from 'mixpanel-browser';` is correctly used and `mixpanel.init('YOUR_TOKEN');` has been successfully executed. Check the browser console for any earlier initialization errors. -
Module not found: Error: Can't resolve 'mixpanel-browser'
cause The `mixpanel-browser` package is not installed in the project's `node_modules` directory, or there's a typo in the import path.fixRun `npm install --save mixpanel-browser` or `yarn add mixpanel-browser` to install the package. Double-check the import statement for any spelling mistakes. -
CORS error (Cross-Origin Resource Sharing) when sending data to Mixpanel
cause This usually indicates an issue with your website's server configuration (e.g., if you're proxing requests) or if the Mixpanel API host does not match your project's data residency (US, EU, India).fixCheck your network requests in the browser's developer console for specific CORS error details. Ensure your `api_host` configuration matches your Mixpanel project's data residency (e.g., `api-eu.mixpanel.com` for EU). If using a proxy, verify its CORS configuration.
Warnings
- gotcha Client-side tracking with Mixpanel can be unreliable due to ad blockers or 'Do Not Track' browser settings, potentially leading to a loss of 30-50% of user events. Server-side tracking or using a proxy is recommended for improved reliability.
- breaking Session Replay for cross-origin iframes (introduced in v2.77.0) requires explicit domain allowlisting via the `record_allowed_iframe_origins` configuration option for security reasons. Without proper allowlisting, content from these iframes will not be captured. Both parent and child iframes need to specify allowed origins.
- breaking The Session Recording Masking API was updated in v2.74.0, introducing `record_mask_all_text` (defaulting to `true`) and `record_unmask_text_selector`. If your application previously relied on default unmasked text, it might now be masked, requiring explicit configuration to reveal specific elements.
- gotcha The `disable_persistence` option (enhanced in v2.69.0) now strictly prevents modification of `sessionStorage` and `IndexedDB`. If your application inadvertently relied on less strict persistence disabling, you might observe altered data storage behavior for device IDs and super properties.
- gotcha The `mixpanel-browser` package is distinct from the server-side `mixpanel` Node.js library. Confusing the two can lead to incorrect imports and unexpected behavior, especially concerning browser-specific features like session replay.
- gotcha The Network Recording plugin for Session Replay (v2.76.0) is in beta, and captured data will not appear in the Mixpanel UI until the feature is explicitly enabled within your Mixpanel project settings. Documentation for UI enablement is often separate from SDK release notes.
Install
-
npm install mixpanel-browser -
yarn add mixpanel-browser -
pnpm add mixpanel-browser
Imports
- mixpanel
const mixpanel = require('mixpanel-browser');import mixpanel from 'mixpanel-browser';
- mixpanel (core-only)
import mixpanel from 'mixpanel-browser/src/loaders/loader-module-core';
- mixpanel (async modules)
import mixpanel from 'mixpanel-browser/src/loaders/loader-module-with-async-modules';
- mixpanel.flags
mixpanel.flags.loadFlags();
Quickstart
import mixpanel from 'mixpanel-browser';
const MIXPANEL_TOKEN = process.env.MIXPANEL_TOKEN ?? 'YOUR_MIXPANEL_PROJECT_TOKEN';
// Initialize Mixpanel with autocapture, session recording, and debug mode
mixpanel.init(MIXPANEL_TOKEN, {
autocapture: true, // Automatically track common user interactions
track_pageview: true, // Automatically track page views
record_sessions_percent: 100, // Record 100% of user sessions for replay
record_heatmap_data: true, // Enable heatmap, rage click, and dead click collection
persistence: 'localStorage', // Use localStorage for more reliable persistence than cookies
debug: true, // Enable debug logs in the console
// Example of cross-origin iframe recording allowlist for security (since v2.77.0)
// record_allowed_iframe_origins: ['https://embedded-widget.example.com'],
});
// Identify a user after they log in or sign up
mixpanel.identify('USER_ID_123', {
name: 'John Doe',
email: 'john.doe@example.com',
plan: 'Enterprise'
});
// Track a custom event with properties
mixpanel.track('Signed Up', {
'Signup Type': 'Referral',
'Source Page': '/pricing'
});
// Track a page view explicitly (if not using track_pageview: true in init)
// mixpanel.track('Page View', {
// 'Page Title': document.title,
// 'Page URL': window.location.href
// });
// Set or update user profile properties
mixpanel.people.set({
'$last_login': new Date().toISOString(),
'Subscription Status': 'Active'
});
// Example of using feature flags (requires feature flags configured in Mixpanel)
mixpanel.flags.whenReady().then(() => {
if (mixpanel.flags.enabled('new-feature-flag')) {
console.log('New feature is enabled for this user!');
} else {
console.log('New feature is NOT enabled for this user.');
}
});