Reputation: 814
I need to track when someone is downloading a file from my server, so I created an endpoint that take as parameter a filename.
This endpoint simply sends a GA event and returns the file to the user.
But, as I am server side, I can't easily get the Client ID to send it back to Google Analytics. After some research, this CID is available in the _ga
cookie but Google advise to not count on it as the cookie might change in the future:
So, how can I gather the Client ID server-side to send it back with my event ?
Upvotes: 4
Views: 5592
Reputation: 618
The _ga cookie is generated and used by the analytics.js library and it is the way that Google Analytics identifies users on your site. This value is generated to be stored in the cookie so as far as I know you cannot generate it from an API call for example. Even if you have done your research allow me provide you some information on the _ga value. The value of the cookie as you have seen is something like GA1.2.XXXXXXXXX.XXXXXXXXXX
The part you have to extract to get the CID value that you will send with your server side request is the two last parts of the value separated by a dot(.) meaning:
GA1.2.XXXXXXXXX.XXXXXXXXXX <-- The bold part including the dot in the middle
Also as you have referenced, Google reports that you should not count on the 'name' of the cookie. Meaning that a function like getCookie('_ga') will not be guaranteed to work in the future. But if you keep on reading the analytics tracker object provides a function callback that will provide you with this value guaranteed.
ga(function(tracker) {
var clientId = tracker.get('clientId');
});
The way I would go about it is use this callback, get the CID, send it encrypted in the payload of my request(ex. as an extra parameter), decode it at the server and then send the Measurement Protocol request.
Upvotes: 6