Integrating Mixpanel with ASP.NET MVC server-side and JavaScript client-side

This post is a quick tip, just some notes on an issue I encountered and the work around I found...

To integrate Mixpanel server-side you need to call their REST API. For integrating Mixpanel in .NET there is a library here (currently it isn't listed on the main Mixpanel page). Once you get that, calls to the REST API are fairly straight-forward and I won't go into detail.

The issue I ran into was that if I tracked on JavaScript, I'd lose the identifying information when I went to start tracking events back through the REST API on the server-side. Since most of our users are anonymous I have no real identifying information.  The way to attribute tracking is through the Mixpanel distinctid. The Mixpanel Funnel FAQ gives a quick example of assigning a distinctid yourself, which is another approach. But since they are already assigning one automatically, I decided just to grab the cookie they are putting on the site. This may not be a best practice, but seems to work.

Here's basically how it works...

First track the page view, below is using jQuery and the standard Mixpanel JavaScript call.

$(function () { mixpanel.track('Site Pageview'); //Track page view });  

Then on the server side we'll grab the data from the cookie (note this function is just a simple wrapper I created to get cookie information and parse to JSON)

string cookie = CookieHelper.GetValue("mp_<YOURACCESSTOKEN>_mixpanel");

This will return JSON with distinct_id and a few other details. Now in the C# code we can just send across a click:

//Record to mixpanel API
var tracker = new MixpanelTracker("<YOURACCESSTOKEN");
var properties = new Dictionary<string, object>();
properties["distinct_id"] = cookie["distinctId"];
tracker.Track("Server-side Process", properties);

Now you should be able to track your anonymous users on the client-side and the server-side in ASP.NET MVC.