Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Analytics: Change userID at runtime in a SPA

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.

like image 613
vtortola Avatar asked Jul 30 '14 12:07

vtortola


1 Answers

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.

like image 184
Philip Walton Avatar answered Oct 14 '22 02:10

Philip Walton