Google Analytics Tracking Methods

Discover the top 5 ways to track user behavior in Google Analytics, from GA4 to Firebase, with clear benefits for seamless data collection.

Ceyhun Enki Aksan
Ceyhun Enki Aksan Entrepreneur, Maker

Now, as frequently done, I have previously discussed JavaScript code implementations related to web analytics tools.

In some cases, I have mentioned alternative methods for these operations. For example, the pixel code is one of those alternatives. So, what are the options available for evaluation based on Google Analytics?

Google Analytics (GA) Tracking Methods

As is well known, Google Analytics uses two different property (property) formats: Universal Analytics and GA4. Each property is evaluated within its own set of rules and delivers data through integrated reports based on these rules. Universal Analytics has a long history tied to multiple JavaScript libraries, while GA4 is currently being used in a more recent timeframe.

Google Analytics
Google Analytics

Generally, these properties are linked to web sites and applications through JavaScript code. However, in certain situations, we may be required to perform exceptional operations. Outside of JavaScript, for instance, different methods may be required for mobile applications and internet-connected devices. Google Analytics addresses these methods under the headings of websites and web applications, mobile applications, and internet-connected devices1.

Websites and Web Applications

Websites and web applications primarily involve JavaScript code implementations. Google Analytics offers a wide range of tracking libraries, both currently in use and previously used but no longer supported, under the Universal Analytics framework2.

JS - Universal Analytics (UA)

Let’s briefly take a look at the available options, including those that are no longer in use. We’ll start with the ga.js library, which was deprecated in 2017.

note

The GA_MEASUREMENT_ID definition for gtag.js refers only to the legacy property definition created for Universal Analytics; UA-XXXXX-Y. However, GA4 and Google Ads property IDs can also be defined with the config parameter.

Classic Google Analytics
Classic Google Analytics
ga.js

When Google acquired Urchin in 2005, Google began participating in various web technology processes3. Along with developments, Google Analytics released the ga.js library in 20094. This library was developed until 2014 and remained in use until 20175.

The ga.js installation code is as follows:

<script>
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'GA_MEASUREMENT_ID']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>

Access to the ga.js installation code via Google Analytics is no longer available, and documentation now redirects you to the analytics.js library.

Google Analytics
Google Analytics
analytics.js

Google Analytics announced the use of analytics.js in 20136. Following the completion of the development of the ga.js library in 2014, analytics.js became the preferred choice for tracking processes on web pages. This transition can be described as the shift from the classic (classic) Google Analytics property structure to the Universal Analytics property structure. Currently, analytics.js remains available and is actively used by many websites and services.

The setup code for analytics.js is as follows:

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'GA_MEASUREMENT_ID', 'auto');
  ga('send', 'pageview');
</script>

analytics.js is based on the tracker7 and hit type8 structures for sending data to Google Analytics.

Trackers specify which property is being measured, while hit types specify the type of interaction being measured.

gtag.js

gtag.js was announced in beta form in 2017 and has since matured with ongoing updates and new developments, now being offered by default in Google Analytics and Google Ads setup procedures. It is referred to as Global Site Tag due to its ability to be used across different Google services.

The tracking code for gtag.js is as follows:

<script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'GA_MEASUREMENT_ID');
</script>

Unlike analytics.js, properties in gtag.js are defined as config parameters. This setup tag is used for Google Analytics Universal Analytics (UA), GA4, and Google Ads. The config parameter can be used simultaneously for one or more properties9.

gtag('config', 'UA-XXXXX-Y'); // UA MEASUREMENT_ID
gtag('config', 'G-XXXXX'); // GA4 MEASUREMENT_ID
gtag('config', 'AW-XXXXX'); // AW CONVERSION_ID

gtag.js installation code does not use a tracker structure to send data to Google Analytics, unlike analytics.js. Data is sent to the property identifiers specified by the config command. The event definitions provided to gtag.js specify the types of data to be sent to Google Analytics10. My general setup for Google Analytics follows the Global Site Tag installation method.

Google Analytics v4
Google Analytics v4

JS - Google Analytics v4 (GA4)

