{"id":11335,"library":"mixpanel-browser","title":"Mixpanel Browser SDK","description":"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.","status":"active","version":"2.78.0","language":"javascript","source_language":"en","source_url":"https://github.com/mixpanel/mixpanel-js","tags":["javascript","typescript"],"install":[{"cmd":"npm install mixpanel-browser","lang":"bash","label":"npm"},{"cmd":"yarn add mixpanel-browser","lang":"bash","label":"yarn"},{"cmd":"pnpm add mixpanel-browser","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"This is the primary import for the client-side Mixpanel SDK. While the package specifies Node.js engines, it is predominantly used in browser environments via bundlers. CommonJS `require` is generally incorrect for the browser-targeted build; use ESM `import` statements.","wrong":"const mixpanel = require('mixpanel-browser');","symbol":"mixpanel","correct":"import mixpanel from 'mixpanel-browser';"},{"note":"Use this specific path to import the core SDK without the `mixpanel-recorder` SDK. This is useful for reducing bundle size if session replay functionality is not required. The export is still the default `mixpanel` object.","symbol":"mixpanel (core-only)","correct":"import mixpanel from 'mixpanel-browser/src/loaders/loader-module-core';"},{"note":"This loader allows for asynchronously loading session recording and targeting bundles, which can help optimize initial page load performance.","symbol":"mixpanel (async modules)","correct":"import mixpanel from 'mixpanel-browser/src/loaders/loader-module-with-async-modules';"},{"note":"The `mixpanel.flags` object for Feature Flags is available directly on the `mixpanel` instance after initialization. TypeScript types for this subsystem were added in v2.72.0.","symbol":"mixpanel.flags","correct":"mixpanel.flags.loadFlags();"}],"quickstart":{"code":"import mixpanel from 'mixpanel-browser';\n\nconst MIXPANEL_TOKEN = process.env.MIXPANEL_TOKEN ?? 'YOUR_MIXPANEL_PROJECT_TOKEN';\n\n// Initialize Mixpanel with autocapture, session recording, and debug mode\nmixpanel.init(MIXPANEL_TOKEN, {\n  autocapture: true, // Automatically track common user interactions\n  track_pageview: true, // Automatically track page views\n  record_sessions_percent: 100, // Record 100% of user sessions for replay\n  record_heatmap_data: true, // Enable heatmap, rage click, and dead click collection\n  persistence: 'localStorage', // Use localStorage for more reliable persistence than cookies\n  debug: true, // Enable debug logs in the console\n  // Example of cross-origin iframe recording allowlist for security (since v2.77.0)\n  // record_allowed_iframe_origins: ['https://embedded-widget.example.com'],\n});\n\n// Identify a user after they log in or sign up\nmixpanel.identify('USER_ID_123', {\n  name: 'John Doe',\n  email: 'john.doe@example.com',\n  plan: 'Enterprise'\n});\n\n// Track a custom event with properties\nmixpanel.track('Signed Up', {\n  'Signup Type': 'Referral',\n  'Source Page': '/pricing'\n});\n\n// Track a page view explicitly (if not using track_pageview: true in init)\n// mixpanel.track('Page View', {\n//   'Page Title': document.title,\n//   'Page URL': window.location.href\n// });\n\n// Set or update user profile properties\nmixpanel.people.set({\n  '$last_login': new Date().toISOString(),\n  'Subscription Status': 'Active'\n});\n\n// Example of using feature flags (requires feature flags configured in Mixpanel)\nmixpanel.flags.whenReady().then(() => {\n  if (mixpanel.flags.enabled('new-feature-flag')) {\n    console.log('New feature is enabled for this user!');\n  } else {\n    console.log('New feature is NOT enabled for this user.');\n  }\n});","lang":"typescript","description":"Initializes Mixpanel with common configuration options, identifies a user, tracks a custom event, sets user profile properties, and demonstrates basic feature flag usage."},"warnings":[{"fix":"For critical events, consider implementing server-side tracking. For client-side tracking, investigate setting up a proxy server to mitigate ad blocker impact. Ensure users are informed about data collection as per privacy regulations.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"When initializing Mixpanel, configure `record_allowed_iframe_origins` with an array of allowed domain origins. Example: `mixpanel.init('YOUR_TOKEN', { record_sessions_percent: 100, record_allowed_iframe_origins: ['https://embedded-widget.example.com'] });`","message":"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.","severity":"breaking","affected_versions":">=2.77.0"},{"fix":"Review your session recording configuration. To unmask specific text elements, use `record_unmask_text_selector`. To disable global text masking, set `record_mask_all_text: false` (use with caution for sensitive data). Example: `mixpanel.init('TOKEN', { record_mask_all_text: true, record_unmask_text_selector: '.unmask-this-content' });`","message":"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.","severity":"breaking","affected_versions":">=2.74.0"},{"fix":"Ensure that `disable_persistence: true` is used only when genuinely intending to prevent *all* client-side storage by Mixpanel, understanding it disables features like anonymous-to-identified user tracking and super properties. Verify data flow and user identity stitching under this configuration.","message":"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.","severity":"gotcha","affected_versions":">=2.69.0"},{"fix":"Always use `mixpanel-browser` for client-side web applications and `mixpanel` (the Node.js package) for server-side implementations. Ensure correct import syntax (`import` for `mixpanel-browser`) and initialize with browser-appropriate configurations.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"No direct SDK fix required; acknowledge that visibility in the Mixpanel UI depends on backend enablement. Refer to Mixpanel's official documentation for instructions on enabling beta features in your project settings.","message":"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.","severity":"gotcha","affected_versions":">=2.76.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure 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.","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.","error":"ReferenceError: mixpanel is not defined"},{"fix":"Verify 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.","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.","error":"TypeError: mixpanel.track is not a function"},{"fix":"Run `npm install --save mixpanel-browser` or `yarn add mixpanel-browser` to install the package. Double-check the import statement for any spelling mistakes.","cause":"The `mixpanel-browser` package is not installed in the project's `node_modules` directory, or there's a typo in the import path.","error":"Module not found: Error: Can't resolve 'mixpanel-browser'"},{"fix":"Check 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.","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).","error":"CORS error (Cross-Origin Resource Sharing) when sending data to Mixpanel"}],"ecosystem":"npm"}