Google Analytics: Change userID at runtime in a SPA
Asked Answered
A

1

6

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.

Abram answered 30/7, 2014 at 12:40 Comment(0)
B
7

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.

Bower answered 30/7, 2014 at 19:23 Comment(7)
While it is possible to set it outside of the create method, I wouldn't recommend it. Just have it as ga('create', 'UA-XXXX-Y', 'auto', {userID: 'USER ID'});Wheatley
@Wheatley your suggestion won't work here because the OP doesn't know the user ID at create time.Bower
Yup just noting that the set method may or may not work as expected in the long run.Wheatley
@Wheatley using set with userId is officially supported.Bower
Thanks! it works great. Can you please point me where I may find this in the documentation? Thanks.Abram
@Abram developers.google.com/analytics/devguides/collection/…Bower
Is there a way to do the same with GA4? Setting user_id seems to have no effect.Earhart

© 2022 - 2024 — McMap. All rights reserved.