Web

Getting Started

1. Integrate the SDK

In each page you want to track, include the following code at the end of the <head> section.

<script>
    + function(l, y, t, i, c, s) {
        l['LocalyticsGlobal'] = i;
        l[i] = function() {
            (l[i].q = l[i].q || []).push(arguments)
        };
        l[i].t = +new Date;
        (s = y.createElement(t)).type = 'text/javascript';
        s.src = '//web.localytics.com/v3/localytics.min.js';
        (c = y.getElementsByTagName(t)[0]).parentNode.insertBefore(s, c);
        ll('init', 'YOUR-LOCALYTICS-APP-KEY', {} /* Options */ );
    }(window, document, 'script', 'll');
</script>

2. Next steps

Congratulations! You have successfully performed the basic Localytics integration and are now sending session data to Localytics.

Note that it may take a few minutes for your first datapoints to show up within the Localytics Dashboard. In the meantime, we suggest reading about how to tag events.

Session lifecycle

With just the basic integration above, the Localytics SDK automatically measures user engagement and retention by tracking interactions with your site. On page load, the Localytics SDK creates and uploads a "start session" datapoint that captures many details about the user (e.g., Browser, Operating System, Country) that can be used to split and filter charts in the Localytics Dashboard.

After a period of inactivity, the SDK marks the current session as closed. If the user returns to your site within a timeout period (30 minutes by default) the session will be resumed as if the user never left. Otherwise, the session is finalized and uploaded the next time the user visits your site. In the Localytics Web SDK a user is considered active every time they load a page or perform an action that results in an event being tagged.

Session lifecycle tracking allows Localytics to calculate number of sessions, average session length, time between sessions, and a number of other core engagement metrics in the Localytics Dashboard.

Tagging events

Track user actions in your app using events in Localytics. All events must have a name, but you can also track the details of the action with event attributes. Event attributes help to provide context about why and how the action occurred. Every event can have up to 50 attributes unique to that event with each attribute having a limit of 255 characters.

Simple event

ll('tagEvent', 'Item Purchased');

Event with attributes

ll('tagEvent', 'Item Purchased', {'Item Name': 'Stickers', 'Aisle': 'Knick-knacks'});		

Identifying users

The Localytics SDK automatically captures and uploads device IDs which the Localytics backend uses to uniquely identify users. Some apps connect to their own backend systems that use different IDs for uniquely identifying users. There is often additional identifying information, such as name and email address, connected with the external IDs. Localytics provides various setters for passing this information to Localytics when it is available in your app. Using these setters ensures that you will be able to properly connect Localytics IDs to the IDs available in other systems.

User ID

ll('setCustomerId', '3neRKTxbNWYKM4NJ')

User first name

ll('setCustomerFirstName', 'John')

User last name

ll('setCustomerLastName', 'Smith')

User full name

ll('setCustomerFullName', 'Sir John Smith, III')

User email address

ll('setCustomerEmail', 'sir.john@smith.com')

User profiles

Track user properties using profile attributes in Localytics. Each profile has one or more named properties that describe that user. Because they contain rich user data, profiles are excellent for creating audiences to target with personalized messaging. Each profile is identified by a unique user ID that you provide to Localytics via the SDK. If you do not set a known user ID, then the Localytics SDK automatically generates an anonymous profile ID.

Each time you set the value of a profile attribute, you can set the scope to "app-level" or "org-level". App-level profile attributes are only stored in relation to that specific Localytics app key, so they can only be used for building audiences for that one app. Org-level profile attributes are available to all apps in the org, so they can be used across multiple Localytics app keys, which might represent the same app on a different platform or multiple apps produced by your company. If you choose not to set a scope, the SDK defaults to "app-level" scope.

If you repeatedly set the same profile attribute value, the Localytics SDK and backend will take care of deduplicating the values for you so only the most recent value gets stored for that profile.

Best Practices

We upload data on Profiles as soon as you tag it to ensure that data is not lost when users close tabs or navigate to different sites. Unlike Dimensions, that data is sent up in individual HTTP requests and is not tied to a session or event uploaded afterwards. To minimize traffic for your users, we recommend tagging most user attributes after a login event or when those attributes change, rather than on every page on your site.

