Update time: January 17, 2025
This article introduces how to set the User ID in GA4, also set User ID as a custom dimension(aka:User Properties, User Scope Custom Dimension).
Step 1 : Get User ID
The first step is to obtain the User ID of the user after login through Variable in GTM, there are multiple ways:
- 1st Party Cookie:After the user logs in, the Email ID is stored in the Cookie, and then the 1st Party Cookie is used to obtain it. The disadvantage of this method is that if the cookie is not allowed, the User ID will be lost.
- JavaScript Variable:After the user logs in, store the Email ID in JavaScript Variable, and then use JavaScript Variable to get it.
- Data Layer Variable:After the user logs in, send the Email ID through dataLayer.push, and then use Data Layer Variable to get it.
So I suggest using JavaScript Variable, the code that needs to be added to the page is as follows:
<script> user_id="c046f9efa4a3d9c5bc14a2a56f870933after"; </script>
Since GA4 is not allowed to send PII information, it usually encrypts the sent User ID, such as using its Hash value, assume User ID is Email ID, my Email ID is [email protected], the Hash value is c046f9efa4a3d9c5bc14a2a56f870933after.
Note: This code is required for all pages after login.
In GTM, click 「Variables」——「New」——「Choose a variable type to begin setup…」——「JavaScript Variable」 then name it “User ID”, and configure as follows:
The function of this configuration is to use theJavaScript Variable to obtain the user_id in the JavaScript Variable
Step 2 : Set up User ID
Next, add the variable User ID to the Configuration settings in the GA4 basic page tracking code(Note that this setting is in the GA4 base page tracking code.), such as:
Step 3 : Set up Custom Dimensions
Secondly, create a Google Tag: Event Settings variable in GTM and set it in “Google Analytics User Properties” as follows (If you have already created Google Tag: Event Settings, add user_id_cd settings in Property Name):
Name it “Common Event Parameter”.
Next, set the variable Common Event Parameter to the Event Settings Variable in the GA4 basic page tracking code(Note that this setting is in the GA4 base page tracking code.), such as:
Step 4 : Preview and Release
Finally, Preview testing and release:
The test is as expected and can be released and data collected.
Read More:
Step 5 : Custom Definitions
This custom dimension also needs to be registered in Custom definitions before it can be used. Create a custom dimension as follows in Custom definitions:
Step 6 : Verify data in Real-time Report
Generally, after 24 hours, we can see the data in GA4, such as: