JavaScript

API Integration

Installing the Library

To start tracking with the Mixpanel JavaScript library, just paste the following code into the page you want to track inside the <head> and </head> tags. Make sure to change YOUR_TOKEN to your project token. You can find your project token in the settings dialog in the Mixpanel web application.

<!-- start Mixpanel --><script type="text/javascript">(function(c,a){if(!a.__SV){var b=window;try{var d,m,j,k=b.location,f=k.hash;d=function(a,b){return(m=a.match(RegExp(b+"=([^&]*)")))?m[1]:null};f&&d(f,"state")&&(j=JSON.parse(decodeURIComponent(d(f,"state"))),"mpeditor"===j.action&&(b.sessionStorage.setItem("_mpcehash",f),history.replaceState(j.desiredHash||"",c.title,k.pathname+k.search)))}catch(n){}var l,h;window.mixpanel=a;a._i=[];a.init=function(b,d,g){function c(b,i){var a=i.split(".");2==a.length&&(b=b[a[0]],i=a[1]);b[i]=function(){b.push([i].concat(Array.prototype.slice.call(arguments,
0)))}}var e=a;"undefined"!==typeof g?e=a[g]=[]:g="mixpanel";e.people=e.people||[];e.toString=function(b){var a="mixpanel";"mixpanel"!==g&&(a+="."+g);b||(a+=" (stub)");return a};e.people.toString=function(){return e.toString(1)+".people (stub)"};l="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 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<l.length;h++)c(e,l[h]);var f="set set_once union unset remove delete".split(" ");e.get_group=function(){function a(c){b[c]=function(){call2_args=arguments;call2=[c].concat(Array.prototype.slice.call(call2_args,0));e.push([d,call2])}}for(var b={},d=["get_group"].concat(Array.prototype.slice.call(arguments,0)),c=0;c<f.length;c++)a(f[c]);return b};a._i.push([b,d,g])};a.__SV=1.2;b=c.createElement("script");b.type="text/javascript";b.async=!0;b.src="undefined"!==typeof MIXPANEL_CUSTOM_LIB_URL?
MIXPANEL_CUSTOM_LIB_URL:"file:"===c.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";d=c.getElementsByTagName("script")[0];d.parentNode.insertBefore(b,d)}})(document,window.mixpanel||[]);
mixpanel.init("YOUR TOKEN");</script><!-- end Mixpanel -->

The snippet will load our library onto the page asynchronously to keep your website loading quickly even if placed in the <head> of the page.

The snippet provides a global variable named mixpanel that you can use to send data to the Mixpanel API.

Opting Users Out of Tracking

Client-side tracking of individual user data can be stopped or resumed by controlling a user’s opt-out/opt-in state. Opt-out methods and library configuration settings only affect data sent from a single library instance. Data sent from other sources to Mixpanel’s APIs will still be ingested regardless of whether the user is opted out locally.

The opt-out/opt-in state of a user is controlled by an opt-out flag that is set as a browser cookie or localStorage entry. If the value of the flag is true, then the user is opted-out and will not be tracked. If the opt-out flag is false, then the user is tracked. The flag is not set when the SDK is initialized, so the initial state is neither opted in nor opted out. Without the flag set, the user will be tracked by default.

To opt a user out of tracking locally, use the mixpanel.opt_out_tracking method. To resume tracking for an individual user, use mixpanel.opt_in_tracking. Call mixpanel.has_opted_out_tracking to check user’s opt-out status locally. By default, an "$opt_in" event is sent every time that a user opts in.

// Opt a user out of data collection
mixpanel.opt_out_tracking();

// Check a user's opt-out status 
// Returns true if user is opted out of tracking locally
mixpanel.has_opted_out_tracking();

Opting Users Out of Tracking by Default

Mixpanel’s tracking libraries will send user data by default. Explicitly initializing a default opt-out state of true will opt-out all users by default, preventing data from sending unless a user’s opt-out state is set to false. Mixpanel’s Javascript library also respects browser Do Not Track settings.

// Initializing a default opt-out state of true 
// will prevent data from being collected by default
mixpanel.init("YOUR TOKEN", {opt_out_tracking_by_default: true})

Delete Existing Data

Opting users out of tracking will stop any future tracking. This does not automatically delete data that has already been collected. Mixpanel's deletion API can be used to delete existing data.

Sending Events

Once you have the snippet in your page, you can track an event by calling mixpanel.track with the event name and properties.

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

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

Tracking Website Links

When tracking link clicks with mixpanel.track, the page can change before the event is successfully sent, leading to inaccurate results.

To make this easier, use mixpanel.track_links. This function will allow you to bind an event to a link click with much greater accuracy.

Here's how it works:

<div id="nav">
    <a href="/">Home</a>
    <a href="/about">About</a>
    <a href="/pricing">Pricing</a>
</div>
<script type="text/javascript">
    mixpanel.track_links("#nav a", "click nav link", {
        "referrer": document.referrer
    });
</script>

This will send a "click nav link" event (with a 'referrer' property) each time a user clicks on a navigation link. It's important to note that the links matched by the CSS selector must exist on the page at the time the mixpanel.track_links call is made, or it will not bind correctly.

Other Tracking Methods

There are other less common ways to send data to Mixpanel. To learn more, please follow the links to the full API documentation.

mixpanel.track_forms - similar to track_links, but tracks form submissions.

Mixpanel Cookie

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, use the set_config() method and change the secure_cookie flag from false to true. If you configure your instance to send data over HTTP instead of HTTPS, but do set secure_cookie: true, then your cookie data is not sent to the server.

Super Properties

It's very common to have certain properties that you want to include with each event you send. Generally, these are things you know about the user rather than about a specific event - for example, the user's age, gender, source, or initial referrer.

To make things easier, you can register these properties as super properties. If you tell us just once that these properties are important, we will automatically include them with all events sent. Super properties are stored in a browser cookie, and will persist between visits to your site.

To set super properties, call mixpanel.register.

<script type="text/javascript">
    mixpanel.register({
        "age": 28,
        "gender": "male",
        "source": "facebook"
    });
</script>

The next time you track an event, the super properties you just set will be included as properties. If you call

mixpanel.track("Signup");

after making the previous call to mixpanel.register, it is just like adding the properties directly:

mixpanel.track("Signup", {
    "age": 28,
    "gender": "male",
    "source": "facebook"
});

Setting Super Properties Only Once

If you want to store a super property only once (often for things like initial referrer, ad campaign, or source), you can use mixpanel.register_once. This function behaves like mixpanel.register and has the same interface, but it doesn't override super properties you've already saved.

<script type="text/javascript">
    mixpanel.register_once({
        "ad_campaign": "fb-01"
    });
</script>

This means that it's safe to call mixpanel.register_once with the same property on every page load, and it will only set it if the super property doesn't exist.

Super Properties Live in Local Storage

Our JS library uses a cookie (created in the domain of the page loading the lib) to store super properties. These are stored as JSON in the cookie. 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, you may do so using set_config to adjust the value for the cookie_expiration(an integer in days).

Group Analytics

Reach out to your Customer Success Manager or the Mixpanel Sales Team to enable Group Analytics in your reports.

Mixpanel Group Analytics allows behavioral data analysis by selected groups, as opposed to individual users.

Grouping by identifiers other than the distinct_id will allow analysis at a company or group level when using Mixpanel analytics. Read this article to learn more about Group Analytics.

A group is identified by the group_key and group_id.

  • group_key is the property that connects event data for Group Analytics.
  • group_id is the identifier for a specific group.

If the property “company” is chosen for Group Analytics, “company” is the group_key, and “Mixpanel”, “Company A”, and “13254” are all potential group_id values.

A user can belong to multiple groups. All updates to a group operate on the group_key and group_id.

Creating a Group Key

You must reach out to your CSM to determine what event property you will use for the group_key in Group Analytics.

Adding Users to a Group

Adding users to groups causes the group_key and group_id to send as a property key and value for all events triggered by that user on the device. You can add multiple values for a single user to the group_key list property.

Similar to a distinct_id, the group_key allows Mixpanel to group events by an identifier for analysis. A group_key, however, is a group level identifier and not a user level identifier like the distinct_id.

You can add users to groups by calling the set_group() method.

//Assign Company A and Company B to a user
mixpanel.set_group(“company”, [“Company A”, “Company B”])

You can call add_group() to add any additional groups to an existing list.

//Add “Mixpanel” to the list of existing groups
mixpanel.add_group(“company”, “Mixpanel”)

Creating Group Profiles

It is possible to create a Group profile that is similar to a people profile. You must call get_group().set() to build a group profile. It is important to the group_key, group_id, and one property so that the profile is not empty.

mixpanel.get_group(group_key, group_id).set({“property_name”: property_value})

Setting Group Profile Properties

You can add details to Groups by adding properties to them.

In order to update Group profile properties, you must specify the group that needs to be updated by calling get_group().

mixpanel.get_group(“company”, “Mixpanel”)

The get_group() method can be chained with other commands that edit properties specific to the group.

You can set the property $name to populate the name field at the top of the group profile.

These operations are similar to the corresponding operations for people property updates.

set

mixpanel.get_group().set() updates or adds a property to a group.

mixpanel.get_group(group_key, group_id).set({“property_name”: property_value})

set once

mixpanel.get_group().set_once() adds a property value to a group only if it has not been set before.

mixpanel.get_group(group_key, group_id).set_once({“property_name”: property_value})

unset

mixpanel.get_group().unset() unsets a specific property in the group.

mixpanel.get_group(group_key, group_id).unset(“property_name”)

remove

mixpanel.get_group().remove() removes a specific value in a list property.

mixpanel.get_group(group_key, group_id).remove(“property_name”, “property_value”)

union

mixpanel.get_group().union() adds the specified values to a list property and ensures that those values only appear once.

mixpanel.get_group(group_key, group_id).union(“property_name”, [property_value1,  [property_valueN])
                                                                
                                                                

Managing User Identity

The Mixpanel library will assign a default unique identifier (we call it "distinct_id") to each unique user who comes to your website. This distinct_id is saved as a cookie so that it will persist across sessions.

If you choose, you can assign your own user IDs. This is particularly useful if a user is using your app on multiple platforms (both web and mobile, for example). To assign your own distinct_ids, you can use mixpanel.identify.

// Associate all future events sent from
// the library with the distinct_id 13793
mixpanel.identify('13793');

In general, if you use mixpanel.identify, you should call it as soon as the user logs in to your application. This will track all of their actual application usage to the correct user ID.

NOTE

Calling mixpanel.identify with a new ID will change the ID being sent with future events. If you change the ID in the middle of a funnel, the funnel will break - we won't be able to associate the old ID with the new.

Combining Anonymous User Data with Identifiable User Data

There are moments when you want to link two IDs together. For example, users of your application may engage with your product anonymously before signing up. In which case, it would be nice to combine their anonymous activity and their activity once they're a customer. To do this, you would create an alias from the new user id in your system to the old anonymous one. You should use mixpanel.alias in conjunction with mixpanel.identify. The mixpanel.alias method sends an update to our server linking the current ID with a new ID going forward (not retroactively).

// This links the known ID 13793 in your database table
// to the anonymous auto-generated ID our library created.
mixpanel.alias('13793');

The recommended usage pattern is to call mixpanel.alias when the user signs up, and mixpanel.identify when they log in. This will keep your signup funnels working correctly. For more information, please see Using Alias and Identify.

NOTE

If you use mixpanel.alias you should only call it once during the lifetime of the user. Calling it more than once per user can create duplicate people profiles.

Call Reset at Logout

Reset generates a new random distinct_id and clears super properties. Call reset to clear data attributed to a user when that user logs out. This allows you to handle multiple users on a single device. For more information about maintaining user identity, see the Identity Management: Best Practices article.

Storing User Profiles

In addition to events, you can store user profiles in Mixpanel's People Analytics product. Profiles are persistent sets of properties that describe a user - things like name, email address, and signup date. You can use profiles to explore and segment users by who they are, rather than what they did. You can also use profiles to send messages, such as emails, SMS, push, or in-app messages.

NOTE

The Mixpanel library does not automatically create people profiles for any user that performs an event. In order to send profile updates, you must call mixpanel.identify in addition to mixpanel.people.set, which empowers you to create profiles for only the users of your choice.

Setting Profile Properties

You can set properties on a user profile with mixpanel.people.set.

mixpanel.people.set({ "Plan": "Premium" });

// identify must be called along with people.set
mixpanel.identify("13793");

This will set a "Plan" property, with a value "Premium", on user 13793's profile. If there isn't a profile with distinct_id 13793 in Mixpanel already, a new profile will be created. If user 13793 already has a property named "Plan" in their profile, the old value will be overwritten with "Premium".

Incrementing Numeric Properties

You can use mixpanel.people.increment to change the current value of numeric properties. This is useful when you want to keep a running tally of things, such as games played, messages sent, or points earned.

// If no number is passed, the default is to increment by 1
mixpanel.people.increment("games played");

// You can also pass a number to increment
// Here we add 500 to the user's point count
mixpanel.people.increment("points earned", 500);

// Pass an object to increment multiple properties
mixpanel.people.increment({
    "dollars spent": 17,
    // Subtract by passing a negative value
    "credits remaining": -34
});

Other Types Of Profile Updates

There are a few other types of profile updates. To learn more, please follow the links to the full API documentation.

Tracking Revenue

Mixpanel makes it easy to analyze the revenue you make from individual customers. By associating charges with user profiles, you can compare revenue across different customer segments and calculate things like lifetime value.

You can track a single transaction with mixpanel.people.track_charge. This call will add transactions to the individual user profile, which will also be reflected in the Mixpanel Revenue report.

// Make sure identify has been called
// before making revenue updates
mixpanel.identify("13793");

// Tracks $100 in revenue for user 13793
mixpanel.people.track_charge(100);

// Refund this user 50 dollars
mixpanel.people.track_charge(-50);

// Tracks $25 in revenue for user 13793
// on the 2nd of January at 9:45pm
mixpanel.people.track_charge(
    25,
    { '$time': "2013-01-02T21:45:00" }
);

In-App Messages

Mixpanel provides a quick start guide for web in-app messages to help you get integrated.

Make sure that you have already:

  1. Included the latest version of the Mixpanel JavaScript library on your website.
  2. Made sure you are identifying your users in your website's JavaScript code.
  3. Created a web in-app message on the Messages tab of the Mixpanel website.

JavaScript


API Integration

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.