Obtaining GA4 Client ID via gtag.js without GTM: A Step-by-Step Guide

Are you using Google Analytics 4 (GA4) analytics code embedded through gtag.js? If so, this guide will help you seamlessly extract your Client ID for enhanced tracking and analysis. Whether you’re aiming to verify the implementation or want to set up user properties, we’ve got you covered. Let’s dive into the process step by step.

1. Retrieving the Client ID

To obtain the Client ID, we’ll make use of the following code snippet. This code ensures that your GA4 analytics code doesn’t truncate the value:

<!-- Google Analytics -->
function getGAValue() {
    var match = document.cookie.match('(?:^|;)\\s*_ga=([^;]*)'),
        raw = match ? decodeURIComponent(match[1]) : null;
    if (raw) {
        match = raw.match(/(\d+\.\d+)$/)
    }
    return (match) ? match[1] : null;
}
<!-- End Google Analytics -->

var ga_client_id = getGAValue() + '.';

2. Transferring the Client ID to GA4

To seamlessly transfer your variable (Client ID) to GA4, follow these steps:

a. Include the gtag.js script on your website. Replace {STREAM_ID} with your actual GA4 stream ID.

<script async src="https://www.googletagmanager.com/gtag/js?id={STREAM_ID}"></script>

b. Implement the gtag.js code with user properties to set up the Client ID. This ensures your variable is correctly integrated into your GA4 analytics:

<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', '{STREAM_ID}', {
    'user_properties': {
      client_id: ga_client_id
    }
  });
</script>

3. Verification and Debugging

To ensure the correctness of your implementation, you can perform the following steps:

  • Use the Realtime report to monitor incoming hits.
  • Utilize the Debug View (consider installing an extension to facilitate hit tracking).
  • Confirm your Client ID’s presence and accuracy in reports, as well as the Debug View.

By following these steps, you’ll be equipped to effectively retrieve and utilize your GA4 Client ID via gtag.js. Enhance your tracking capabilities and unlock valuable insights for informed decision-making.

Pawan Rai
DevOps Engineer at SprigHub
Cookie Value: