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. Instead, you can turn on any new tool with the flick of a switch.

All of our libraries are open-source, so you can view Analytics.js on Github.

Getting Started

To get started head over to our Analytics.js QuickStart which will help you install analytics tracking 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 tie one of your users and their actions to a recognizable userId and traits. You can read more about how to set it up or about how it works.

Note: You won’t need to call identify for anonymous visitors to your site. We’ll automatically assign them an anonymousId, so just calling page and track will still work just fine without identify.

Here’s what an identify call looks like, along with its method signature:

analytics.identify('1e810c197e', {
  name: 'Bill Lumbergh',
  email: 'bill@initech.com'
});
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 options, that let you do things like enable or disable specific integrations for the call.
callback Function, optionalA callback function that gets called after a short timeout, giving the browser time to make outbound requests first.

The userId and traits are both optional. So you can omit the userId if you want to associate traits with the currently identified user, anonymous or not, like so:

analytics.identify({
  email: 'bill@initech.com',
  newsletter: true,
  industry: 'Technology'
});

We’ll store those traits internally, and carry them over the next time you call identify with a userId. For example, you might do that when someone signs up for a newsletter but hasn’t yet created an account on your site.

You can also omit both traits and options—passing the callback as the second argument—if all you want to do is associate an ID, like so:

analytics.identify('1e810c197e', function(){
  // Do something after the identify request has been sent, like
  // submit a form or redirect to a new page.
});

Track

The track method lets you record any actions your users perform. You can read more about how to set it up or about how it works.

Here’s a basic example, along with the track method signature:

analytics.track('Signed Up', {
  plan: 'Startup',
  source: 'Analytics Academy'
});
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 options, that let you do things like enable or disable specific integrations for the call.
callback Function, optionalA callback function that gets called after a short timeout, giving the browser time to make the track requests first. Also checkout our dedicated trackLink and trackForm helpers.

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.

Page

The page method lets you record page views on your website, along with optional extra information about the page being viewed.

It’s already included in the Analytics.js snippet by default just after the call to load, so in most cases you never need to touch it. However, if you want to add extra information, like tagging the page with a name or category, read on!

Note that you must call page at least once per page load! (That’s why we put it in your snippet for you.) If you have a single page app you can call it multiple times, whenever a new page view occurs.

Here’s a basic example, along with the page method signature:

analytics.page('Signup');
analytics.page([category], [name], [properties], [options], [callback]);
category String, optionalThe category of the page. Useful for things like ecommerce where many pages might live under a larger category. Note: if you only pass one string to page we assume it’s a name, not a category. You must include a name if you want to send a category.
name String, optionalThe name of the of the page, for example Signup or Home.
properties Object, optionalA dictionary of properties of the page. We’ll automatically send the url, title, referrer and path, but you can add your own too!
options Object, optionalA dictionary options, that let you do things like enable or disable specific integrations for the call.
callback Function, optionalA callback function that gets called 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. For example, if you 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'
});

You can also override these values if you’d like, for example:

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

In which case we will respect your overridden title of My Overridden Title and add in the default url and referrer.

Alias

The alias method combines two previously unassociated user identities. This comes in handy if the same user visits from two different devices and you want to combine their history.

Some providers also don’t alias automatically for you when an anonymous user signs up (like Mixpanel), so you need to call alias manually right after sign up with their brand new userId.

Here’s a basic example along with the alias method signature:

analytics.alias('019mr8mf4r');
analytics.alias(userId, [previousId], [options], [callback]);
userId StringThe new User ID you want to associate the user with.
previousId String, optionalThe previous ID that the user was recognized by. This defaults to the currently identified user’s ID if you don’t pass one. In most cases you don’t need to worry about this argument.
options Object, optionalA dictionary options, that let you do things like enable or disable specific integrations for the call.
callback Function, optionalA callback function that gets called after a short timeout, giving the browser time to make the alias requests first.

