How to Capture the Client ID as a Variable in GTM

Google Tag Manager BCS 1 years ago (2025-01-17) 2704 Views 0 Comments

Updated: December 12, 2025

This article explains how to capture the Client ID as a variable in GA4 or GTM. You might initially think of using first-party cookies, custom JavaScript, or window.gaGlobal.vid. However, these approaches often fail to retrieve the Client ID, returning “not set,” so I don’t recommend them.

Some may also consider using customTask, which was available in Universal Analytics, but GA4 doesn’t support it, making it unsuitable as well.

So, how can you reliably and accurately get the Client ID in GA4?

  • If you’re implementing GA4 with hard-coded gtag(), you can access the Client ID directly through gtag().
  • If you’re using GTM to deploy GA4, the recommended approach is to use the Analytics Storage or the readAnalyticsStorage API.

GA4:gtag()

gtag() is essentially a wrapper for the Google Tag API and requires gtag.js to be loaded before it can be used. This means gtag() is only available when GA4 is deployed via the hard-coded method. The usage looks like this:

gtag('get', 'YOUR_MEASUREMENT_ID', 'client_id', (client_id) => {
    // do something with client_id
})

f you are deploying GA4 through GTM, gtag is not loaded by default, and calling it will trigger a "gtag is not defined" error. You could attempt to make it available globally:

function gtag() { dataLayer.push(arguments); }

However, this approach often leads to execution-order issues. In short, without loading it globally beforehand, gtag() cannot be reliably used in GTM setups.

 

GTM:Analytics Storage

Analytics Storage is a built-in variable in GTM that can retrieve the Client ID, Session ID, and Session Number.

In GTM, click「Variables」——「New」——「Choose a variables type to begin setup…」——「 Analytics Storage」,Name it “Client ID“, and make the following settings:How to Capture the Client ID as a Variable in GTM

 

GTM:readAnalyticsStorage API

This is an API provided by GTM for retrieving the Client ID and Session ID.

It works through a custom variable template. To use it, you need to create a custom variable template that leverages the readAnalyticsStorage API to access the Client ID and Session ID. Some ready-to-use code is available here: https://github.com/luratic/ga4_get_client_id_and_session_info. After downloading it, import it into「 Variable Templates」 under 「Templates」in GTM:

How to Capture the Client ID as a Variable in GTM

Once imported, you can create variables as follows, in GTM, click「Variables」——「New」——「Choose a variables type to begin setup…」——「GA4 – Get Client Id & Session Info (Safe API)」,Name it “Client ID“, and make the following settings:How to Capture the Client ID as a Variable in GTM

 

 

 

 

Read More:

Like (0)
Post my comment
Cancel comment
Expression Bold Strikethrough Center Italic

Hi, you need to fill in your nickname and email!

  • Nickname (required)
  • Email (required)
  • Website