Along with the increasing adoption of websites and web applications, the need for cross-platform (cross) tracking and device-specific operations led Google to announce in 2019, in beta form, the App + Web property feature. This property structure enables the evaluation of user actions based on pages and screens. Starting in 2020, the App + Web feature was officially released under the name GA411. Unlike the UA property structure, GA4 acquires a property identifier in the format G-XXXXXXXXXX. This same identifier can be used across iOS, Android, and web installations.

Both website and web application installations can be accomplished by adding an additional config definition to the gtag.js code.

gtag('config', 'G-XXXXX'); // GA4 MEASUREMENT_ID

Starting in 2019, Firebase Analytics, also known as Firebase for Google Analytics, was made available as part of the Firebase platform12 13. Firebase Analytics comes with its own reporting structure, but it is also integrated with GA4.

const firebaseConfig = {
  apiKey: "AIzaSyXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", // Your Firebase API key
  authDomain: "your-project-id.firebaseapp.com",
  databaseURL: "https://your-project-id.firebaseio.com",
  projectId: "your-project-id",
  storageBucket: "your-project-id.appspot.com",
  messagingSenderId: "123456789012",
  appId: "1:123456789012:web:abcdef1234567890",
  measurementId: "G-XXXXXXXXXX"
};
...
firebase.analytics();

Firebase Analytics can be linked to GA4 via the gtag.js library, even though it has a separate installation process using the Firebase JavaScript SDK14.

Accelerated Mobile Pages (AMP) also allows the use of the Global Site Tag’s feature in an appropriate way for the amp code structure15.

<script async custom-element="amp-analytics" src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script>
<amp-analytics type="gtag" data-credentials="include">
<script type="application/json">
{
  "vars" : {
    "gtag_id": "<GA_MEASUREMENT_ID>",
    "config" : {
      "<GA_MEASUREMENT_ID>": { "groups": "default" }
    }
  }
}
</script>
</amp-analytics>

Mobile Applications

As mentioned under the heading Websites and Web Applications, Google Analytics also provides tracking solutions for mobile applications developed for iOS16 17 and Android18 19. These operations are carried out through Firebase, Google’s application development platform.

A Firebase SDK installation is required for both platforms. The SDK creates two types of data records: events and user properties.

Events capture user actions, system events, and/or errors occurring within the app, while user properties enable segmentation based on user-defined attributes such as language preference or geographic location.

IMPORTANT RULES:

  1. Maintain the original formatting (markdown, HTML tags, links, etc.)
  2. Keep technical terms and proper nouns as appropriate
  3. Preserve code blocks and technical syntax exactly
  4. Maintain the same tone and style
  5. Only output the translated text, no explanations or comments

In mobile applications, previous versions of Android v4, Android v3, Android v2, Android v1, iOS v3, iOS v2, iOS v1, Unity v4, Unity v3 have been provided. Currently, these development kits are no longer supported.

Measurement Protocol

Measurement Protocol enables tracking of user interactions (events) and page views (hits) on any device connected to the internet. Although previously available for different platforms via Flash/Flex and Silverlight, these libraries are no longer supported in the current version.

Google Analytics sends user interaction data directly to Google Analytics servers via HTTP requests using the Measurement Protocol. This allows for the creation of online-offline user sessions, enables data transmission from client to server, and allows tracking of interactions (hit/event) almost across any environment20.

The Measurement Protocol can also be implemented as a pixel code. This enables email tracking as well21.

<img src="https://www.google-analytics.com/collect?v=1&..." />

MP - Universal Analytics (UA)

Measurement Protocol sends data based on the hit in Universal Analytics and receives a basic HTTP request with the following mandatory parameters22. Google Analytics sends data in two parts via the Measurement Protocol: Transport defines how the data is sent (GET or POST and the endpoint definition), while payload contains the data being sent23.

v=1              // Protocol version.
&tid=UA-XXXXX-Y  // Tracking ID / Property ID.
&cid=555         // Anonymous Client ID.
&t=              // Hit type.

The currently available version is 1. At least one of the Client ID or User ID must be defined in the request. The value 555 for Client ID represents an anonymous user. The aip parameter can be added to the request as a boolean value to prevent the IP address of the requesting client from being recorded.

