analytics.js

analytics.js makes it dead simple to send your data to any tool without having to learn, test or implement a new API every time.

All of our libraries are open source, and you can view analytics.js on Github.

Getting Started

Head over to our analytics.js QuickStart Guide which will help you implement analytics.js on your site in just a few minutes. Once you’ve installed the library, read on for the detailed API reference!

Want to stay updated on releases? Subscribe to the release feed.

Identify

The identify method is how you associate your users and their actions to a recognizable userId and traits. You can see an identify example in the guide or find details on the identify method payload here.

Note: We recommend against using identify for anonymous visitors to your site. analytics.js automatically retrieves an anonymousId from localStorage or assigns one for new visitors. It will be attached to all page and track events both before and after an identify.

identify method definition:

analytics.identify([userId], [traits], [options], [callback]);
userId String, optionalThe database ID for the user. If you don’t know who the user is yet, you can omit the userId and just record traits. You can read more about identities in the identify reference.
traits Object, optionalA dictionary of traits you know about the user, like their email or name. You can read more about traits in the identify reference.
options Object, optionalA dictionary of options. For example, enable or disable specific integrations for the call. Note: If you do not pass a traits object, pass an empty object (ie, ‘{}’) before options
callback Function, optionalA function that is executed after a short timeout, giving the browser time to make outbound requests first.

Example:

analytics.identify('025pikachu025', {
    name: 'Pikachu',
    type: 'electric',
    email: 'peekAtMe@poke.mon',
    abilities: ['static', 'lightning rod (hidden)'],
    baseStats: {
        hp: 35,
        attack: 55,
        defense: 40,
        specialAttack: 50,
        specialDefense: 50,
        speed: 90
    },
    nickname: 'Mouse Pokémon'
});

By default, user traits are cached in the browser’s local storage and attached to each subsequent identify call. For example, when someone signs up for a newsletter but does not have an account on your site:

analytics.identify({
  nickname: 'Amazing Grace',
  favoriteCompiler: 'A-0',
  industry: 'Computer Science',
  email: 'grace@usnavy.gov'
});

and when the user completes signup:

analytics.identify('12091906-01011992', {
  name: 'Grace Hopper'
});

The traits object for the second call will include nickname, favoriteCompiler, and industry.

You may omit both traits and options—-passing the callback as the second argument if

analytics.identify('12091906-01011992', function() {
  // Do something after the identify request has been sent
  // Note: site-critical functionality should not depend on your analytics provider
});

Track

The track method lets you record any actions your users perform. You can see a track example in the guide or find details on the track method payload here.

track method definition:

analytics.track(event, [properties], [options], [callback]);
event StringThe name of the event you’re tracking. You can read more about the track method and what event names we recommend.
properties Object, optionalA dictionary of properties for the event. If the event was 'Added to Cart', it might have properties like price and productType.
options Object, optionalA dictionary of options. For example, enable or disable specific integrations for the call. Note: If you do not pass a properties object, pass an empty object (ie, ‘{}’) before options
callback Function, optionalA function that is executed after a short timeout, giving the browser time to make outbound requests first.

The only required argument to track in analytics.js is an event name string. You can read more about how we recommend naming your events.

Example:

analytics.track('Article Completed', {
  title: 'How to Create a Tracking Plan',
  course: 'Intro to Analytics',
});

Check out Analytics Academy There are two helper methods discussed later: trackLink and trackForm

Page

The page method lets you record page views on your website, along with optional extra information about the page being viewed. Note: Because some integrations require a page call to instantiate their libraries, you must call page at least once per page load! You may call it more than once if needed, (eg, on virtual page changes in a single page app).

The page call included by default in the analytics.js snippet may be modified within these guidelines.

page method definition:

analytics.page([category], [name], [properties], [options], [callback]);
category String, optionalThe category of the page. Useful for cases like ecommerce where many pages might live under a single category. _Note: if you pass only one string to page it is assumed to be name. You must include a name to send a category.
name String, optionalThe name of the page.
properties Object, optionalA dictionary of properties of the page. Note: url, title, referrer and path are collected automatically! Additionally this defaults to a canonical url, if available, and falls back to document.location.href.
options Object, optionalA dictionary of options. For example, enable or disable specific integrations for the call. Note: If you do not pass a properties object, pass an empty object (ie, ‘{}’) before options
callback Function, optionalA function that is executed after a short timeout, giving the browser time to make outbound requests first.

Default Properties

A few properties are automatically added to each page call.

analytics.page('Pricing');

We will translate that to the following without any extra work from you:

