Analytics.js (Javascript) Source


Analytics.js, Segment’s Javascript source, makes it simple to send your data to any tool without having to learn, test or implement a new API every time.

Getting Started

Read through the Analytics.js QuickStart Guide which explains how to add Analytics.js to your site in just a few minutes. Once you’ve installed the library, read on for the detailed API reference!

Basic tracking methods

The basic tracking methods below are the building blocks of your Segment tracking. They include Identify, Track, Page, Group, and Alias, as described below.

These names may seem familar because these are the basic methods covered by the Segment Spec. The documentation on this page explains how to use these methods in Analytics.js specifically.

Good to know: For any of the different methods described in this page, you can replace the properties in the code samples with variables that represent the data collected.

Identify

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

Segment recommends against using identify for anonymous visitors to your site. Analytics.js automatically retrieves an anonymousId from localStorage or assigns one for new visitors, which is attached to all page and track events both before and after an identify.

The Identify method follows the format below:

analytics.identify([userId], [traits], [options], [callback]);

The Identify call has the following fields:

userId optional String The 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 optional Object A dictionary of traits you know about the user, like their email or name. You can read more about traits in the identify reference.
options optional Object A dictionary of options. For example, enable or disable specific destinations for the call. Note: If you do not pass a *traits* object, pass an empty object (ie, ‘{}’) before *options*
callback optional Function A function executed after a short timeout, giving the browser time to make outbound requests first.

By default, traits are cached in the browser’s localStorage and are attached to each subsequent Identify call.

For example, you might call Identify when someone signs up for a newsletter, but hasn’t yet created an account on your site. The example below shows an Identify call (using hard-coded traits) that you might send in this case.

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

Then, when the user completes the sign up process, you might see the following:

analytics.identify('12091906-01011992', {
  name: 'Grace Hopper',
  email: 'grace@usnavy.gov'
});

The traits object for the second call also includes nickname, favoriteCompiler, and industry.

You may omit both traits and options, and pass the callback as the second argument.

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 actions your users perform. You can see a track example in the Quickstart guide or find details on the track method payload.

The Track method follows the format below:

analytics.track(event, [properties], [options], [callback]);

The track call has the following fields:

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

The only required argument in Analytics.js is an event name string. You can read more about how Segment recommends you name events.

Example Track call:

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

For more information about choosing which events to track, event naming and more, check out Analytics Academy

The only required argument on Track calls in Analytics.js is an event name string. Read more about how Segment recommends naming your events.

trackLink is a helper method that attaches the track call as a handler to a link. With trackLink a short timeout (300 ms) is inserted to give the track call more time. This is useful when a page would redirect before the track method could complete all requests.

The trackLink method follows the format below.

analytics.trackLink(element, event, [properties])
element(s) Element or Array DOM 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 Function The 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 optional Object or Function A 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. The trackForm method inserts a short timeout (300 ms) to give the track call more time to complete. This is useful to prevent a page from redirecting before the track method could complete all requests.

The trackForm method follows the format below.

analytics.trackForm(form, event, [properties])
form(s) Element or Array Element or Array The 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 Function The 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 optional Object or Function A 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
});

Page

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

Because some destinations require a page call to instantiate their libraries, you must call page at least once per page load. You can call it more than once if needed, for example on virtual page changes in a single page app.

A Page call is included by default as the final line in the Analytics.js snippet. You can modify this page call within the guidelines below.

The page method follows the format below.

analytics.page([category], [name], [properties], [options], [callback]);

The page call has the following fields:

category optional String The 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 optional String The name of the page.
properties optional Object A 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 optional Object A dictionary of options. For example, enable or disable specific destinations for the call. Note: If you do not pass a properties object, pass an empty object (ie, ‘{}’) before options
callback optional Function A function that is executed after a short timeout, giving the browser time to make outbound requests first.

Default Page Properties

A few properties are automatically added to each page call.

analytics.page('Pricing');

Segment adds the following information 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 by explicitly setting them in your calls. For example:

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

Translates to:

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

Group

