I want to send a google analytics event from the server using the measurement protocol.
The documentation states the cid is required, and should be a UUID (https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#cid).
However, I want to use the same client id as what is stored in the _ga cookie. But according to this, I shouldn't parse the id out of the cookie directly since it could change without warning.
Furthermore, the string returned by tracker.get('clientId') in the browser is not a standard UUID string, so even if I retrieved the value in the browser and sent it to the server, it still isn't in the format the documentation says it should be.
So, what do I need to do to get the client-id from the cookie in a forward compatible way?
Use
ga.getAll()[0].get('clientId');
to get the clientId.Regarding their documentaiton, Google just doesn't want you to grab the cookie directly, and parse it out, as the cookie could change in the future.
The method they outlined is the preferred way to grab the clientId.
Regarding the clientId and using UUID, you can pretty much pass in any value that anonymously identifies somebody (including using GA's clientId).
What we've done is use
ga.getAll()[0].get('clientId');
to grab the client and send it to the server where we can put the clientId into the require parameter for the measurement protocol, and send back a server-side measurement protocol request to GA with transaction data like Cost of Goods sold, etc. Using the clientId allows you to connect the transaction to the source/medium, etc.The right way to get ClientID is to ask tracker by passing a callback.
It has to be called after
ga("create",...)
and the request is:After this you have to call
ga("send"...)
to run the batch of previous settings.If you want to call this out of the initial setting queue, you have to verify, that GoogleAnalytics are already initialized.
You can ask
ga.getAll();
if there is any tracker. If yes, then you can pass callback.If you will use any other way, you can get in troubles early or late.