analytics.page('Pricing', {
  title: 'Segment Pricing',
  url: 'https://segment.com/pricing',
  path: '/pricing',
  referrer: 'https://segment.com/warehouses'
});

You can override these values. For example:

analytics.page('Pricing', {
  title: 'My Overridden Title',
  path: '/pricing/view'
});

For this page call, title will be My Overridden Title, path will be '/pricing/view, and url and referrer will be the defaults.

Alias

The alias method combines two previously unassociated user identities.

Aliasing from anonymous to known users is generally handled automatically when you identify a user. However, some tools will require an explicit Alias call.

alias method definition:

analytics.alias(userId, [previousId], [options], [callback]);
userId StringThe new user ID you want to associate with the user.
previousId String, optionalThe previous ID that the user was recognized by. This defaults to the currently identified user’s ID.
options Object, optionalA dictionary of options. For example, enable or disable specific integrations for the call.
callback Function, optionalA function that is executed after a short timeout, giving the browser time to make outbound requests first.

Example:

analytics.alias('MTIwOTE5MDYtMDEwMTE5OTI');

Most notably, alias is necessary for properly implementing KISSmetrics and Mixpanel.

Group

The group method associates an individual user with a company, organization, project, workspace, team, tribe, platoon, assemblage, cluster, troop, gang, party, society or any other name you came up with for the same concept.

group method definition:

analytics.group(groupId, [traits], [options], [callback]);
groupId StringThe Group ID to associate with the current user.
traits Object, optionalA dictionary of traits for the group. Example traits for a group include address, website and employees.
options Object, optionalA dictionary of options. For example, enable or disable specific integrations for the call. Note: If you do not pass a properties object, pass an empty object (ie, ‘{}’) before options
callback Function, optionalA function that is executed after a short timeout, giving the browser time to make outbound requests first.

Example:

analytics.group('UNIVAC Working Group', {
  principles: ['Eckert', 'Mauchly'],
  site: 'Eckert–Mauchly Computer Corporation',
  statedGoals: 'Develop the first commercial computer',
  industry: 'Technology'
});

By default, group traits are cached in the browser’s local storage and attached to each subsequent group call, similar to Identify method behavior.

trackLink is a helper method that binds a track call to an element. With trackLink a small timeout (300 ms) is inserted to give the track call more time. Useful when a page would redirect before the track method can complete all requests.

trackLink method definition:

analytics.trackLink(element, event, [properties])
element(s) Element or ArrayDOM element to be bound with track method. You may pass an array of elements or jQuery objects. Note: This must be an element, not a CSS selector.
event String or FunctionThe name of the event, passed to the track method. Or a function that returns a string to be used as the name of the track event.
properties Object or Function, optionalA dictionary of properties to pass with the track method. Or a function that returns an object to be used as the properties of the event.

Example:

var link = document.getElementById('free-trial-link');

analytics.trackLink(link, 'Clicked Free-Trial Link', {
  plan: 'Enterprise'
});

Track Form

trackForm is a helper method that binds a track call to a form submission. With trackForm a small timeout (300 ms) is inserted to give the track call more time. Useful when a page would redirect before the track method can complete all requests.

analytics.trackForm(element, event, [properties])
form(s) Element or ArrayThe form element to track or an array of form elements or jQuery objects. Note: trackForm takes an element, not a CSS selector.
event String or FunctionThe name of the event, passed to the track method. Or a function that returns a string to be used as the name of the track event.
properties Object or Function, optionalA dictionary of properties to pass with the track method. Or a function that returns an object to be used as the properties of the event.

Example:

var form = document.getElementById('signup-form');

analytics.trackForm(form, 'Signed Up', {
  plan: 'Premium',
  revenue: 99.00
});

Ready

An event called ready is emitted when all enabled integration libraries have loaded and analytics.js has completed initialization. Code inside the function will only be executed after ready has been emitted.

Useful for accessing end-tool library methods that do not match any analytics.js methods, especially configuration.

analytics.ready(callback);
callback FunctionA function to be executed after all enabled integrations have loaded.

Example:

analytics.ready(function() {
  window.mixpanel.set_config({ verbose: true });
});

Querystring API

analytics.js can trigger track and identify events based on the URL querystring. This is helpful for tracking email click throughs, social media clicks, and digital advertising as well as for cross-domain tracking.

Here are the query parameters to use:

paramdescriptiontriggers
ajs_uidThe userId to pass to an identify call.This will trigger an identify call.
ajs_eventThe event name to pass to a track call.This will trigger a track call.
ajs_aidThe anonymousId to set for the user.This will trigger an analytics.user().anonymousId() call.
ajs_prop_<property>A property to pass to the track callThis property will be included in the track call triggered by ajs_event
ajs_trait_<trait>A trait to pass to the identify callThis trait will be included in the identify call triggered by ajs_uid

