GA4 cookies explained

What cookies Google uses and why it’s important to understand what they mean

Autor: Daniil Podtesov

Published: Aug 19th 2024 | 8 min read

Have you ever wondered how Google distinguishes between sessions and users? How does it determine which session is engaged and which isn't? We have, and to answer these questions, we explored the purpose of the GA4 cookies stored a browser after consenting to analytical storage.

What are Google cookies and why is it important to understand what they mean?

Google tools use different cookies for analytics and advertising purposes. In this article, we will explain Google Analytics cookies, which help collect data that allows services to understand how users interact with a particular service. Specifically, we will explore two gtag.js analytics cookies:

  1. _ga (one per device)
  2. *ga*<measurement_id> (one per GA4 property)

These cookies are used to distinguish unique users and their sessions. By understanding their components, we can gain a deeper insight into how GA4 tracks user behavior. Let’s explore how each component of these cookies works.

How to find stored cookies?

To find cookies in your browser, go to Dev Tools (the F12 button) → Application → Cookies.

As we can see in the picture, there’s more than one *ga<measurement_id> cookie but only one _ga cookie. Why is that? The reason is that the website crossmasters.com is being measured to more than one GA4 property and *ga<measurement_id> cookie is used by Google Analytics to identify and track each individual session of your device, whereas _ga is used by Google Analytics to distinguish users. Let’s explain what each cookie means.

As mentioned previously, _ga is the device cookie used by Google Analytics. It enables Google Analytics to distinguish one visitor from another and lasts for 400 days. Any site that implements Google Analytics, including Google services, uses the _ga cookie and each _ga cookie is unique to the specific device. It’s important to mention that this cookie is stored only in cases when a user has consented to analytics storage.

This cookie’s value is composed of several components:

  1. Google Analytics 4 version
  2. Domain level
  3. Random number
  4. Cookie created timestamp

The first digit is fairly easy to understand: it reflects the GA4 version used in tracking.

Domain Level is a number that indicates the level of the domain. For example, "example.com" has a level of 1, while "sub.example.com" has a level of 2. This information helps us understand the structure of a website and its subdomains.

The next parameter doesn’t really have any particular informational value per se but it plays a very important part in the cookie by ensuring the user can be uniquely identified. The Random number generated by GA4 identifies and distinguishes the given visitor on a website.

The last parameter of the _ga cookie is the Cookie Creation Timestamp, a timestamp of the moment the cookie was created. In simpler terms, it is the moment when a visitor created the cookie by visiting a website for the first time in 2 years, or after clearing the cookies in their browser.

As previously mentioned, GA4 uses a cookie as an identifier for a specific device. When the random number and timestamp (the third and fourth components) are extracted from the cookie, this is referred to as the “Effective User ID.” Why is this important? Because if you’ve ever examined the “user_pseudo_id” parameter in BigQuery, you'll notice it has the same structure. Therefore, if you’ve ever wanted to compare GA4 data with BigQuery for the same user or analyze web behavior in BigQuery, you now know which cookie to reference.

The second cookie we will be looking at is *ga*<measurement_id> (one per GA4 property). This cookie value is composed of several components:

  1. GA4 version
  2. Domain level
  3. Session start timestamp
  4. Session count
  5. Engaged session
  6. Last event timestamp
  7. 60-sec countdown
  8. Two unidentified parameters

This cookie’s value thus contains 8 distinct parts, each representing a specific piece of information about the user interaction. The first two numbers (GA4 version and Domain level) are already explained in the previous cookie description, so let’s skip them.

Sessions are the core of web analytics. In GA4 Session ID is a Session Start Timestamp which is the number of seconds elapsed from the 1st of January 1970. It’s also worth mentioning that because, theoretically, multiple sessions can have the same Session Start Timestamp, so to uniquely identify a session Google merges device ID (concatenation of Random number and Cookie Creation Timestamp of the _ga cookie) and Session Start Timestamp value.

Let’s look on our the example and confirm that it is indeed timestamp of the session.

v = new Date(1690013078*1000)
Sat Jul 22 2023 10:04:38 GMT+0200 (Central European Summer Time)