For example, if you are setting the user's last viewed news section in a Profile, consider tagging that only in the Category page, or even using the referrer URL to avoid setting that profile attribute if category for an individual article is the same as the previous page's.

Setting a profile attribute value

Numeric value

ll('setProfileAttribute', 'Age', 45, 'org');

Numeric values in a set

ll('setProfileAttribute', 'Lucky Numbers', [8, 12], 'app');

Date value

ll('setProfileAttribute', 'Last Purchase Date', new Date(), 'org');

Date values in a set

ll('setProfileAttribute', 'Upcoming Milestone Dates', [new Date('2015-10-01'), new Date('2016-03-14')], 'app');

String value

ll('setProfileAttribute', 'Hometown', 'New York, New York', 'org');

String values in a set

ll('setProfileAttribute', 'States Visited', ['New York', 'California', 'South Dakota'], 'app');

Removing a profile attribute

ll('deleteProfileAttribute', 'Days until graduation', 'org');

Adding to a set of profile attribute values

Adding a numeric value to a set

ll('addProfileAttributesToSet', 'Lucky numbers', [8], 'app');

Adding a date value to a set

ll('addProfileAttributesToSet', 'Upcoming Milestone Dates', [new Date('2015-04-19')], 'org');

Adding a string value to a set

ll('addProfileAttributesToSet', 'States visited', ['North Dakota'], 'app');

Removing from a set of profile attribute values

Removing numeric values from a set

ll('removeProfileAttributesFromSet', 'Lucky numbers', [8, 9], 'org');

Removing date values from a set

ll('removeProfileAttributesFromSet', 'Upcoming Milestone Dates', [new Date('2016-03-14')], 'app');

Removing string values from a set

ll('removeProfileAttributesFromSet', 'States visited', ['California'], 'org');

Incrementing a numeric profile attribute value

ll('incrementProfileAttribute', 'Age', 1, 'app');

Decrementing a numeric profile attribute value

ll('decrementProfileAttribute', 'Days Until Graduation', 3, 'app');

Tracking user flow

Track screens or views within your app so you can visualize user flow within the Localytics Dashboard. We recommend exhaustively tagging every visible view in your app.

The Localytics SDK will perform duplicate suppression on two identical tagged screens that occur in a row within a single session. For example, in the set of screens {"Screen 1", "Screen 1"}, the second screen would be suppressed. However, in the set {"Screen 1", "Screen 2", "Screen 1"}, no duplicate suppression would occur.

ll('tagScreen', 'Item List')

Tracking revenue

There are two ways to think about Lifetime Value (LTV) in Localytics: monetary and non-monetary. If your app allows real currency transactions, our Dashboard can show LTV in USD. If your app uses virtual currencies like coins or tokens, you can configure your app to report LTV as the raw data you pass in.

You can configure each Mobile App in Localytics to have either a monetary value or raw data for Lifetime Value:

Tracking Monetary LTV

If you'd like to track LTV as monetary-based revenue, you should increment the value upon the completion of a purchase by the purchase amount. Make sure to configure your app in Localytics to show LTV as "Tracked as Money (US cents)".

LTV must be an integer amount, and the Localytics system requires you pass the number of USD cents as the LTV value in order to track money. For example, if the purchase amount is "USD $2.99", you should pass the integer "299" as the LTV. If the cents don't matter to you, feel free to round up to whole dollar values, but continue to pass the value as cents. If you want to track the rounded value of "USD $3.00", you should pass "300" as the value.

Currently, Localyics only allows LTV tracking in USD. If you want to track other currencies, you could convert the monetary amount to USD on the device before sending to Localytics.

Tracking Non-Monetary LTV

Another way to measure LTV is to track a non-monetary value important to your app. Examples include the number seconds spent engaged with content, or the amount of virtual currency earned. To track these values, send the corresponding integer value to Localytics. Make sure to configure your app in Localytics to show LTV as "Raw Value". Otherwise, Localytics will automatically divide your values by 100 and display a "$" in front of the values in the Dashboard.

LTV Examples

Increment user lifetime value (LTV) on any event using the optional LTV incrementer parameter as seen below.