trackLink is a helper that binds a track call to whenever a link is clicked. Usually the page would change before you could call track, but with trackLink a small timeout is inserted to give the track call enough time to fire.

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

analytics.trackLink(link, 'Clicked Free-Trial Link', {
  plan: 'Enterprise'
});
element(s) Element or ArrayThe link DOM element you want to track clicks on. You can also pass an array of link elements, or a jQuery object. Note: This must be an element, not a CSS selector.
event String or FunctionThe name of the event, which gets passed straight to the track method. You can also pass a function that returns the event name string instead, which will be called with the link element that was clicked.
properties Object or Function, optionalA dictionary of properties which get passed straight to the track method. You can also pass a function that returns the properties dictionary instead, which will be called with the link element that was clicked.

Track Form

trackForm is a helper that binds a track call to a form submission. Usually the page would change before you could call track, but with trackForm a small timeout is inserted to give the track call enough time to fire.

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

analytics.trackForm(form, 'Signed Up', {
  plan: 'Premium',
  revenue: 99.00
});
form(s) Element or ArrayThe form DOM element you want to track submissions for. You can also pass an array of form elements, or a jQuery object. Note: trackForm takes an element, not a CSS selector.
event String or FunctionThe name of the event which gets passed straight to the track method. You can also pass a function that returns the event name string instead, which will be called with the link element that was clicked.
properties Object or Function, optionalA dictionary of properties which get passed straight to the track method. You can also pass a function that returns the properties dictionary instead, which will be called with the link element that was clicked.

Ready

The ready method allows you to pass in a callback that will be called as soon as all of your enabled integrations have loaded. It’s like jQuery’s ready method, except for integrations.

If you want to make calls to a specific integration, like adding an extra setting to Mixpanel, you can use a ready callback so that you’re guaranteed to have access to the Mixpanel object, like so:

analytics.ready(function(){
  window.mixpanel.set_config({ verbose: true });
});
analytics.ready(callback);
callback FunctionA callback you want to fire after all your enabled integrations have loaded.

Querystring API

Analytics.js can trigger basic track and identify events based on the querystring. This is helpful for tracking email click throughs, social media clicks, or digital advertising.

Here are the query parameters to use:

ajs_uidThe userId to pass to an identify call.
ajs_eventThe event name to pass to a track call.
ajs_aidThe anonymousId to set for the user.

So for example, with this URL:

http://segment.com/?ajs_uid=12345&ajs_event=Clicked%20Email&ajs_aid=abc123

That would trigger the following on the page:

analytics.identify('12345');
analytics.track('Clicked Email');
analytics.user().anonymousId('abc123');

You can pass both parameters like the example above, or you can just pass one parameter in the URL.

Selecting Integrations

The alias, group, identify, page and track calls can all be passed an object of options for the call. That lets you turn certain integrations on or off.

Here’s an example showing an identify call that only goes to Mixpanel and KISSmetrics:

analytics.identify('019mr8mf4r', {
  email: 'achilles@segment.com',
  plan: 'Premium'
}, {
  integrations: {
    'All': false,
    'Mixpanel': true,
    'KISSMetrics': true,
    'Google Analytics': false
  }
});

In this case, we’re specifying that we want this identify to only go to Mixpanel and KISSmetrics. 'All': false says that no integration should be enabled unless otherwise specified. 'Mixpanel': true turns on Mixpanel, etc. To specify an integration, just use it’s formal name (i.e. “AdLearn Open Platform” or “awe.sm”), which is also the title of the integration’s documentation.

User & Group

Once Analytics.js loaded, you can retrieve information about the currently identified user or group like their id and traits. Here’s how you’d access information about the user:

analytics.ready(function(){
  var user = analytics.user();
  var id = user.id();
  var traits = user.traits();
});

Similarly, here’s how you’d access information about the group:

analytics.ready(function(){
  var group = analytics.group();
  var id = group.id();
  var traits = group.traits();
});