The 2-digit Sessions Count shows how many sessions a user has engaged in. Each session represents a unique period of user activity on the website which can be set up in your GA4 admin settings to fit your purposes.

For example, in our case session expires when a user is inactive for 30 minutes straight.

The Engaged Session metric is a critical tool used to measure whether website users are actively engaged (1) or not (0). Essentially, it functions as a test to gauge the level of interest in your content. By tracking this metric, you can determine the extent to which your website visitors are engaging with your content. If they are sticking around and viewing the various pages on your site, it's a good indication that your content is engaging and relevant to their interests.

One of the key components of the cookie is the Last Event Timestamp. This information reveals when the most recent event took place during the session, providing a snapshot of user activity over time.

Another important component of the cookie is the 60-second Countdown. This feature assists in measuring the length of time users spend on a page, providing valuable insights into user engagement. Please keep in mind, that the meaning behind this parameter was only tested experimentally and wasn’t confirmed by the official GA4 documentation.

Unfortunately it was the last parameter for us that we were able to decipher. The last two parts of the cookie remain unknown.

Conclusion

Understanding the ga and ga<measurement_id> cookies in GA4 is crucial for optimizing website performance and user experience. By analyzing its components, we can gain valuable insights into user behavior and engagement. This information can help businesses and content creators make data-driven decisions that improve their digital presence. We hope this article has provided you with a clear understanding of each component of the ga<measurement_id> cookie and its significance in modern web analytics.

Bonus

So, for those of you who kept reading until the end and who have a feeling that these cookies can help you with a problem you’re facing right now, we prepared a solution that allows you to explore your cookies by yourself in a much simpler form. Below is a script that will do the job for you:

function parseGaCookies() {
    const getCookie = (name) => {
        const value = "; " + document.cookie;
        const parts = value.split("; " + name + "=");
        if (parts.length == 2) return parts.pop().split(";").shift();
    }

    const gaCookies = document.cookie.split('; ').filter(cookie => cookie.startsWith('_ga_'));
    const parsedCookies = [];

    gaCookies.forEach(cookie => {
        const cookieParts = cookie.split('=');
        const cookieNameParts = cookieParts[0].split('_');
        const rawStreamIds = cookieNameParts[2];
        const streamIds = rawStreamIds.split(',').map(id => id.startsWith('G-') ? id : 'G-' + id);
        const duplicateStream = streamIds.length > 1;
        const cookieValue = getCookie('_ga_' + rawStreamIds);

        if(cookieValue.startsWith('GS1')) {
            const components = cookieValue.split('.');

            if (components.length !== 9) {
                console.log("Invalid cookie format. Please make sure to provide a valid GA4 cookie.");
                return;
            }

            const version = components[0].replace('GS', '');
            const domainLevel = components[1];
            const sessionStartAt = new Date(components[2] * 1000);
            const sessionsCount = components[3];
            const engagedSession = components[4];
            const lastEventAt = new Date(components[5] * 1000);
            const countdown = components[6];
            const mysteryZero1 = components[7];
            const mysteryZero2 = components[8];
            const engagedTime = Math.round((lastEventAt - sessionStartAt) / 1000);

            parsedCookies.push({
                "Measurement IDs": streamIds,
                "Version": version,
                "Domain Level": domainLevel,
                "Session Start At": sessionStartAt.toISOString(),
                "Sessions Count": sessionsCount,
                "Engaged Session": engagedSession,
                "Last Event At": lastEventAt.toISOString(),
                "Engaged Time": engagedTime,
                "Countdown": countdown,
                "Mystery Zero 1": mysteryZero1,
                "Mystery Zero 2": mysteryZero2,
                "Duplicate Stream": duplicateStream
            });
        }
    });

    console.log(JSON.stringify(parsedCookies, null, 2));
    return parsedCookies;
}

// Example usage:
parseGaCookies();

To use that script you have to copy it, open the website you want to explore and go to: Dev Tools (F12) → Console. In console you have to paste the script and press Enter

After that the script will automatically identify the cookies you have stored in your browser on the website you’re visiting and will describe them for you.

As for us, we hope that you will find our solution useful 🙂