ll('tagEvent', 'Item Purchased', {'Item Name': 'Stickers', 'Aisle': 'Knick-knacks'}, 499);

Setting custom dimensions

Custom dimensions are special fields that are used for splitting and filtering data within the Localytics Dashboard and are useful for storing user-level information. Custom dimensions are like sticky event attributes in the sense that once their value is set, it remains set until the value is changed again. Unlike event attributes, custom dimension values are attached to all three types of datapoints (session start, session close, and event) the same way that standard dimensions are which makes their values available within almost every report in the Localytics Dashboard.

Custom dimensions start at an index of 0 and the number of custom dimensions available to you depends on the level of your subscription. Name all of your custom dimensions in the Localytics Dashboard > Settings > Apps > (find app) > Gear icon > Custom Dimensions.

Whenever a datapoint is created, all custom dimension values are attached to the datapoint. Therefore, it is ideal to set custom dimensions as soon as their value is known in all code paths in your app. See initialization options for instructions on how to set custom dimension values during initialization.

Set value

ll('setCustomDimension', 0, 'Trial');

Clear value

ll('setCustomDimension', 0, null);

Advanced

Initialization options

You can pass a number of options to the init method of your Localytics instance.

Option Description
appVersion Your app's version number
sessionTimeout Time in seconds until Localytics marks the session as closed. Default: 1800
customDimensions An array of custom dimension values. Use this to set custom dimensions before the first session.
customerId A String representing the customer ID. Use this to set the customer ID before the first session.
customerEmail A String representing the customer's email. Use this to set the customer email before the first session.
customerName A String representing the customer's name. Use this to set the customer name before the first session.
domain Changes the domain used for cookies. Use this to track users across subdomains.
trackPageView Automatically track page view events. The default value is false.
cacheOffline Set to true to enable offline caching, which will automatically retry analytics uploads on subsequent pages if the device is offline. IE 8 and browsers without CORS support ignore this flag. Events will be stored in localStorage if possible (unless the cookies override is set to true), and fall back to cookies if not. Devices with cacheOffline enabled will also upload using the useXHR option if possible.
cookies Always store all data in cookies and not localStorage. The default value is false, unless localStorage is not supported in the browser.
useXHR When uploading data, use XHR (Post) requests. Defaults to false unless cacheOffline is set to true. Always false on IE 8 and browsers without CORS support.
autoUpload Automatically upload events as they are created. The default value is true. If this value is false, then localytics.upload() will have to be called to pass data to the Localytics Dashboard.

Example:

ll('init', 'YOUR-LOCALYTICS-APP-KEY', {trackPageView: true, domain: 'localytics.com'});

Integrating with AMD

This modified integration code produces an AMD-compatible integration.

<script>
    +function(l,y,t,i,c,s) {
           l['LocalyticsGlobal'] = i;
           l[i] = function() { (l[i].q = l[i].q || []).push(arguments) };
           l[i].t = +new Date;
           (s = y.createElement(t)).type = 'text/javascript';
           s.src = '//web.localytics.com/v3/localytics.min.js';
           (c = y.getElementsByTagName(t)[0]).parentNode.insertBefore(s, c);

           ll('init', 'YOUR-LOCALYTICS-APP-KEY', {} /* Options */);
           define('localytics', function(){ return ll; });
    }(window, document, 'script', 'll');
</script>
  	

Integrating with CommonJS

Use our standard web integration, plus these instructions, to create a CommonJS-compatible integration.

In your package.json, include the following snippet.

"browserify-shim": {
    "localytics": "global:ll"
},
"browserify": {
    "transform": [
        "browserify-shim"
    ]
}

Multiple instances

Multiple instances of the Localytics Web SDK can be intialized on the same page using namespaces. You can use any alphanumeric string as a namespace name in place of ns1 and ns2 in the examples below.

ll('init.ns1', 'YOUR-LOCALYTICS-APP-KEY', {} /* Options */);
ll('init.ns2', 'YOUR-LOCALYTICS-APP-KEY', {} /* Options */);

Be sure to specify the matching namespace name in all SDK calls as follows.

ll('tagEvent.ns1', 'Some Event');
ll('tagEvent.ns2', 'Another Event');