How to Get Client ID to Variable in GTM?

Google Tag Manager BCS 8 months ago (01-17) 1393 Views 0 Comments

Update time: August 4, 2025

This article introduces how to get the Client ID as a variable in GA4/GTM

You might first consider using First-Party Cookies, Custom JavaScript, or window.gaGlobal.vid. However, these methods may fail to obtain the Client ID, resulting in a “not set”,  I don’t recommend using these methods.

Some people also consider using customTask, which is used in UA, but GA4 doesn’t support it, so it’s also unsuitable.

So, how can GA4 correctly and accurately obtain the Client ID?

  • If you’re hard-coding GA4, use gtag().
  • If you’re installing GA4 through GTM, use the readAnalyticsStorage API.

GA4:gtag()

gtag() actually uses the Google tag API. It requires gtag.js to be loaded before it can be used. That is, gtag can only be used by using the GA4 hard-coded deployment method. The usage is as follows:

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

If you are using GTM, it does not load gtag by default, so you will get an error “gtag is not defined”. If you still want to use it, you need to load it globally:

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

But this will cause problems with the order of execution. If it is not loaded globally, it cannot be used.

 

GTM:readAnalyticsStorage API

This is an API provided by GTM to obtain Client ID/Session ID.

It uses a custom variable template. You need to create a custom variable template and use the readAnalyticsStorage API within it to retrieve the Client ID/Session ID. Some code has been shared, such as this: https://github.com/luratic/ga4_get_client_id_and_session_info. After downloading it, import it into「 Variable Templates」 under 「Templates」:

Then you can use it to create variables, 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:

 

Read More:


If you don't understand, You can leave a comment below.
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