Getting Started

mParticle’s JavaScript SDK is a flexible tool for tracking user activity in JavaScript, whether in a standalone web app running in a browser, or as part of a native WebView.

The Quickstart on this page assumes you are incorporating the SDK into a standalone web app. See our native WebViews documentation for help instrumenting WebViews.

Quickstart

1. Create your API Key

To send data from a web browser to your mParticle account, you need an API key. In the mParticle dashboard, navigate to Setup > Inputs and select the Web platform. From here you will be able to create a key and secret. Note that the Javascript API only requires the Key.

2. Include the snippet in your project

Within the <head> tag of a development version of your app, paste the following snippet. Don’t forget to replace 'YOUR_API_KEY' with your own key.

<script type="text/javascript">
  (function (apiKey) {
      window.mParticle = window.mParticle || {};
      window.mParticle.eCommerce = { Cart: {} };
  
      window.mParticle.Identity = {};
      window.mParticle.config = window.mParticle.config || {
       isDevelopmentMode: true
     };
     window.mParticle.config.rq = [];
      window.mParticle.ready = function (f) {
          window.mParticle.config.rq.push(f);
      };
      function a(o,t){return function(){t&&(o=t+"."+o);var e=Array.prototype.slice.call(arguments);e.unshift(o),window.mParticle.config.rq.push(e)}}var x=["endSession","logError","logEvent","logForm","logLink","logPageView","setSessionAttribute","setAppName","setAppVersion","setOptOut","setPosition","startNewSession","startTrackingLocation","stopTrackingLocation"],y=["setCurrencyCode","logCheckout"],z=["login","logout","modify"];x.forEach(function(o){window.mParticle[o]=a(o)}),y.forEach(function(o){window.mParticle.eCommerce[o]=a(o,"eCommerce")}),z.forEach(function(o){window.mParticle.Identity[o]=a(o,"Identity")});
  
     var mp = document.createElement('script');
     mp.type = 'text/javascript';
     mp.async = true;
     mp.src = ('https:' == document.location.protocol ? 'https://jssdkcdns' : 'http://jssdkcdn') + '.mparticle.com/js/v2/' + apiKey + '/mparticle.js';
     var s = document.getElementsByTagName('script')[0];
     s.parentNode.insertBefore(mp, s);
  })('YOUR_API_KEY');
</script>

As soon as you load a page with this snippet, you should be able to see data arriving in your Live Stream:

If you don’t see data in the Live Stream after loading the page a few times, check that you’ve correctly copied your API Key, that your config object contains isDevelopmentMode: true.

3. Send simple event data

Once you’ve verified that your app is sending data to mParticle you can try logging a few simple events:

// Log the current page view
mParticle.logPageView("Home");

// Log an event when the user plays a video
var play = document.querySelector("#play")
play.onclick = function () {
  mParticle.logEvent('Play Video', mParticle.EventType.Navigation, {"video_title": "See Ibiza"})
}

See our detailed docs on event tracking, screen tracking and eCommerce for more details.

4. Identify logged-in users

So far, we’re able to track activity in your web app, but we can only identify the users behind that activity by a cookie. If your app has login functionality, you can pass identities to mParticle, so that you can more easily track individual users over time.

// When a user logs in, send known IDs to mParticle in a login request
var loginIdentityRequest = {
  userIdentities: {
    email:      'email@example.com',
    customerid: '123456'    
  }
}
mParticle.Identity.login(loginIdentityRequest);

// When a user logs out, let mParticle know to stop 
// attributing activity to the known user
var identityRequest = {
  userIdentities: {}
}
mParticle.Identity.logout(logoutIdentityRequest);

This is just a very basic example. Identifying users on the web is a complicated task, and mParticle’s IDSync features give you a lot of control over how you handle it. See our Identity documentation for more detail.

5. Set user attributes

You can tell mParticle about your users by setting user attributes. These user attributes can become part of data forwarded to partners or used to create audiences for targeting.

// Get the current user
var currentUser = mParticle.Identity.getCurrentUser();

// Set user attribute 'color_preference' to 'blue'
currentUser.setUserAttribute("color_preference","blue");

See our Identity documentation for more detail on users.

Advanced Setup

Configuration options

The mParticle.config object is used to specify options that the mParticle SDK will use when initializing.

An example configuration object is below.

window.mParticle.config = {
    rq: [],
    isDevelopmentMode: true,
    identifyRequest: {
        userIdentities: { email: 'email@example.com', customerid: '123456' }
    },
    identityCallback: myIdentityCallback,
    useNativeSdk: false,
    useCookieStorage: true,
    maxProducts: 10,
    appVersion: '1.0.0',
    sessionTimeout: 60,
    customFlags: {'SimpleReach.Title': 'title', 'SimpleReach.Url': 'url'}
}
Setting Type Default Description
rq array Ready Queue - An array that accepts functions to run after mParticle and any kits are initialized. Ignores anything that is not a function.
isDevelopmentMode bool false When isDevelopmentMode is true, the app is in development mode.
identifyRequest object none Object containing identities to include in initial Identity request
identityCallback function none Function to run on completion of Identity Request
useNativeSdk bool false An option to send events via XHR request to either the native SDK or the JS SDK when in a WebView.
useCookieStorage bool false Sets the persistence storage to cookies, instaead of localStorage (default).
maxProducts int 20 Max number of products allowed in the cart, any additional items will not be added. Cart must be cleared before adding additional products.
appVersion string Version of your application
sessionTimeout int 30 Time in minutes that a session will expire if the user remains inactive.
customFlags object Some integrations require custom flags on initialization. An example of a one integration that uses customFlags is SimpleReach, docs can be found here

