Cookies and user identification with gtag.js

gtag.js uses cookies to identify unique users across browsing sessions. This guide explains how to customize the cookie settings.

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

Field name Value type Default value
cookie_name string _ga
cookie_domain string auto
cookie_expires integer 63072000 (two years, in seconds)

To change any of these values, update the config for your property to specify them in the parameter list. For example:

gtag('config', 'GA_TRACKING_ID', {
  'cookie_name': 'gaCookie',
  'cookie_domain': 'blog.example.co.uk',
  'cookie_expires': 2419200  // 28 days, in seconds
});

By default, gtag.js has automatic cookie domain configuration enabled. When enabled, automatic cookie domain configuration sets the _ga cookie to the highest level domain it can. For example, if your website address is blog.example.co.uk, gtag.js will set the cookie domain to example.co.uk. If gtag.js detects that you're running a server locally (e.g. localhost), it automatically sets the cookie_domain to 'none'.

To turn off automatic cookie domain configuration, update the config for your property to specify a value for the cookie_domain parameter:

gtag('config', 'GA_TRACKING_ID', {
  'cookie_domain': 'blog.example.co.uk'
});

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 cookie_expires field. This means that if you use the default cookie_expires time of two years, and a user visits your site every month, the user's cookie will never expire.

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

Set User ID

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

To implement the User ID with gtag.js, update the config for your property to set the User ID:

gtag('config', 'GA_TRACKING_ID', {
  'user_id': 'USER_ID'
});