The hit parameter can take values of pageview, screenview, event, transaction, item, social, exception, or timing. Each value has its own set of parameters. For example, with a pageview, optional page definitions such as URL, Hostname, Path, Title, Content Group, and Link ID can be specified.

POST /collect HTTP/1.1
Host: www.google-analytics.com

v=1&tid=UA-XXXXX-Y&cid=555&t=pageview&dp=%2Fhome

As shown in the above request example, Universal Analytics data sent via the Measurement Protocol is sent to the /collect endpoint. Each request contains a single hit. If multiple hits are required, the /batch endpoint should be used instead of /collect.

POST /batch HTTP/1.1
Host: www.google-analytics.com

v=1&tid=UA-XXXXX-Y&cid=555&t=pageview&dp=%2Fhome
v=1&tid=UA-XXXXX-Y&cid=555&t=pageview&dp=%2Fabout
v=1&tid=UA-XXXXX-Y&cid=555&t=pageview&dp=%2Fcontact

The /batch endpoint has certain limitations.

  • Each request can contain up to 20 hits.
  • The total payload size of all hits must not exceed 16K bytes.
  • The size of any individual hit payload must not exceed 8K bytes.

Errors in definition and formatting can occur during request construction. You can validate the accuracy of your request using the Hit Builder24 tool. For example, the hit definition below includes an event (event) parameter.

v=1              // Version.
&tid=UA-XXXXX-Y  // Tracking ID / Property ID.
&cid=555         // Anonymous Client ID.

&t=event         // Event hit type
&ec=video        // Event Category. Required.
&ea=play         // Event Action. Required.
&el=holiday      // Event label.
&ev=300          // Event value.

You can test this hit definition using Hit Builder and click here for other definitions.

We can send e-commerce events using the Measurement Protocol. Below you can see the request parameters containing the purchase event. To verify and/or modify the request, click here.

v=1                                   // Version.
&tid=UA-XXXXX-Y                       // Tracking ID / Property ID.
&cid=555                              // Anonymous Client ID.
&t=pageview                           // Pageview hit type.
&dh=mydemo.com                        // Document hostname.
&dp=/receipt                          // Page.
&dt=Receipt%20Page                    // Title.

&ti=T12345                            // Transaction ID. Required.
&ta=Google%20Store%20-%20Online       // Affiliation.
&tr=37.39                             // Revenue.
&tt=2.85                              // Tax.
&ts=5.34                              // Shipping.
&tcc=SUMMER2013                       // Transaction coupon.

&pa=purchase                          // Product action (purchase). Required.
&pr1id=P12345                         // Product 1 ID. Either ID or name must be set.
&pr1nm=Android%20Warhol%20T-Shirt     // Product 1 name. Either ID or name must be set.
&pr1ca=Apparel                        // Product 1 category.
&pr1br=Google                         // Product 1 brand.
&pr1va=Black                          // Product 1 variant.
&pr1ps=1                              // Product 1 position.

MP - Google Analytics v4 (GA4)

Important differences exist between Google Analytics Universal Analytics and GA4, both in JavaScript object structures and based on the Measurement Protocol. The Measurement Protocol API provided for GA4 is in alpha version and comes with certain restrictions25.

Operations performed for GA4 receive only event definitions, not hit definitions, and are sent to a different URL and the /collect endpoint (transport). Additionally, this protocol is also available for use with the Firebase platform.

// GA4
const measurement_id = `G-XXXXXXXXXX`;
const api_secret = `<secret_value>`;

fetch(`https://www.google-analytics.com/mp/collect?measurement_id=${measurement_id}&api_secret=${api_secret}`, {
  method: "POST",
  body: JSON.stringify({
    client_id: 'XXXXXXXXXX.YYYYYYYYYY',
    events: [{
      name: 'tutorial_begin',
      params: {},
    }]
  })
});

// Firebase
const firebase_app_id = `1:1234567890:android:321abc456def7890`;
const api_secret = `<secret_value>`;

fetch(`https://www.google-analytics.com/mp/collect?firebase_app_id=${firebase_app_id}&api_secret=${api_secret}`, {
  method: "POST",
  body: JSON.stringify({
    app_instance_id: 'app_instance_id',
    events: [{
      name: 'tutorial_begin',
      params: {},
    }]
  })
});

