Mixpanel JavaScript Browser Client Library

repository·master·Indexed 21 days ago

https://github.com/mixpanel/mixpanel-js

The official Mixpanel JavaScript library for sending user activity data from websites to Mixpanel projects. It supports client-side integration via NPM, browser modules, or direct script loading. The library includes features for event tracking, user identity management via alias and add_group, and integration with the OpenFeature Web SDK through the @mixpanel/openfeature-web-provider for managing feature flags, experiments, and dynamic configurations.

Tokens
17.1K
Snippets
79
Records
91
Agent score
73%

What's inside mixpanel-browser

  1. Set Evaluation Context and Runtime Properties

    master

    Context is used for flag evaluation.

    Important: Per-evaluation context (passing context as an argument to getBooleanValue, etc.) is not supported. You must set context globally using OpenFeature.setContext(). Setting context triggers a re-fetch of flag values from Mixpanel.

    Using Runtime Properties

    To use Mixpanel's Runtime Properties targeting rules, include a custom_properties key in your context. Values must be flat key-value pairs (no nested objects).

    await OpenFeature.setContext({
      email: 'user@example.com',
      plan: 'premium',
      custom_properties: {
        tier: 'enterprise',
        seats: 50,
        industry: 'technology'
      }
    });
  2. Understand Context Mapping and Identity

    master

    Context Mapping

    All properties in the OpenFeature EvaluationContext are passed directly to Mixpanel. There is no transformation or filtering.

    Note on targetingKey: Unlike other providers, targetingKey is not a special bucketing key in this provider. It is treated as a standard context property. Mixpanel's server-side configuration determines which properties are used for targeting and bucketing.

    User Identity

    This provider does not call mixpanel.identify(). You must manage user identity separately using the standard Mixpanel API. The provider will automatically use the current Mixpanel distinct_id for flag evaluations.

    // Manage identity through Mixpanel directly
    mixpanel.identify('user-123');
    
    // The provider will use Mixpanel's current distinct_id automatically
    const client = OpenFeature.getClient();
    const value = client.getBooleanValue('my-flag', false);
  3. How the `window._mixpanel()` interface works

    master

    Once the wrapper is loaded, it exposes a global method window._mixpanel(). This method acts as a pipe to the standard Mixpanel SDK commands.

    Command Syntax

    To execute a command, pass the command name as the first argument. If you need to target a specific Mixpanel library instance, prefix the command name with the library name and a dot (<library_name>.).

    General Pattern: window._mixpanel('<library_name.><command_name>', <parameters>)

    Example: Tracking an event with a custom library name:

    window._mixpanel(
        'myTracker.track', // Uses the library name "myTracker"
        'Add To Cart',     // Event name
        {product_id: 'shirt123'} // Optional event parameters
    );
    window._mixpanel(
        'myTracker.track',
        'Add To Cart',
        {product_id: 'shirt123'}
    );
  4. Integrate with React using @openfeature/react-sdk

    master

    You can use the @openfeature/react-sdk to consume flags reactively in React components.

    1. Initialize Mixpanel and the MixpanelProvider outside of your component tree.
    2. Wrap your application in the OpenFeatureProvider.
    3. Use hooks like useBooleanFlagValue within your components.
    import { OpenFeatureProvider, useBooleanFlagValue } from '@openfeature/react-sdk';
    import { OpenFeature } from '@openfeature/web-sdk';
    import mixpanel from 'mixpanel-browser';
    import { MixpanelProvider } from '@mixpanel/openfeature-web-provider';
    
    // Initialize outside of component
    mixpanel.init('YOUR_PROJECT_TOKEN', {
      flags: {
        context: { plan: 'premium' }
      }
    });
    const provider = new MixpanelProvider(mixpanel.flags);
    OpenFeature.setProvider(provider);
    
    function App() {
      return (
        <OpenFeatureProvider>
          <MyComponent />
        </OpenFeatureProvider>
      );
    }
    
    function MyComponent() {
      // Use the hook to get flag values reactively
      const showBanner = useBooleanFlagValue('show-banner', false);
    
      return (
        <div>
          {showBanner && <Banner message="Welcome to our new feature!" />}
        </div>
      );
    }
  5. Exclude mixpanel-recorder to reduce bundle size

    master

    The default mixpanel-browser bundle includes the mixpanel-recorder SDK (used for session replay). If you want to reduce your bundle size and do not need session recording, you can import specific loaders instead:

    Core SDK only (no session recording)

    Use this to load only the core SDK without any option of session recording:

    import mixpanel from 'mixpanel-browser/src/loaders/loader-module-core';

    Core SDK with asynchronous module loading

    Use this to load the core SDK and optionally load session recording and targeting bundles asynchronously via script tags:

    import mixpanel from 'mixpanel-browser/src/loaders/loader-module-with-async-modules';
  6. Quick Start: Integrate Mixpanel with OpenFeature

    master

    Follow these steps to initialize Mixpanel and register the MixpanelProvider with the OpenFeature SDK:

    1. Initialize Mixpanel: Pass the flags configuration object (including initial context) to mixpanel.init.
    2. Register Provider: Instantiate MixpanelProvider using mixpanel.flags and use OpenFeature.setProviderAndWait(provider) to ensure the provider is ready before evaluation.
    3. Evaluate Flags: Use OpenFeature.getClient() to get a client and call evaluation methods like getBooleanValue.
    import mixpanel from 'mixpanel-browser';
    import { OpenFeature } from '@openfeature/web-sdk';
    import { MixpanelProvider } from '@mixpanel/openfeature-web-provider';
    
    // 1. Initialize Mixpanel with feature flags and context
    mixpanel.init('YOUR_PROJECT_TOKEN', {
      flags: {
        context: {
          plan: 'premium'
        }
      }
    });
    
    // 2. Create and register the Mixpanel provider
    const provider = new MixpanelProvider(mixpanel.flags);
    await OpenFeature.setProviderAndWait(provider);
    
    // 3. Get a client and evaluate flags
    const client = OpenFeature.getClient();
    const showNewFeature = client.getBooleanValue('new-feature-flag', false);
    
    if (showNewFeature) {
      console.log('New feature is enabled!');
    }
  7. Use mixpanel-browser as a browser JavaScript module via importmap

    master

    If you are using native browser JavaScript modules, you can use an importmap to map the mixpanel-browser identifier to the Mixpanel CDN URL. This allows you to use standard import statements in your module files.

    <script type="importmap">
    {
      "imports": {
        "mixpanel-browser": "https://cdn.mxpnl.com/libs/mixpanel-js/dist/mixpanel.module.js"
      }
    }
    </script>
    <script type="module" src="main.js"></script>

    Then in your main.js:

    import mixpanel from 'mixpanel-browser';
    
    mixpanel.init('YOUR_TOKEN', {autocapture: true, debug: true, persistence: 'localStorage'});
  8. Install mixpanel-browser via NPM

    master

    To use Mixpanel in a project with a front-end packager like Vite or Webpack, install the mixpanel-browser package. Note that this package name is used to distinguish the client-side library from the server-side Node.js library (mixpanel).

    npm install --save mixpanel-browser
  9. Use the Mixpanel JavaScript SDK wrapper for Google Tag Manager

    master

    The Mixpanel JavaScript SDK wrapper provides a way to interact with the window.mixpanel interface from environments with restricted JavaScript capabilities, such as Google Tag Manager (GTM) custom templates. Because GTM's sandboxed JavaScript API restricts features like the new keyword or prototype, you must use this wrapper to communicate with the Mixpanel SDK.

    Deployment

    The wrapper is served via the Mixpanel CDN at: https://cdn.mxpnl.com/libs/mixpanel-js-wrapper.js

  10. Use the Mixpanel OpenFeature Provider

    master

    The MixpanelProvider allows you to use the standardized OpenFeature API to manage feature flags using Mixpanel as the backend. You can either wrap an existing Mixpanel instance or use the MixpanelProvider.create() static method to initialize a new one.

    To use it, register the provider with the OpenFeature SDK and then use the OpenFeature client to evaluate flags.

    import mixpanel from 'mixpanel-browser';
    import { OpenFeature } from '@openfeature/web-sdk';
    import { MixpanelProvider } from '@mixpanel/openfeature-web-provider';
    
    // Option 1: Initialize Mixpanel manually and wrap its flags
    mixpanel.init('TOKEN', {
      flags: {
        context: { plan: 'premium' }
      }
    });
    await OpenFeature.setProviderAndWait(new MixpanelProvider(mixpanel.flags));
    
    // Option 2: Use the static create method to initialize everything at once
    // const provider = MixpanelProvider.create('TOKEN', { /* config */ });
    // await OpenFeature.setProviderAndWait(provider);
    
    // Use flags via the OpenFeature client
    const client = OpenFeature.getClient();
    const showNewUI = client.getBooleanValue('new-ui', false);