In order to add functions to the readyQueue, call window.mParticle.ready() with a single function as its argument below where window.mParticle.ready is declared.

For example:

<script type="text/javascript">
    (function (apiKey) {
       ...
       window.mParticle.ready = function (f) {
           window.mParticle.config.rq.push(f);
       };
       window.mParticle.ready(function() {
           mParticle.logEvent('mParticle has been loaded!')
       });
       ...
    })('YOUR_API_KEY');
</script>

Console Logging

When in a development environment (mParticle.config.isDevelopmentMode = true), you will be able to view logs in the console.

Differences from Native SDKs

In addition to forwarding user data to mParticle, the JavaScript SDK is designed to interface directly with integration partner SDKs to forward data directly to the partner from the browser client, in order to take advantage of cookie data which can only be read by the cookie owner. This means that Web integrations often work a little differently from the corresponding Native app version. See Working with Web Data for more details.

Download Size

Our JavaScript SDK is designed to have the smallest possible impact on the performance of your web app. Assets are minified, gzipped, and are downloaded asynchronously. Ideally, the SDK is placed as high on the page as possible (for example, in the <head> tag) to ensure accurate tracking, though this is not strictly necessary and is up to your team. The size of the core SDK package is approximately 25KB. Your actual download size will change depending on how your project is configured. If download size is a concern for your web app, you can take the following steps:

  • Prune integrations that are no longer in active use. Almost all web integrations operate on the client. For example, if you enable the Braze integration, mParticle will automatically download the Braze SDK and invoke its methods automatically for you when you log events. The more integrations you enable, the larger your download will be.
  • Minimize your usage of the Data Filter. The JavaScript SDK needs to download your filter settings from mParticle in order to know which events and attributes to pass to integrations. Every event that you disable will result in a unique data filter object within the JavaScript SDK configuration. Wherever possible, fix data issues at the source and use the Data Filter only as a stopgap measure.

Upgrade to Version 2 of the SDK

Version 2 of the JavaScript SDK contains breaking changes from version 1.x, including new methods to support mParticle’s IDSync features and the deprecation of older methods for managing users. Ignore this section if you are using the mParticle SDK for the first time and don’t need to upgrade from an older version.

New JS Loading Snippet

Please use the snippet above on this page. Version 2 allows methods to be called on the SDK before the SDK has loaded. These methods get enqueued and replayed once the SDK loads. To enable this, the new snippet must be used.

New config options

It is now possible to provide an Identity Request and Identity Callback in your mParticle.config. These options handle the intial Identity Request made by the SDK on initialization. See Configure the SDK. Also, isSandbox has been deprecated in favor of ‘isDevelopmentMode’. Finally, isDebug has been deprecated on the config object as well. In order to view detailed logs in version 2, you can pass an options object as the second parameter into mParticle.init() with a key of ‘logLevel’ and a value of ‘verbose’, ie:

Identity and User Attributes

Previously, current user identities and attributes were set at the level of the browser and included with any outgoing batches. This approach has been deprecated in favor of more explicit user management via the Identity API. It is recommended that you include an Identity request when you initialize the SDK - if you do not, a request will automatically be sent containing only the Device Application Stamp. You should also update the current User Identity at appropriate points in your app lifecycle, such as Login and Logout.

onUserAlias

When transitioning from one user to another, usually as a previously anonymous user creates an account and becomes a known user, some Identity Strategies will alias the old anonymous profile to the new known one. Setting onUserAlias gives you the option to copy over attributes currently held in local storage to the new user profile.

getCurrentUser()

The setUserIdentity and setUserAttribute methods are deprecated as at version 2. Instead, the current user, as determined by the Identity API is exposed via mParticle.Identity.getCurrentUser(). The returned user object provides methods to check the MPID of the current user, modify the user’s Identity Record and get/set attributes.

Shopping Cart

The shopping cart is now maintained against the current user. See the eCommerce docs for details.

Upgrade Checklist

  • Create MParticleOptions object and pass it to startWithOptions in your initialization code.
  • If you are implementing an eCommerce strategy, implement an onUserAlias function.
  • Replace any instance of setUserIdentity with the appropriate Identity method.
  • Any methods affecting a user must now be called on your your current user object. Check the following methods:

    • setUserTag
    • removeUserTag
    • setUserAttribute
    • removeUserAttribute
    • setUserAttributeList
    • removeAllUserAttributes
    • getUserAttributesLists
    • getAllUserAttributes
  • Any methods accessing the cart must be called on the current user object.