Mixpanel in React: typed events, no cookies, EU endpoint

By · · React · 7 min

How I set up Mixpanel in a React and TypeScript app so that event names can't be misspelt, nothing is stored in cookies or local storage, and all data goes to Mixpanel's EU servers. With the session replay trade-off spelled out.

This is the Mixpanel setup I use in Nebula·3, a synthesizer that runs in the browser. It is a React and TypeScript app with no login, no accounts and no backend, which makes it a clean example: the only thing I want to know is how people use it.

What you'll learn

  • How to make every Mixpanel event a TypeScript type, so a typo fails the build
  • How to run Mixpanel without cookies or local storage, and what you give up for it
  • How to send data to Mixpanel's EU endpoint and keep development traffic out
  • How to keep high-frequency interactions from drowning your reports
  • What changes when you switch on session replay

Start with the questions, not the events

Tracking everything is easy and useless. For a synth, the questions were short:

  1. Which presets do people pick, and how do they get to them?
  2. Do they actually play, or only listen to the preview?
  3. Does anyone connect a MIDI keyboard?

Those three questions became eight events. Every event I was tempted to add had to answer one of them.

One union type for every event

The whole tracking plan is one TypeScript union. Each member has a name and the exact properties that event carries:

export type AnalyticsEvent =
  | {
      name: "preset_selected";
      props: {
        preset_name: string;
        preset_bank: string;
        method: "browser" | "step_button" | "arrow_key" | "bank_button";
        is_previewing: boolean;
      };
    }
  | {
      name: "note_played";
      props: {
        preset_name: string;
        preset_bank: string;
        input: "pointer" | "computer_keyboard" | "midi";
      };
    }
  | { name: "midi_connected"; props: { device_count: number } };
// ...five more

The track function is generic over the event name, and looks up the matching properties:

export function track<N extends AnalyticsEvent["name"]>(
  name: N,
  props: Extract<AnalyticsEvent, { name: N }>["props"]
) {
  if (!live) {
    if (import.meta.env.DEV) console.debug("[analytics]", name, props);
    return;
  }
  void load().then((m) => m.track(name, props));
}

Now track("preset_selcted", ...) is a compile error, and so is forgetting preset_bank or passing input: "mouse". The union doubles as documentation: anyone building a Mixpanel report can read one file and know every event and property that exists.

Two conventions keep the data tidy later: snake_case for event and property names, and booleans prefixed with is_.

Mixpanel without cookies or local storage

By default the Mixpanel SDK stores a distinct id in a cookie or in local storage, so it can recognise a returning visitor. You can turn that off:

mixpanel.init(TOKEN, {
  api_host: "https://api-eu.mixpanel.com",
  disable_persistence: true,
  batch_requests: false,
  ip: false,
  track_pageview: false,
  autocapture: false,
});

What each option does:

  • disable_persistence: true stops the SDK from writing its cookie or local storage entry. The anonymous id then lives only as long as the page.
  • batch_requests: false matters more than it looks. Batching keeps a send queue in local storage, so with batching on, the SDK still writes to the device. Sending each event straight away avoids that.
  • ip: false tells Mixpanel not to derive a location from the visitor's IP address.
  • autocapture: false and track_pageview: false mean only the events in the union are sent, plus one page view I fire by hand.

The price is real: every page view is a new anonymous visitor. You can't measure retention or returning users, and funnels only work within a single visit. For a toy instrument that is an acceptable trade. For a product with accounts it usually isn't, and you would call identify after login instead.

EU data residency

If your Mixpanel project is set to EU data residency, the SDK has to send to the EU endpoint, https://api-eu.mixpanel.com. Leave api_host at its default and events go to the US endpoint and never show up in an EU project. It is a one-line setting that is easy to miss, because nothing errors.

Keep development out of your data

Two guards, both in the same file:

const TOKEN = import.meta.env["VITE_MIXPANEL_TOKEN"] as string | undefined;
const live = import.meta.env.PROD && !!TOKEN;

Only a production build with a token sends anything. In development, track logs the event to the console, which is also the fastest way to check that an event fires once and carries the right properties.

The SDK itself is loaded with a dynamic import("mixpanel-browser") the first time it is needed. That keeps it out of the initial bundle and means it never runs during server-side rendering.

Record the first time, not every time

A synth produces a note event for every key press. Sending all of them would bury everything else and tell me nothing new. So the noisy events are recorded once per preset:

if (played.current !== patch.name) {
  played.current = patch.name;
  track("note_played", {
    preset_name: patch.name,
    preset_bank: patch.bank.toLowerCase(),
    input,
  });
}

The same goes for the first knob edit and the first mod wheel move. The question was "did they play this preset, and with what?", and one event answers it.

Automated behaviour is excluded too. Nebula·3 has a hands-free demo tour that switches presets by itself; those switches don't send preset_selected, because nobody selected anything.

Properties that ride along with every event

Some context belongs on every event. register adds it once:

mixpanel.register({
  entry_point: new URLSearchParams(location.search).has("showcase") ? "showcase" : "direct",
  is_midi_supported: "requestMIDIAccess" in navigator,
  theme,
});

With that, any report can be split by how the visitor arrived or by the colour theme they were using, without repeating those properties at every call site.

Session replay changes the picture

Events tell you what happened. Session replay shows you how: where someone hesitated, which control they tried to drag on a phone. I switched it on for the mobile layout work:

mixpanel.init(TOKEN, {
  // ...the options above
  record_sessions_percent: 100,
  record_heatmap_data: true,
});

Be honest with yourself about what this does to the "stores nothing" setup. The recorder buffers its data in IndexedDB before sending it, so the app now does write to the visitor's device, even with persistence disabled. Text is masked by default and form inputs stay masked; I unmasked text because nothing on the page is personal.

Whether replay needs consent in your situation depends on what your pages show and where your visitors are. That is a question for whoever handles privacy for the project, not something a config option settles.

The short version

  • Put every event in one TypeScript union and make track generic over it.
  • disable_persistence plus batch_requests: false keeps event tracking off the visitor's device; you lose returning-visitor data.
  • Set api_host to the EU endpoint for an EU project.
  • Send only from production builds, log to the console in development.
  • Record noisy interactions once per meaningful unit.
  • Treat session replay as a separate decision with its own storage and privacy implications.

The full case study, including a recording of a real session replay, is at Nebula·3. If you want this set up in your own product, see product analytics with Mixpanel.

Related reading