When using the Measurement Protocol for GA4, the following points should be observed26:

  • Each request can contain a maximum of 25 actions.
  • Each action can accept a maximum of 25 parameters.
  • For action names, a maximum of 40 characters is allowed, using only alpha-numeric characters and underscore. The name must start with alphabetic characters. Predefined action names are not allowed27.
  • Each action can have a maximum of 25 user-defined properties (user properties).
  • For user-defined properties, a maximum of 24-character name definition is allowed.
  • For user-defined properties, a maximum of 36-character value definition is allowed.
  • Parameters can have a maximum of 60 characters, using only alpha-numeric characters and underscore. The name must start with alphabetic characters.
  • Parameter values can have a maximum length of 100 characters.
  • The total data size (body content) carried by the request can be up to 130k bytes.

For GA4 action validation, GA4 Event Builder is used instead of Hit Builder28.

The api_secret and measurement_id request parameters are required for data transmission via GA4 Measurement Protocol. To obtain the api_secret, follow the steps: Admin > Data Streams > Choose your stream > Measurement Protocol > Create, and for measurement_id: Admin > Data Streams > Choose your stream > Measurement ID27.

The client_id, events[], and events[].name keys are required within the JSON body. Below is an example request for the purchase action in GA4.

const measurementId = `G-XXXXXXXXXX`;
const apiSecret = `<secret_value>`;

fetch(`https://www.google-analytics.com/mp/collect?measurement_id=${measurementId}&api_secret=${apiSecret}`, {
  method: "POST",
  body: JSON.stringify({
    "client_id": "client_id",
    "events": [{
      "name": "purchase",
      "params": {
        "affiliation": "Google Store",
        "coupon": "SUMMER_FUN",
        "currency": "USD",
        "items": [{
          "item_id": "SKU_12345",
          "item_name": "jeggings",
          "coupon": "SUMMER_FUN",
          "discount": 2.22,
          "affiliation": "Google Store",
          "item_brand": "Gucci",
          "item_category": "pants",
          "item_variant": "Black",
          "price": 9.99,
          "currency": "USD"
        }],
        "transaction_id": "T_12345",
        "shipping": 3.33,
        "value": 12.21,
        "tax": 1.11
      }
    }]
  })
});

You can click here to verify and/or modify this request.

As a Result

Google Analytics tracking offers various solutions tailored to specific requirements. While events are generally implemented using JavaScript tracking code, alternative and device-based deployment methods may also be preferred, especially due to the dynamic nature of the implementation. The Measurement Protocol enables event tracking to be performed via requests without being restricted by platform or device, allowing us to carry out tracking operations even in scenarios where traditional code deployment is not feasible—for example, using the image tag.

Footnotes

  1. Set up Google Analytics
  2. Daan van den Bergh. (2020). What’s the Difference Between analytics.js, gtag.js & ga.js?
  3. The Associated Press. (2017). Google Acquires Urchin Software. The New York Times
  4. Google Analytics Web Tracking (ga.js) Changelog
  5. Introduction to ga.js (Legacy)
  6. Google Analytics Web Tracking (analytics.js) Changelog
  7. Creating Trackers
  8. Hits, hit types, and the Measurement Protocol
  9. Add an additional Google Analytics property to an existing tag
  10. Upgrade analytics.js
  11. What’s New. Analytics Help
  12. Firebase for Google Analytics
  13. Ken Williams. (2020). What is App + Web? The New Version of Google Analytics
  14. Add the Analytics SDK to your application
  15. Add Analytics to AMP pages
  16. Mobile App Reporting in Google Analytics - iOS
  17. iOS. Get Started
  18. Mobile App Reporting in Google Analytics - Android
  19. Android. Get Started
  20. Measurement Protocol Overview
  21. Email Tracking - Measurement Protocol
  22. Measurement Protocol Parameter Reference
  23. Measurement Protocol Reference
  24. Hit Builder. Google Analytics - Demos & Tools
  25. Limitations. Measurement Protocol (Google Analytics 4)
  26. Sending events. Measurement Protocol (Google Analytics 4)
  27. Measurement Protocol Reference. Measurement Protocol (Google Analytics 4 2
  28. GA4 Event Builder. Google Analytics - Demos & Tools