Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the client id while sending data to GA using Measurement protocol?

I have tried using analytics.js (Universal Analytics) through both frontend (js) and backend(Measurement protocol).

When using through frontend (js way):
I check that there is a cookie named _ga whose value is GA1.2.1360127879.1438853622 . And it is sending data to GA with cid=1360127879.1438853622 through request 'http://www.google-analytics.com/collect?...' . I know that 1360127879 is the unique id and 1438853622 is the timestamp.

When using through backend (Measurement Protocol):
I have few questions here:

1. How can i get the client id from browser?

One way is to read the _ga cookie from backend and parse the client id from it.But i read that it is not recommended.Because google can change the format anytime.Somewhere i read that use:

 ga(function(tracker) {
 var clientId = tracker.get('clientId');
 });

But i am not getting how to get the client id in backend using this? I want to use the same client id which frontend is using.

2. What is actually the client id? Is it the unique id alone or the combination of unique_id.timestamp. What should i send to GA from backend?

like image 536
Shobhit_Geek Avatar asked Feb 09 '23 09:02

Shobhit_Geek


1 Answers

If you look at a website that's using the recommend Google Analytics JavaScript Snippet, you'll see that the client ID it's sending looks something like this:

324729700.1423421585

And the value being stored in the _ga cookie looks something like this:

GA1.3.324729700.1423421585

Notice how the last two parts are the same, and just the GA1.3 part is different.

The only part you need to care about is the client ID that's sent to the Measurement Protocol, so if you have access to the _ga cookie from the server, you should strip the GAX.X. prefix and just send the rest.

But i read that it is not recommended. Because google can change the format anytime.

This isn't true. These cookies have a two-year expiration time, so they're probably not going to be changed. And think about it, if Google did change them, data for millions of websites would suddenly be wrong, so there's no good reason for them to do that.

FWIW, the best way to track users server-side is to use the User ID feature, but if your users aren't authenticated, then using the existing client ID is perfectly fine.

Update:

To answer your second question, the timestamp is part of the client ID, do not strip it. The timestamp is used to help make the ID "more unique".

like image 115
Philip Walton Avatar answered Feb 11 '23 22:02

Philip Walton