For example, this link:

http://segment.com/?ajs_uid=025pikachu025&ajs_event=Email%Clicked&ajs_aid=abc123&ajs_prop_emailCampaign=Gotta%20Catch%20Em%20All&ajs_trait_name=Pikachu

Will trigger the following events on segment.com:

analytics.user().anonymousId('abc123');
analytics.identify('025pikachu025', { name: 'Pikachu' });
analytics.track('Email Clicked', { 'emailCampaign': 'Gotta Catch Em All' });

You can pass up to one of each trigger parameter as shown in the example above.

Selecting Integrations

An integrations object may be passed in the options of alias, group, identify, page and track methods, allowing selective integration filtering.

Note: We recommend using the Segment Dashboard Schema page to set filters for track methods, allowing filter management with no code changes.

An example showing how to send data only to Intercom and Google Analytics:

analytics.identify('025pikachu025', {
  email: 'peekAtMe@email.poke',
  name: 'Pikachu',
  type: 'electric'
}, {
  integrations: {
    'All': false,
    'Intercom': true,
    'Google Analytics': true
  }
});

'All': false flags that no integration should receive data. Note: Integration flags are case sensitive and match the integration’s name in the docs (i.e. “AdLearn Open Platform”, “awe.sm”, “MailChimp”, etc.).

User & Group Information

Once analytics.js is loaded, executing the user or group method functions will return information about the currently identified user or group.

Examples:

analytics.ready(function() {

  var user = analytics.user();
  var id = user.id();
  var traits = user.traits();

});
analytics.ready(function() {

  var group = analytics.group();
  var id = group.id();
  var traits = group.traits();

});

Clearing Traits

Passing an empty object to the traits object will clear all cached traits for a User or Group. Remember, traits are cached by default by identify and group methods You can clear the traits object for the user or group by passing traits an empty object:

analytics.user().traits({});
analytics.group().traits({});

Reset / Logout

Calling reset will reset the id, including anonymousId, and clear traits for the currently identified user and group.

analytics.reset();

Note: The reset method only clears the cookies/localStorage set by Segment, not the those of integrated end-tools, as their native libraries might set their own cookies to manage user tracking, sessions, and manage state. To completely clear out the user session, check the documentation provided by those tools.

Anonymous ID

analytics.js generates a UUID and sets this as anonymousId for all new visitors to your site.

Example:

ajs_anonymous_id=%2239ee7ea5-b6d8-4174-b612-04e1ef3fa952

Retrieving the Anonymous ID

Retrieve the of the current user anonymousId:

analytics.user().anonymousId();

Setting the Anonymous ID

Override the assigned anonymousId for the current user:

analytics.user().anonymousId('ABC-123-XYZ');

Or in the options object of identify, page, or track calls, like this:

analytics.identify('025pikachu025', {
  name: 'Pikachu'
}, {
  anonymousId: 'ABC-123-XYZ'
});
analytics.page({}, { anonymousId: 'ABC-123-XYZ' });
analytics.track('Clicked Email', {
  callToAction: 'Signup'
}, {
  anonymousId: 'ABC-123-XYZ'
});

Keep in mind that setting the anonymousId in analytics.js does not overwrite the anonymous tracking IDs for any integrations you’re using.

Refreshing the Anonymous ID

A user’s anonymousId will refresh on any of the following conditions:

  • A user clears their cache or cookies
  • analytics.reset() is called during in the user’s browser session
  • analytics.identify() is called with a userId that differs from the current userId

Debug

Calling the debug method will turn on debug mode, logging helpful messages to the console.

Enable:

analytics.debug();

Disable:

analytics.debug(false);

Emitter

The global analytics object emits events whenever you call alias, group, identify, track or page. Using the on method You can set listeners for these events and run your own custom code. Useful for sending data to a service for which Segment does not have an integration.

analytics.on(method, callback);
method StringName of the method to listen for
callback FunctionA function to execute after each the emitted method, taking three arguments: event, properties, options

Example:

analytics.on('track', function(event, properties, options) {

  bigdataTool.push(['recordEvent', event]);

});

Extending Timeout

The timeout method will set the length (in milliseconds) of the callbacks and helper functions:

analytics.timeout(500);

Set the timeout to 500ms. This is helpful if you have multiple scripts that need to fire in your callback or trackLink, trackForm helper function. We recommend extending to 500ms if you’re triggering ad network conversion pixels since those are often a bit slower to load.

Performance

The analytics.js library and all of the integration libraries are loaded with the HTML script async tag.

