Update time: January 17, 2025
This article introduces how to get the Client ID as a variable in GTM.
There are many methods:
1st Party Cookie
GA4 will store the Client ID in the first-party Cookie _ga, as follows:
In GTM, click「Variables」——「New」——「Choose a variables type to begin setup…」——「1st Party Cookie」,Name it “cookie_ga”, and make the following settings:
Then create another variable, click「Variables」——「New」——「Choose a variables type to begin setup…」——「1st Party Cookie」,Name it “Client ID-cookie”, and make the following settings:
Finally, preview and debug to see if this variable Client ID-cookie can obtain the Client ID:
Read More:Explanation of Cookie Values Used by Google Analytics 4
gaGlobal
After the GA4 tracking code is loaded, it will be represented as the Client ID in window.gaGlobal.vid, which can be viewed in the browser developer tools:
It can be get through custom JavaScript variables. click「Variables」——「New」——「Choose a variables type to begin setup…」——「1st Party Cookie」,Name it “Client ID-gaGlobal“, and make the following settings:
Next, preview and debug to see if this variable Client ID-gaGlobal can obtain the Client ID:
Note: gaGlobal will be slow to obtain the Client ID and is not recommended.
gtag()
gtag() actually uses the Google tag API, which requires gtag.js to be loaded before it can be used.
If you use GTM, it does not load gtag by default, so it will report an error “gtag is not defined”. If you still want to use it, you need to load it globally:
function gtag() { dataLayer.push(arguments); }
Then you can use gtag. Due to the limitation of code execution, it is not possible to perform the above loading when all data is sent. Therefore, some GA4 tracking may be faster than the above loading, resulting in failure to obtain the Client ID. Therefore, if you use GTM, it is not recommended to obtain it in this way.
customTask
GA4 does not support customTask yet.
Read More: