DocsTracking MethodsSDKsJavascript

Mixpanel SDKs: Javascript

Getting Started

Please refer to our Quickstart Guide.

The Full API Reference, Library Source Code, and an Example Application is documented in our GitHub repo.

Installing the Library

The easiest way to install the library is to load it from our CDN to your website. Paste the following code snippet right before the closing </head> tag in your page HTML.

// Paste this right before your closing head tag
<script type="text/javascript">
(function (f, b) { if (!b.__SV) { var e, g, i, h; window.mixpanel = b; b._i = []; b.init = function (e, f, c) { function g(a, d) { var b = d.split("."); 2 == b.length && ((a = a[b[0]]), (d = b[1])); a[d] = function () { a.push([d].concat(Array.prototype.slice.call(arguments, 0))); }; } var a = b; "undefined" !== typeof c ? (a = b[c] = []) : (c = "mixpanel"); a.people = a.people || []; a.toString = function (a) { var d = "mixpanel"; "mixpanel" !== c && (d += "." + c); a || (d += " (stub)"); return d; }; a.people.toString = function () { return a.toString(1) + ".people (stub)"; }; i = "disable time_event track track_pageview track_links track_forms track_with_groups add_group set_group remove_group register register_once alias unregister identify name_tag set_config reset opt_in_tracking opt_out_tracking has_opted_in_tracking has_opted_out_tracking clear_opt_in_out_tracking start_batch_senders people.set people.set_once people.unset people.increment people.append people.union people.track_charge people.clear_charges people.delete_user people.remove".split( " "); for (h = 0; h < i.length; h++) g(a, i[h]); var j = "set set_once union unset remove delete".split(" "); a.get_group = function () { function b(c) { d[c] = function () { call2_args = arguments; call2 = [c].concat(Array.prototype.slice.call(call2_args, 0)); a.push([e, call2]); }; } for ( var d = {}, e = ["get_group"].concat( Array.prototype.slice.call(arguments, 0)), c = 0; c < j.length; c++) b(j[c]); return d; }; b._i.push([e, f, c]); }; b.__SV = 1.2; e = f.createElement("script"); e.type = "text/javascript"; e.async = !0; e.src = "undefined" !== typeof MIXPANEL_CUSTOM_LIB_URL ? MIXPANEL_CUSTOM_LIB_URL : "file:" === f.location.protocol && "//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js".match(/^\/\//) ? "https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js" : "//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js"; g = f.getElementsByTagName("script")[0]; g.parentNode.insertBefore(e, g); } })(document, window.mixpanel || []);
</script>

Afterward, create an instance of the Mixpanel object by calling .init() using your project token in your JS file. Any methods called from this object will target your project.

// Create an instance of the Mixpanel object
mixpanel.init('YOUR_PROJECT_TOKEN');

Library Configuration

The Mixpanel object can be initialized with different configurations. See a complete list of the configuration options and default values here.

You can override the default configuration using the config argument when initializing the library.

Example Usage

// create an instance of the Mixpanel object
mixpanel.init('YOUR_PROJECT_TOKEN', {
    persistence: 'localStorage',    // set persistence to local storage
    debug: true,                    // enable debug log in console
});

You can update the configuration after initialization using the .set_config method.

Example Usage

// create an instance of the Mixpanel object
mixpanel.init('YOUR_PROJECT_TOKEN', {
    debug: true,    // enable debug log in console
});
 
// disable debug log after initialization
mixpanel.set_config({
    debug: false
});
 
// debug is disabled

Sending Events

The Javascript SDK provides a few different methods to send event data to your project. Calling any of the event tracking methods below will generate an event payload, then trigger a request to the /track API endpoint to ingest the event into your project.

All events sent from the JavaScript library will be sent over HTTPS.

The /track endpoint will only validate events with timestamps within the last 5 days of the request. Events with timestamps older than 5 days will not be ingested. See below on best practices for historical imports.

Track Events

Once you initialized the Mixpanel object, call .track() to send an event by providing the event name and any event properties.

Example Usage

// Send a "Played song" event to Mixpanel
mixpanel.track("Played song",{
    "genre": "hip-hop"  // with an event property "genre" set to "hip-hop"
    }
);

Avoid using names containing $ or mp (e.g. $name, mp_country_code, etc.) as they are used by our reserved event properties which receive special treatment in our UI or are used for special processing.

Track Page Views

Page view tracking is turned off by default. Page view events can be added automatically on every page load by enabling the track_pageview config option when creating the Mixpanel object.

Example Usage

//create an instance of the Mixpanel object
mixpanel.init('YOUR_PROJECT_TOKEN', {
    track_pageview: true    // enable automatic pageview tracking
    });

The default track_pageview setting does not auto-track page views in single-page applications. For tracking dynamic page views in single-page applications, the track_pageview option can also accept the following values for tracking.

Example Usage

// Track when the path changes, ignoring any query string or hash changes
mixpanel.init('YOUR_PROJECT_TOKEN', {
    track_pageview: "url-with-path"
    });
 
// Track when the path or query string change, ignoring hash changes
mixpanel.init('YOUR_PROJECT_TOKEN', {
    track_pageview: "url-with-path-and-query-string"
    });
 
// Track any URL changes in the path, query string, or hash
mixpanel.init('YOUR_PROJECT_TOKEN', {
    track_pageview: "full-url"
    });

The default page view event has the event name ($mp_web_page_view), and includes the event properties page title (current_page_title), URL components (current_domain, current_url_path, current_url_protocol, current_url_search), and marketing parameters. Additional page view event properties can be added.

Example Usage

// Send a default page view event "$mp_web_page_view"
mixpanel.track_pageview();
 
// Send a default page view event with additional "page" property
mixpanel.track_pageview({
    "page": "Pricing"
    });

Track UTM Tags

The JavaScript library will automatically add any UTM parameters (utm_source, utm_campaign, utm_medium, utm_term, utm_content, utm_id, utm_source_platform, utm_campaign_id, utm_creative_format, utm_marketing_tactic) present on the page to events fired from that page load. Please note when configuring UTMs that UTM tracking is case sensitive, and should be formatted lower-case as shown in the examples above.

When UTM parameters for an identified user are seen for the first time, these will also be stored on the user profile as initial_utm_source, initial_utm_campaign, initial_utm_medium, initial_utm_term, initial_utm_content, initial_utm_id, initial_utm_source_platform, initial_utm_campaign_id, initial_utm_creative_format, and initial_utm_marketing_tactic.

In addition to UTM parameters, Mixpanel will also add any advertising click IDs to events fired. These include dclid, fbclid, gclid, ko_click_id, li_fat_id, msclkid, sccid, ttclid, twclid, wbraid.

Learn more about UTM tracking.

Note: UTM parameters are by default persisted as Super Properties. To disable this UTM persistence, use the SDK initialization option {stop_utm_persistence: true} (refer to our Release Notes in GitHub).

Other Tracking Methods

There are other less common methods for sending data to Mixpanel. Refer to the full API documentation.

Importing Historical Events

The Javascript SDK is a tracking SDK designed for real-time tracking in a client-side environment. Calling the .track() method triggers a request to our /track API endpoint, which will validate for events with a timestamp that is within the last 5 days of the request. Events older than 5 days will not be ingested.

For bulk import of historical events older than 5 days, we will need to use the /import API endpoint which is optimized for scripting and supports ingesting historical data. We recommend the Python SDK (see the .import_data() function) and mixpanel-utils module (see the import_events() function) which both leverages the /import API for event ingestion.

Setting Super Properties

Super properties are global event properties that you define once and apply to all events.

To register super properties, call .register().

Use .register_once() to register super properties without overwriting existing values.

Example Usage

// register "name" as a super property
mixpanel.register({
    name: 'Sam',
});
 
// register "city" as an additional super property
// ignore "name" since it already exists
mixpanel.register_once({
    name: 'Samantha',
    city: 'San Francisco'
});
 
// track a "registration" event
// the event will include the "name" property set to "Sam"
// and "city" set to "San Francisco"
mixpanel.track('registration');

Your super properties are stored in the cookie generated by the domain that is loading the library. They will persist for the life of that cookie, which by default is 365 days. If you wish to change the life of the cookie, adjust the cookie_expiration configuration.

Example Usage

// set cookie_expiration to 90 days upon initialization
mixpanel.init('YOUR_PROJECT_TOKEN', {
    'cookie_expiration': 90
});

Managing User Identity

You can handle the identity of a user using the .identify() and .reset() methods. Learn more about identity management and identifying users.

Identify

⚠️

We recommend against calling .identify() for anonymous visitors to your site.

Call .identify() when you know the identity of the current user, passing in their user ID as an argument. This is typically at account registration and at log in.

Example Usage

// your user signs in and tracks a sign in event
mixpanel.track('sign in');
 
// upon sign in, identify the user with their ID
// ensure future events sent from the user have distinct_id 12345
mixpanel.identify('12345');

Call Reset at Logout

Call .reset() to clear data attributed to a user when they logout. This will clear the cookie/local storage and allows you to handle multiple users on a single device.

Example Usage

// your user logs out and tracks a log out event
mixpanel.track('log out');
 
// generate new cookie with new distinct_id
mixpanel.reset();

Storing User Profiles

Once your users are identified, create user profiles by setting profile properties to describe them. Example profile properties include “name”, “email”, “company”, and any other demographic details about the user.

The Javascript SDK provides a few methods for setting profile properties under .people, which will trigger requests to the /engage API endpoint.

Setting Profile Properties

You must call .identify() before setting profile properties in order to associate the profile properties you set with the target user. If identify is not called, the profile update will be queued for ingestion until an identify call is made.

Set profile properties on a user profile by calling the .people.set() method.

If a profile property already exist, if will be overwritten with the latest value provided in the method. If a profile property does not exist, it will be added to the profile.

Example Usage

// You must call identify to associate the profile update with the user
// Create "plan" profile prop for user "12345"
mixpanel.identify('12345');
mixpanel.people.set({
    plan: 'Premium'
    });
 
// We only need to call identify once per page load
mixpanel.people.set({
    plan: 'Enterprise',   // Update "plan" from "Premium" to "Enterprise"
    company: 'mixpanel'  // Create new "company" profile prop
});

Other Types Of Profile Updates

There are a few other methods for setting profile properties. See a complete reference of the available methods here.

A few commonly used people methods are highlighted below:

The .people.set_once() method set profile properties only if they do not exist yet. If it is setting a profile property that already exists, it will be ignored.

Use this method if you want to set profile properties without the risk of overwriting existing data.

Example Usage

// set profile properties for user "1234"
mixpanel.identify('1234');
mixpanel.people.set({
    name: 'Sam',
});
 
// "name" will not be update since it already exists
// "email" will be added to profile
mixpanel.people.set_once({
    name: 'Samantha',
    email: 'sam@mail.com'
});

Group Analytics

Read more about Group Analytics before proceeding. You will need to have the group key defined in your project settings first.

Mixpanel Group Analytics is a paid add-on that allows behavioral data analysis by groups (e.g. company, team), as opposed to individual users.

A group is identified by the group_key and group_id.

  • group_key is the event property that connects event data to a group. (e.g. company)
  • group_id is the identifier for a specific group. (e.g. mixpanel,company_a,company_b, etc.)

The Javascript SDK provides a few method for adding individual users to a group and setting group profile properties.

Adding Users to a Group

All events must have the group key as an event property in order to be attributed to a group. Without the group key, an event cannot be attributed to a group.

Call the .set_group() method to register the current user to a group, which would add the group_key as an event property set to the group_id value to all events moving forward.

Alternatively, you can manually add the group key property to be more selective about which events to attribute to a group.

Example Usage

// assign the current user to the "mixpanel" company group
mixpanel.set_group('company', 'mixpanel');
 
// track "some_event"
// event property "company" = ["mixpanel"] is added automatically
mixpanel.track('some_event');
 
// alternatively you can manually set the group key on each event
mixpanel.track('some_event',{
    company: ['mixpanel']
});

Multiple Groups

An event can be attributed to multiple groups by passing in the group_key value as a list of multiple group_id values.

Call .add_group() to add additional group_id to an existing list.

Example Usage

// assign the current user to the "mixpanel" company group
// events will contain 'company' prop set to ["mixpanel"]
mixpanel.set_group('company', 'mixpanel');
 
// add "mp-us" as an additional company group
// new "company" value is ["mixpanel","mp-us"]
mixpanel.add_group('company', 'mp-us');
 
// track "some_event"
// event property "company" = ["mixpanel","mp-us"] is added automatically
mixpanel.track('some_event');

Adding Group Identifiers to User Profiles

To connect group information to a user profile, include the group_key and group_id as a user profile property using the people.set() call.

// set group key "company" as a user prop
// with group id "mixpanel" as value
mixpanel.people.set({"company":"mixpanel"})

Setting Group Profile Properties

Create a group profiles by setting group properties, similar to a user profile. For example, you may want to describe a company group with properties such as “ARR”, “employee_count”, and “subscription”.

To set group profile properties, specify the group that needs to be updated by calling .get_group(), then set the group properties by chaining the .set() method, which will trigger a request to the /groups API endpoint.

Example Usage

// assign the current user to the "mixpanel" company group
mixpanel.set_group('company', 'mixpanel');
 
// specify the target group using the group_key and group_id
// set "name", "features", and "employee_count" as group profile props
mixpanel.get_group('company','mixpanel').set({
    name: 'Mixpanel',
    features: ['reports','alerts','cohorts'],
    employee_count: 100
});

Other Group Profile Methods

There are a few other methods for setting group profile properties under .group.

A few commonly used group methods are highlighted below:

The .group.set_once() method set group profile properties only if they do not exist yet. If it is setting a profile property that already exists, it will be ignored.

Use this method if you want to set group profile properties without the risk of overwriting existing data.

Example Usage

// assign the current user to the "mixpanel" company group
mixpanel.set_group('company', 'mixpanel');
 
// set group profile properties
mixpanel.get_group('company','mixpanel').set({
    name: 'Mixpanel',
});
 
// ignore "name" since it already exists
// add "color" as a group profile prop
mixpanel.get_group('company','mixpanel').set_once({
    name: 'mp',
    color: 'purple'
});

Debug Mode

To enable debug mode, set the debug configuration option to true when initializing the Mixpanel object.

Example Usage

Remove this parameter before going into production.

// enable debug log in the console
mixpanel.init('YOUR_PROJECT_TOKEN', {
    debug: true
});

If you implemented using the HTML snippet, the mixpanel object is globally accessible and you can enable debug mode directly from the console by calling mixpanel.set_config({debug:true});.

Learn more about debugging.

Privacy-Friendly Tracking

You have control over the data you send to Mixpanel. The Javascript SDK provide methods to help you protect user data.

Learn more about Privacy.

Opt Out of Tracking

The Javascript SDK is initialized with tracking enabled by default. Use the .opt_out_tracking() method to opt the user out of data tracking and cookies/local storage for the current Mixpanel instance.

Example Usage

//send "some_event"
mixpanel.track('some_event');
 
// opt user out of tracking
// SDK is prevented from sending any data
mixpanel.opt_out_tracking();
 
// this track call will not work
mixpanel.track('some_other_event');

Opt Out by Default

You can initialize the library with users opted out of tracking by default using the opt_out_tracking_by_default configuration. Once the user is ready to be tracked, call .opt_in_tracking() to start tracking.

Example Usage

// create an instance of the Mixpanel object
// users are opted out of tracking by default
mixpanel.init('YOUR_PROJECT_TOKEN', {
    opt_out_tracking_by_default: true
    });
 
// this track call will not work
mixpanel.track('some_event');
 
//opt user in to tracking
mixpanel.opt_in_tracking();
 
// send "some_other_event"
mixpanel.track('some_other_event');

EU Data Residency

Route data to Mixpanel’s EU servers by setting a api_host configuration when creating the Mixpanel object.

Learn more about EU Data Residency.

Example Usage

// create an instance of the Mixpanel object
// route requests to Mixpanel's EU servers
mixpanel.init('YOUR_PROJECT_TOKEN', {
    api_host: 'https://api-eu.mixpanel.com',
});

India Data Residency

Route data to Mixpanel’s India servers by setting a api_host configuration when creating the Mixpanel object.

Learn more about India Data Residency.

Example Usage

// create an instance of the Mixpanel object
// route requests to Mixpanel's India servers
mixpanel.init('YOUR_PROJECT_TOKEN', {
    api_host: 'https://api-in.mixpanel.com',
});

Disable Geolocation

The Javascript SDK parse the request IP address to generate geolocation properties for events and profiles. To disable geolocation, set the ip to false when initializing the library.

Learn more about geolocation.

Example Usage

//create an instance of the Mixpanel object
// disable IP address for geolocation parsing
mixpanel.init('YOUR_PROJECT_TOKEN', {
    ip: false
});

Disable Default Properties

To disable default properties from being tracked, add them to the property_blacklist config flag when initializing the library.

Example Usage

//create an instance of the Mixpanel object
// stop setting the $os and $browser event properties
mixpanel.init('YOUR_PROJECT_TOKEN', {
    property_blacklist: ['$browser','$os']
});

By default, Mixpanel cookies send over HTTPS requests as part of the headers. However, Mixpanel’s JavaScript library provides a configuration to completely prevent the browser from transmitting your cookies with non-HTTPS requests.

To enable this, set the secure_cookie configuration from the default value of false to true.

Example Usage

// create an instance of the Mixpanel object
mixpanel.init('YOUR_PROJECT_TOKEN', {
    'secure_cookie': true   // prevent transmitting cookie with non-HTTPs requests
});

If you configure your instance to send data over HTTP (instead of HTTPS) but set secure_cookie: true, then your cookie data will not sent to the server.

Hosted Subdomains

By default, Mixpanel cookie works across subdomain, keeping Mixpanel’s Distinct ID and Super Properties consistent across your sub-domains. For hosted subdomains (see complete list of affected domains) that don’t allow cross-subdomain cookies, disable cross-subdomain cookie by setting the cross_subdomain_cookie configuration option to false. Alternatively, you can also use a CNAME to change from yourdomain.hostapp.com to yourdomain.com.

Example Usage

// create an instance of the Mixpanel object
mixpanel.init('YOUR_PROJECT_TOKEN', {
    'cross_subdomain_cookie': false   // prevent cookie persistence across subdomains
});

Tracking Via Proxy

You can route events from Mixpanel’s SDKs via a proxy in your own domain, which can reduce the likelihood of ad-blockers impacting your tracking.

image

There are two steps: setting up a proxy server and pointing our JavaScript SDK at your server.

Step 1: Set up a proxy server

The simplest way is to use our sample nginx config. This config redirects any calls made to your proxy server to Mixpanel.

Step 2: Point our JavaScript SDK at your server

Add the following line before the Mixpanel JS snippet, replacing YOUR_PROXY_DOMAIN with your proxy server’s domain. This is not required if you use npm or yarn instead of the snippet:

const MIXPANEL_CUSTOM_LIB_URL = "https://<YOUR_PROXY_DOMAIN>/lib.min.js";

Add your proxy server to the mixpanel.init call:

//create an instance of the Mixpanel object
mixpanel.init('YOUR_PROJECT_TOKEN', {
    api_host: 'https://<YOUR_PROXY_DOMAIN>' // set the proxy server as the api_host
    });

Here’s a full code sample.

Session Replay

Session Replay is currently available as an add-on purchase for Enterprise plans.

Capture and replay data on how a user interacts with your application. Replay collection is disabled by default, and the Replay portion of the SDK will not be loaded into your application until specified. To use this feature, you must be on at least version 2.50.0 of our JavaScript SDK.

Before you enable Session Replay for a large audience, we recommend testing in a demo project, and starting in production with smaller sets of users or accounts, so that you can monitor performance and ensure your privacy rules align with company policies.

Sampling Method

The easiest way to begin capturing session replays is by sampling a subset of users, specified during initialization:

mixpanel.init(
    "<YOUR_PROJECT_TOKEN>", 
    {
        record_sessions_percent: 1  //records 1% of all sessions
    }
)

Start with a smaller percentage and tune to fit your analytics needs.

If you already have the JS SDK installed, this is the only code change you need to start capturing session replays.

Init Options

OptionDescriptionDefault
record_block_classCSS class name or regular expression for elements which will be replaced with an empty element of the same dimensions, blocking all contents.new RegExp('^(mp-block|fs-exclude|amp-block|rr-block|ph-no-capture)$')
(common industry block classes)
record_block_selectorCSS selector for elements which will be replaced with an empty element of the same dimensions, blocking all contents."img, video"
record_collect_fontsWhen true, Mixpanel will collect and store the fonts on your site to use in playback.false
record_idle_timeout_msDuration of inactivity in milliseconds before ending a contiguous replay. A new replay collection will start when active again.1800000
(30 minutes)
record_mask_text_classCSS class name or regular expression for elements that will have their text contents masked.new RegExp('^(mp-mask|fs-mask|amp-mask|rr-mask|ph-mask)$')
(common industry mask classes)
record_mask_text_selectorCSS selector for elements that will have their text contents masked."*"
record_max_msMaximum length of a single replay in milliseconds. Up to 24 hours is supported. Once a replay has reached the maximum length, a new one will begin.86400000
(24 hours)
record_min_msMinimum length of a single replay in milliseconds. Up to 8 seconds is supported. If a replay does not meet the minimum length, it will be discarded.0
(0 seconds)
record_sessions_percentPercentage of SDK initializations that will qualify for replay data capture. A value of “1” = 1%.0

Session Replay Methods

We give our customers full control to customize when and where they capture session replays.

Start capturing replay data

mixpanel.start_session_recording()

This will have no effect if replay data collection is in progress.

This is optional, and can be used primarily to programmatically start and stop recording, or exclude something specific from recording. We recommend using the sampling method detailed above unless you need to customize when you capture replay data.

Stop capturing replay data

mixpanel.stop_session_recording()

This will have no effect if there is no replay data collection in progress.

Get replay properties

Use this method to get properties used to identify a replay that is taking place. Add the properties from this method to any events sent to Mixpanel that are not coming from the SDK (e.g. from a CDP library).

If your Mixpanel Events are instrumented using the JavaScript SDK, these properties will automatically be added.

mixpanel.get_session_recording_properties()
// {$mp_replay_id: '19221397401184-063a51e0c3d58d-17525637-1d73c0-1919139740f185'}

Returns an empty object if there is no Replay in progress.

Example Scenarios

ScenarioGuidance
We have a sensitive screen we don’t want to captureWhen user is about to access the sensitive screen, call mixpanel.stop_session_recording(). To resume recording once they leave this screen, you can resume recording with mixpanel.start_session_recording()
We only want to record certain types of users (e.g. Free plan users only)Using your application code, determine if current user meets the criteria of users you wish to capture. If they do, then call mixpanel.start_session_recording() to force recording on
We only want to users utilizing certain featuresWhen user is about to access the feature you wish to capture replays for, call mixpanel.start_session_recording() to force recording on

Tips & Tricks While Implementing

  • Search for Session Recording Checkpoint events in your project, tracked as $mp_session_record. When you capture Mixpanel session replays, the SDK will automatically emit this default event. If you’ve implemented correctly, you should see these events appear.
  • Calling mixpanel.start_session_recording() in your website / application is a good test to see if it causes Session Recording Checkpoint event mentioned above to appear. If it does, and you’re still struggling to find replays for Users and Reports, your sampling rate may not be working, or may be set too low.
  • Check the home page for your project to see if there are any replays listed in the Latest Replays card.
  • If you’re still struggling to implement, submit a request to our Support team for more assistance.

Privacy

Mixpanel offers a privacy-first approach to Session Replay, including features such as data masking. Mixpanel’s Session Replay privacy controls were designed to assist customers in protecting end user privacy. Read more here.

User Data

The Mixpanel SDK will always mask all inputs. By default, all text on a page will also be masked unless a different record_mask_text_selector is specified.

Along with other data, the SDK respects all Do Not Track (DNT) settings as well as manual opt-out for any replay data.

Retention

User replays are stored for 30 days after the time of ingestion. There is no way to view a replay older than 30 days old.

Release History

See All Releases.

Was this page useful?