How to Get Client ID to Variable in GTM?

Google Tag Manager BCS 11 months ago (01-17) 2239 Views 0 Comments

Updated: December 12, 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 Analytics Storage  or 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: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 Get Client ID to Variable in GTM?

 

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」:

How to Get Client ID to Variable in GTM?

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:How to Get Client ID to Variable in GTM?

 

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