The Group method associates an identified user with a company, organization, project, workspace, team, tribe, platoon, assemblage, cluster, troop, gang, party, society or any other collective noun you come up with for the same concept.

This is useful for tools like Intercom, Preact and Totango, as it ties the user to a group of other users.

The Group method follows the format below.

analytics.group(groupId, [traits], [options], [callback]);

The Group call has the following fields:

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

Example group call:

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 how the identify method works.

Find more details about group including the group payload in the Group Spec.

Alias

The Alias method combines two previously unassociated user identities. Segment usually handles aliasing automatically when you call Identify on a user, however some tools require an explicit alias call.

This is an advanced method, but it is required to manage user identities successfully in some of our destinations such as KISSmetrics and Mixpanel.

The Alias method follows the format below:

analytics.alias(userId, [previousId], [options], [callback]);

The Alias call has the following fields:

userId String The new user ID you want to associate with the user.
previousId optional String The previous ID that the user was recognized by. This defaults to the currently identified user’s ID.
options optional Object A dictionary of options. For example, enable or disable specific destinations for the call.
callback optional Fucntion A function that is executed after a short timeout, giving the browser time to make outbound requests first.

For more details about Alias, including the alias call payload, check out our Spec.

Utility Methods

The Analytics.js utility methods help you change how Segment loads on your page. They include:

Ready

The ready method allows you to pass in a method that is called once Analytics.js finishes initializing, and once all enabled device-mode destinations load. It’s like jQuery’s ready method, except for destinations.

ready is still invoked if a destination throws an error (for example for an expired API key or incorrect settings configuration) during initialization. Doing so prevents blocking code listening for the ready callback.

The code in the ready function only executes after ready is emitted.

If you want to access end-tool library methods that do not match any Analytics.js methods, 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 });
});

The ready method uses the following format:

analytics.ready(callback);

The ready method has the following fields:

callback Function A function to be executed after all enabled destinations have loaded.

Debug

Calling the debug method turns on debug mode, which logs helpful messages to the console. Refresh the page after you invoke debug to see the messages.

Enable:

analytics.debug();

Disable:

analytics.debug(false);

Emitter

The global analytics object emits events whenever you call alias, group, identify, track or page.

Use the on method to set listeners for these events and run your own custom code. This can be useful if you want to send data to a service for which Segment does not have a destination.

analytics.on(method, callback);
method String Name of the method to listen for
callback Function A 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]);

});

This method emits events before they are processed by the Segment integration, and may not include some of the normalization Segment does on the client before sending the data to the Segment servers.

Note: Page event properties are stored in the options object.

Extending Timeout

The timeout method sets the length (in milliseconds) of the callbacks and helper functions. This is helpful if you have multiple scripts that need to fire in your callback or trackLink, trackForm helper function.

The example below sets the timeout to 500ms.

analytics.timeout(500);

Tip: We recommend extending to 500ms if you’re triggering ad network conversion pixels since those are often a bit slower to load.

Reset or Logout

Calling reset resets the id, including anonymousId, and clears traits for the currently identified user and group.

analytics.reset();

The reset method only clears the cookies and localStorage created by Segment. It does not clear data from other integrated tools, as those native libraries might set their own cookies to manage user tracking, sessions, and manage state. To completely clear out the user session, see the documentation provided by those tools.

Segment does not share localStorage across subdomains. If you use Segment tracking on multiple subdomains, you must call analytics.reset() for each subdomain to completely clear out the user session.

Managing data flow with the Integrations object

Tip: There are many ways to change how your data flows without having to change your code. See Filtering Data to learn more.

You can pass an integrations object in the options of Alias, Group, Identify, Page and Track methods to send data to only the selected destinations. By default all destinations are enabled.

The example below sends a message only to Intercom and Google Analytics.

analytics.identify('user_123', {
  email: 'jane.kim@example.com',
  name: 'Jane Kim'
}, {
  integrations: {
    'All': false,
    'Intercom': true,
    'Google Analytics': true
  }
});

'All': false tells Segment not to send data to any destinations by default, unless they’re explicitly listed as true in the next lines.