While many tools require access to the DOM or cookies, for the Omniture, Salesforce, and MailChimp integrations do not load the native Javascript library! Instead data is sent from Segment’s servers to the end-tools. We aim to expand on this front in the future.

Only the libraries required for your enabled integrations are loaded. Whenever an integration is disabled, the custom version of analytics.js will no longer request that library.

Using analytics.js will not offer a huge performance benefit, but it should be slightly more performant than installing each of the integrations individually. And as we move more and more integrations server-side, you’ll receive more performance benefits automatically.

One option, if you don’t want to use any bundled 3rd-party tools, is to use our browserify’d analytics-node package.

Cross Subdomain Tracking

Since all of our integrations fully support tracking across subdomains, you only need to create one source to manage your website.

Anonymizing IP

We collect IP address for client-side (iOS, Android, analytics.js and Xamarin) events automatically.

Passing a value for options.context.ip will prevent our server from recording the IP address associated with the request.

Example:

  analytics.track("Order Completed", {}, { context: { ip: "0.0.0.0" }});

Troubleshooting

The console reveals all! Learn how to access the Javascript console in each browser. Any analytics.js methods may be executed manually. Use the Network tab to inspect requests.

Are you loading analytics.js?

Open the Javascript console and enter analytics. Does it return an object, as seen below?

Returning analytics object

The object means that you are successfully loading analytics.js onto your website. If you get an undefined error, analytics.js is not loading successfully:

Returning analytics object error

Solution: Follow the analytics.js Quickstart Guide

Are you loading two instances of analytics.js?

Please note that you cannot load analytics.js twice on the same page, even if you’re using different write keys. You might encounter Uncaught RangeError: Maximum call stack size exceeded. You can onditionally set the write key based on an environment variable.

Example:

var writeKey;
ENV === 'production' ? writeKey = 'A' : writeKey = 'B';

Do you see events appear in your debugger?

When you reload the page, does your debugger show a new page and an identify call? You can also check the Javascript console in the browser and manually fire an identify call as such, which would show up in the debugger.

Making an identify call

If the call doesn’t appear in the debugger, open up the Javascript console and check the Network tab to see if the outbound web services requests are being initiated:

Checking for calls in the network tab

In the above, the p is a page call and the i is an identify call. If you don’t at least see the p, then check if you are loading analytics.js correctly.

Is data being transmitted to your third-party integrations?

Some integrations send data directly from the website to their servers. You can check the Network tab in your Javascript console to see the outbound web services requests being initiated.

In the below image, we use Google Analytics as an example. Our page call will form an outbound request that looks like this:

Google Analytics outbound request

If this outbound request is not showing up in the network when you fire an identify call, then check the following:

Do you have any ad blockers enabled in your browser?

Segment and many integration partners use cookies to store information about users in the browser. Ad blockers prevent cookies and other data these tools rely on to make valid analytics requests. Some portion of your users are likely using ad blockers which will prevent the Segment script from fully executing. Both desktop and mobile browsers are impacted.

Is your web site deployed under a domain on the Public Suffix List?

The Public Suffix List is a catalog of certain Internet effective top-level domains–enumerating all domain suffixes controlled by registrars.

The implications of these domain suffixes is that first party cookies cannot be set on them. Meaning, foo.example.co.uk can share cookie access with bar.example.co.uk, but example.co.uk should be walled off from cookies at example2.co.uk. The latter two domains could be registered by different owners.

Examples of domains on the Public Suffix List that are common in troubleshooting include:

  • *.github.io
  • *.herokuapp.com
  • *.appspot.com

How do I open the Javascript console in your debugger?

The Javascript console reveals all requests, outbound and inbound, to your browser. Additionally, you may execute valid Javascript.

  • Chrome: COMMAND+OPTION+J (Mac) or CTRL+SHIFT+J (Windows).
  • Firefox: COMMAND+OPTION+K (Mac) or CTRL+SHIFT+K (Windows) and then click on the Console tab.
  • Safari: COMMAND+OPTION+I (Mac) or CTRL+ALT+I (Windows) and then click on the Console tab.
  • IE: F12 and then click on the Console tab.

Is there a size limit on requests?

Yes, 15kb per message.

If analytics.js fails to load, are callbacks not fired?

In the event that analytics.js does not load, any callbacks passed into your API calls will not fire. We believe is reasonable since the purpose of callbacks are to provide an estimate that the event was delivered and if the library never loads, the events won’t be delivered.

Known Issues:

Review and contribute to these on Github


If you have any questions or see anywhere we can improve our documentation, please let us know or kick off a conversation in the Segment Community!