nickpharris
nickpharris

Reputation: 485

Sharing Google Analytics ClientID between javascript client and java server

I have been using Google Analytics for basic analytics for my web app - just tracking page impressions using javascript calls like this:

ga('create', 'UA-XXXXXXXXX-1', 'mydomain.com');ga('send', 'pageview')

This approach has always frustrated me because I couldn't reliably capture some server-side events. I have just discovered I can use Measurement Protocol to record events server-side. Recording the events on my server looks easy, except regarding the cid (clientid) parameter...

What I understand is that on the browser, with the javascript I currently have the cid gets randomly created and then stored in the _ga cookie. I also understand that I should share that clientid/cid value between client ('page view') and server (other events) calls for the same client so that they are correlated together.

This StackOverflow link was a helpful reference for me.

Question is: should I

  1. Create a clientid on the server and then share it with the client; or
  2. Should I let the javascript on the client create the clientid and then try to share it with my server? (I suspect this is the better answer)

For (1), what I was thinking I could do is:

The thing that worries me about this approach is that the ID will only persist across the session on the server. I think the intent of the clientId (cid) is that it persists for the client over an extended period... So I think I will lose track of who is new versus returning user?

For (2), frankly I don't know how to do this... I know from the above StackOverflow link that I can get the cid out of the clientId parameters in the ga object. I don't know how I would then send it back to my server (this is probably a simple javascript question).

Would definitely appreciate advice on which approach to use.... thank you!

Upvotes: 7

Views: 1107

Answers (1)

Andy H.
Andy H.

Reputation: 526

I would also recommend you go with option 2: Let Google handle setting of cid parameter.

Since the parameter is already set in the _ga cookie on your domain, it is passed to your app server with every HTTP request.

All that you need to do is on the server side :

  1. Extract the CID from the _ga cookie
  2. Link it to the current user (your app probably uses its own session cookies to identify the user)

For example, this answer provides the Rails code:

def save_google_analytics_client_id
    if current_user && cookies["_ga"]
      client_id = cookies["_ga"].split(".").last(2).join(".")
      if current_user.google_analytics_client_id != client_id
        current_user.google_analytics_client_id = client_id
        current_user.save
      end
    end
  end

Upvotes: 3

Related Questions