As an opposite example, the snippet below sends a message to all integrations except Intercom and Google Analytics.

analytics.identify('user_123', {
  email: 'jane.kim@example.com',
  name: 'Jane Kim'
}, {
  integrations: {
    'Intercom': false,
    'Google Analytics': false
  }
});

You don’t need to include 'All': true in this call because it is implied as the default behavior. Instead, only list the destinations that you want to exclude, with a false flag for each.

Destination flags are case sensitive and match the destination’s name in the docs (for example, “AdLearn Open Platform”, “awe.sm”, “MailChimp”, etc). If a destination has more than one acceptable name, this appears in the documentation for that destination.

Tip: Business tier customers can filter Track calls from the Source Schema page in the Segment UI. We recommend that you use the UI if possible since it’s a much simpler way of managing your filters and can be updated with no code changes on your side.

Load Options

You can modify the .load method in Analytics.js (the second line of the snippet) to take a second argument. If you pass an object with an integrations dictionary (matching the format above), then Segment only loads the integrations in that dictionary that are marked as enabled with the boolean value true.

An example:

analytics.load('writekey', { integrations: { All: false, 'Google Analytics': true, 'Segment.io': true } })

Note: To use this feature, you must be on snippet version 4.1.0 or later. You can get the latest version of the snippet here.

This way, you can conditionally load integrations based on what customers opt into on your site. The pseudocode example below shows how you might load only the tools the user consented to.

onConsentDialogClosed(function(consentedTools){
  analytics.load('writekey', { integrations: consentedTools })
})

Retries

When enabled, Analytics.js automatically retries network and server errors. With persistent retries, Analytics.js can:

  • Support offline tracking. Analytics.js queues your events and delivers them when the user comes back online.
  • Better handle network issues. If there happens to be a time where your application can’t connect to Segment’s API, we’ll continue to store the events on the browser to ensure you don’t lose any data.

Analytics.js stores events in localStorage and falls back to in-memory storage when localStorage is unavailable. It retries up to 10 times with an incrementally increasing backoff between each retry. Analytics.js queues up to 100 events at a time to avoid using too much of the device’s local storage. See the destination Retries documentation to learn more.

Proxying Analytics.js

To use a proxy server with Analytics.js, first change the cdn.segment.com address in the snippet to use your own host. Next, contact Segment Product Support and request to change the endpoint Segment sends your events to so that is uses your proxy instead. Make sure that your proxy behaves exactly like the Segment APIs. You can use the Segment proxy server as an example of a correctly-working proxy.

Plugins

Segment offers video player ‘plugins’ so you can quickly collect video events using Analytics.js. See the specific documentation below to learn more:

Cross-Subdomain Analytics

Analytics.js tracks across subdomains out of the box; all of our destinations fully support this feature.

Analytics.js Performance

The Analytics.js library and all of the destination libraries are loaded with the HTML script async tag. This also means that Segment methods are fired asynchronously, so you should adjust your code accordingly if you require that events be sent from the browser in a specific order.

While many tools require access to the DOM or cookies, for our Zendesk, Salesforce, and MailChimp destinations, Segment does not need to load a 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.

Segment only loads the libraries required for your enabled destinations. When you disable a destination, the custom version of Analytics.js loaded on your site stops requesting that library.

Using Analytics.js does not offer a huge performance benefit, but it is more performant than installing each of the destinations individually. And as more destinations move to accept data directly from Segment, you’ll receive more performance benefits automatically.

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

Bundle size

Segment’s Analytics.js javascript snippet only increases the page size by about 1.1KB.

However, the snippet asynchronously requests and loads a customized javascript bundle (analytics.min.js), which contains the code and settings needed to load your device-mode destinations. The size of this file changes depending on how many and which destinations you enable.

Without any destinations enabled, the analytics.min.js file is about 62KB. Each time you enable a destination, the file’s size may increase slightly.

This page was last modified: 05 Aug 2020

Get started with Segment

Segment is the easiest way to integrate your websites & mobile apps data to over 300 analytics and growth tools.
or
Create free account