Cookies and User Identification

In order for Google Analytics to determine that two distinct hits belong to the same user, a unique identifier, associated with that particular user, must be sent with each hit.

The analytics.js library accomplishes this via the Client ID field, a unique, randomly generated string that gets stored in the browsers cookies, so subsequent visits to the same site can be associated with the same user.

By default, analytics.js uses a single, first-party cookie named _ga to store the Client ID, but the cookie's name, domain, and expiration time can all be customized. Other cookies created by analytics.js include _gid, AMP_TOKEN and _gac_<property-id>. These cookies store other randomly generated ids and campaign information about the user.

Using cookies allows analytics.js to identify unique users across browsing sessions, but it cannot identify unique users across different browsers or devices. If your site has its own authentication system, you can use the User ID feature, in addition to the Client ID, to more accurately identify a user across all the devices they use to access your site.

This guide explains how to customize the cookie settings as well as how to set the user ID field to more accurately measure user activity across sessions.

The following table shows the default cookie field values used by analytics.js:

Field Name Value Type Default value
cookieName text _ga
cookieDomain text The result of the following JavaScript expression:
document.location.hostname
cookieExpires integer 63072000 (two years, in seconds)
cookieUpdate boolean true
cookieFlags text

To modify any of these values, you can specify them in the fieldObject you pass the create command. For example:

ga('create', 'UA-XXXXX-Y', {
  'cookieName': 'gaCookie',
  'cookieDomain': 'blog.example.co.uk',
  'cookieExpires': 60 * 60 * 24 * 28  // Time in seconds.
  'cookieUpdate': 'false',
  'cookieFlags': 'SameSite=None; Secure',
});

The most common cookie field to set is cookieDomain, as such, the create command accepts the cookieDomain field as an optional third parameter for convenience:

ga('create', 'UA-XXXXX-Y', 'blog.example.co.uk');

The recommended Google Analytics tag sets the string 'auto' for the cookieDomain field:

ga('create', 'UA-XXXXX-Y', 'auto');

Specifying 'auto' as the cookieDomain enables automatic cookie domain configuration, which tells analytics.js to automatically determine the best cookie domain to use.

Automatic cookie domain configuration sets the _ga cookie on the highest level domain it can. For example, if your website address is blog.example.co.uk, analytics.js will set the cookie domain to .example.co.uk. In addition, if analytics.js detects that you're running a server locally (e.g. localhost) it automatically sets the cookieDomain to 'none'.

Every time a hit is sent to Google Analytics, the cookie expiration time is updated to be the current time plus the value of the cookieExpires field. This means that if you use the default cookieExpires time of two years, and a user visits your site every month, their cookie will never expire.

If you set the cookieExpires time to 0 (zero) seconds, the cookie turns into a session based cookie and expires once the current browser session ends:

When cookieUpdate is set to true (the default value), analytics.js will update cookies on each page load. This will update the cookie expiration to be set relative to the most recent visit to the site. For example, if cookie expiration is set to one week, and a user visits using the same browser every five days, the cookie expiration will be updated on each visit and so will effectively never expire.

When set to false, cookies are not updated on each page load. This has the effect of cookie expiration being relative to the first time a user visited the site.

Appends additional flags to the cookie when set. Flags must be separated by semicolons.

You should not directly access the cookie analytics.js sets, as the cookie format might change in the future. Instead, developers should use the readyCallback to wait until analytics.js is loaded, and then get the clientId value stored on the tracker.

ga(function(tracker) {
  var clientId = tracker.get('clientId');
});

Disabling Cookies

In some cases you might want to use your own storage mechanism (such as localStorage or a Service Worker) to persist the Client ID across sessions without using cookies. You can disable analytics.js from setting cookies by setting the storage field to 'none'.

ga('create', 'UA-XXXXX-Y', {
  'storage': 'none'
});

If you're storing the clientId field yourself, you'll need to make sure to set the cliendId field when you create the tracker.

ga('create', 'UA-XXXXX-Y', {
  'storage': 'none',
  'clientId': '76c24efd-ec42-492a-92df-c62cfd4540a3'
});

To disable the _gac_<property-id> cookies, set the storeGac field to false in the create command:

ga('create', 'UA-XXXXX-Y', {
  storeGac: false,
});

Using localStorage to store the Client ID

The following code sample shows how you could modify the JavaScript tag to use localStorage to store the Client ID rather than cookies:

var GA_LOCAL_STORAGE_KEY = 'ga:clientId';

if (window.localStorage) {
  ga('create', 'UA-XXXXX-Y', {
    'storage': 'none',
    'clientId': localStorage.getItem(GA_LOCAL_STORAGE_KEY)
  });
  ga(function(tracker) {
    localStorage.setItem(GA_LOCAL_STORAGE_KEY, tracker.get('clientId'));
  });
}
else {
  ga('create', 'UA-XXXXX-Y', 'auto');
}

ga('send', 'pageview');

User ID

User ID enables the analysis of groups of sessions, across devices, using a unique, persistent, and non-personally identifiable ID string representing a user. To learn why you should implement the User ID, see Benefits of using the User ID feature.

To implement the User ID with analytics.js:

  1. Provide your own unique, persistent, and non-personally identifiable string ID to represent each signed-in user. This ID is most often provided by an authentication system.
  2. Set the User ID on the tracker:
ga('create', 'UA-XXXXX-Y', 'auto', {
  userId: USER_ID
});
ga('send', 'pageview');

Handling authentication after pageload

When building Single Page Applications or other dynamic websites that handle user sign-in after the initial page load, the process of setting the user ID value on the tracker can't happen at creation time.

In such cases, you can use the set command to set the value on the tracker as soon as it's known.

// Creates the tracker and sends a pageview as normal
// since the `userId` value is not yet known.
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');

// At a later time, once the `userId` value is known,
// sets the value on the tracker.
ga('set', 'userId', USER_ID);

// Setting the userId doesn't send data to Google Analytics.
// You must also use a pageview or event to send the data.
ga('send', 'event', 'authentication', 'user-id available');

When using this approach, hits sent before the userId field is set will not contain user ID values. However, through a process known as Session Unification, Google Analytics is able to associate these hits with the correct user at processing time.