The documentation indicates that the userId must be set this way:
ga('create', 'UA-XXXX-Y', { 'userId': 'USER_ID' });
But in a Single Page Application (SPA), the user starts as anonymous and then logs in. So the app will start with:
ga('create', 'UA-XXXX-Y', 'auto');
And when he logs in, then I would like to change to a specific ID for tracking that user, but when I try:
ga('create', 'UA-XXXX-Y', { 'userId': 'USER_ID' });
Nothing happens, the user ID does not appears in subsequent requests.
Which is the right way of setting the userId at runtime?
Thanks.
Unfortunately, the documentation is currently incorrect. It is possible to set the user ID outside of the create
method.
The reason your example isn't working is because you're calling create
twice. What you want to do is call set
. Here's how:
// Create the tracker instance.
ga('create', 'UA-XXXX-Y', 'auto');
// Once you know the user ID, set it on the current tracker.
ga('set', { userId: USER_ID });
Now all subsequent hits sent to GA will be associated with this user ID.
UPDATE:
The user ID documentation now reflects that it can be set outside of the create
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With