Simply Stuart Contents

Adding a Mixpanel Proxy to Netlify

September 22, 2023

Mixpanel is a stunning alternative (or companion) to Google Analytics. It has an intuitive UI, generous pricing, great docs, and a focus on event-based analytics. Event-based analytics reduce the noise, helpin you to drill down on the interactions that truly matter for your customers.

Mixpanel proxies

Some ad-blockers block Mixpanel’s js SDKS. To get around dropped events from ad-blockers, Mixpanel recommends using a proxy. However, Mixpanel’s documentation only has an example for nginx, which we don’t have access to if we use hosts like Netlify, so let’s look at how to add proxies in Netlify.

Netlify proxy redirects

In order to proxy requests in Netlify, you have to setup a redirect for each proxy. As of this writing, there are two scripts to proxy and two endpoints:

https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js
https://cdn.mxpnl.com/libs/mixpanel-2-latest.js
https://decide.mixpanel.com/decide
https://api.mixpanel.com/

To proxy the requests in Netlify, redirect traffic from your site or app to Mixpanel for these endpoints. I recommend using a subdomain to make this easier. Below, you’ll see how to do this (using the subdomain mixpanel):

netlify.toml
...
[[redirects]]
from = "https://mixpanel.[YOUR DOMAIN].com/lib.min.js"
to = "https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js"
status = 200
force = true
headers = {X-Forwarded-Host = "https://mixpanel.[YOUR DOMAIN].com"}
[[redirects]]
from = "https://mixpanel.[YOUR DOMAIN].com/lib.js"
to = "https://cdn.mxpnl.com/libs/mixpanel-2-latest.js"
status = 200
force = true
headers = {X-Forwarded-Host = "mixpanel.[YOUR DOMAIN].com"}
[[redirects]]
from = "https://mixpanel.[YOUR DOMAIN].com/decide/*"
to = "https://decide.mixpanel.com/decide/:splat"
status = 200
force = true
[redirects.headers]
Host = "decide.mixpanel.com"
X-Forwarded-Host = "mixpanel.[YOUR DOMAIN].com"
[[redirects]]
from = "https://mixpanel.[YOUR DOMAIN].com/*"
to = "https://api.mixpanel.com/:splat"
status = 200
force = true
[redirects.headers]
Host = "api.mixpanel.com"
X-Forwarded-Host = "mixpanel.[YOUR DOMAIN].com"

Wrapping up

After setting up Mixpanel, commit this to your netlify.toml, push it to production, and that’s it! Hopefully you find this handy for creating apps and experiences that your customers love!

3