Clearing Traits

By default we cache traits when you call identify or group. You can clear the traits object by calling one of the following:

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

Reset / Logout

If you need to clear the user and group id and traits we’ve added a reset function that is most commonly used when your identified users logout of your application.

Calling analytics.reset() will clear out user and group ids, traits, and reset the anonymousId:

analytics.reset();

Note, however, that this function only clears the cookies/localStorage set by Segment and not the those of other third-party tools. Our javascript library asynchronously loads the scripts of some of those tools onto the page and those libraries also use cookies to manage user tracking, sessions, and manage state. If you want to completely clear out the user session, then check the documentation of those other tools to learn how to do so.

Anonymous ID

Analytics.js generates an anonymousId for all visitors to your site. It will look something like this:

ecbde18a-815f-49d2-a822-b52e9657230f

Retrieving the Anonymous ID

You can retrieve the visitor’s current anonymousId like this:

analytics.user().anonymousId();

Setting the Anonymous ID

If you want to set your own anonymousId that can be done independently, like this:

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

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

analytics.identify('123', {
  gender: 'Male',
}, {
  anonymousId: 'ABC-123-XYZ'
});
analytics.page({}, { anonymousId: 'ABC-123-XYZ' });
analytics.track('Clicked CTA', {
  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.

Debug

Analytics.js has a debug mode that logs helpful messages to the console. You can enable it by firing:

analytics.debug();

And turn it off with:

analytics.debug(false);

Emitter

The global analytics object emits events whenever you call alias, group, identify, track or page. That way you can listen to those events and run your own custom code. For example, you could use them to send data to your own custom integration:

analytics.on('track', function(event, properties, options){
  bigdata.push(['recordEvent', event]);
});

Extending Timeout

You can extend the length (in milliseconds) of the method callbacks and helpers like this:

analytics.timeout(500);

This will 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 it loads are loaded asynchronously, so they will never block the page or increase your page’s load time for your users.

Depending on the integration, we even optimize away the need to load their Javascript library at all! Whenever possible, we send the tracking data straight from our servers, instead of loading an additional library onto your site. For example, all Omniture, Salesforce, and MailChimp data is routed straight from our servers. Of course, integration libraries often require access to the DOM or cookies, so in those cases we load the libraries onto the page itself.

We also guarantee that only the code required for your enabled integrations is loaded on the page at any given time. Whenever you disable an integration, we strip that extra code out of your project’s copy of Analytics.js so that you’re always loading the smallest amount of code possible.

With all of that, there isn’t a huge performance benefit to using Analytics.js but it would 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.

If you don’t want to use any bundled 3rd-party tools, you can use our browserify’d analytics-node package.

Troubleshooting

All of the troubleshooting will require using the Javascript console on the website with which you want to track. Each browser has a different way of accessing the Javascript console, which can be found here.

Are you loading Analytics.js?

Open up your Javascript console in the browser. Type analytics in the console and hit enter. Does it return an object, as below?

Returning analytics object

Seeing 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

Then make sure that you are copying and pasting the snippet as per the steps here.

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 can, however, conditionally set the write key based on an environment variable. Here’s an 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?

Ad blockers prevent cookies and other pieces of data to be set on your browser. Segment and many third-party integrations use cookies to identify your users. Enabling ad blockers would prevent third-party integrations to retrieve the information necessary to be sent to their servers.

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, with the intention of enumrating all domain suffixes that are controlled by registrars.

The implications of domain suffixes on this list is that first party cookies cannot be set on them. For example, a page at 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, since 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 is important to examine all outbound and inbound requests to your browser, as well as manually executing Javascript on your page.

  • Chrome: COMMAND+OPTION+J (Mac) or CTRL+SHIFT+J (Windows).
  • Firefox: COMMAND+SHIFT+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.

If you ever have any questions, or see anywhere we can improve our documentation, feel free to contact us!