Google Analytics: Changing Runtime User ID in SPA

The documentation indicates that userId should be set as follows:

ga('create', 'UA-XXXX-Y', { 'userId': 'USER_ID' }); 

But in a single page application (SPA), the user starts up as anonymous and then logs in. Therefore, the application will start with:

 ga('create', 'UA-XXXX-Y', 'auto'); 

And when it logs in, I would like to switch to a specific identifier to track this user, but when I try:

 ga('create', 'UA-XXXX-Y', { 'userId': 'USER_ID' }); 

Nothing happens, the user ID does not appear in subsequent requests.

What is the correct way to set userId at runtime?

Thanks.

+6
source share
1 answer

Unfortunately, the documentation is currently incorrect. You can set the user ID outside the create method.

The reason your example does not work is because you call 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.

+7
source

Source: https://habr.com/ru/post/973098/


All Articles