Server-side conversion tracking from a Stripe webhook

Server-side conversion tracking from a Stripe webhook records sales ad blockers drop, joins guest browsing to the buyer's account and never breaks checkout.

By

Browser analytics is weakest at the one event you care about most. The buyer pays on Stripe's page, and the script that should report the sale may be blocked, or the tab may already be closed. When I added Mixpanel to a photo marketplace, I moved the completed purchase out of the browser and into the Stripe webhook. This post covers that server-side conversion tracking setup: why the webhook is the right place for it, how a device id carried through Stripe metadata joins guest browsing to the account the purchase creates, and the rules that keep analytics from ever getting in the way of a payment.

Why the browser loses your most important event

A purchase event sent from the page depends on a chain of things going right. The analytics script has to load, the buyer has to come back from the payment page, and the tab has to stay open long enough for the request to leave. Two ordinary things break that chain: an ad blocker and a closed tab. Neither shows up as an error anywhere. Your sales numbers are just lower than your payments, and you cannot tell which sales are missing.

Stripe knows about the payment whatever the browser does. The Stripe webhook documentation describes how it pushes events to your endpoint, and in live mode it keeps trying to deliver them for up to three days. That makes the webhook a far more dependable place to record a sale than a thank-you page.

So I split the work by what each side can see. The browser reports the journey: search, image viewed, license selected, added to or removed from cart, cart and checkout viewed, checkout form errors, checkout started, payment cancelled, failed or succeeded, downloads, sign-up, login and logout. The server reports the completed purchase, because that one has to survive whatever happens on the visitor's device.

What is server-side conversion tracking?

Server-side conversion tracking means your backend reports a conversion to your analytics tool, triggered by the system that knows it happened, such as a payment webhook. Ad blockers and closed tabs cannot stop it, because no browser is involved. The catch is that the server has no idea what the visitor did before paying, so you have to carry an identifier across yourself.

Carry the device id through Stripe metadata

That identifier is the difference between a useful purchase event and a lonely one. Guests on this site are tracked under Mixpanel's anonymous id, and a guest's first purchase creates their account. If the webhook only sends the new user id, the sale sits on a fresh profile with no history, and you lose the path that led to it.

The fix is to pass the browser's device id along with the order. The browser reads it when checkout starts, the server stores it in the Stripe session's metadata, and the webhook reads it back. With names simplified:

// Browser, when the buyer starts checkout
const deviceId = mixpanel.get_property('$device_id');
await api.createCheckout({ ...order, deviceId });

// Server, when creating the Stripe session
const session = await stripe.checkout.sessions.create({
  ...params,
  metadata: deviceId ? { device_id: deviceId } : {},
});

Mixpanel's simplified ID merge guide explains why this works. An event carrying both $device_id and $user_id links the two, and the earlier anonymous events then belong to that user. One event from the webhook joins a guest's earlier browsing to the account the purchase created.

Two things I would keep in mind if you copy this. The device id comes from the client, so check that it is a string and cap its length before you store it. And it can be missing, for example when the analytics script was blocked. The purchase should still be recorded in that case, without the join. A sale with no history beats no sale.

Analytics must never throw inside the webhook

The webhook has real work to do: mark the order paid, create the account, send the receipt. Analytics is the least important thing in that handler, and it must behave that way. If a call to an analytics API throws, the delivery fails, and Stripe retries a paid order for the sake of a chart.

My rule on this project: the tracking call is off when MIXPANEL_TOKEN is unset, and it never throws inside the webhook. The shape, trimmed:

export async function trackPurchase(event: PurchaseEvent) {
  const token = process.env.MIXPANEL_TOKEN;
  if (!token) return;
  try {
    const res = await fetch('https://api.mixpanel.com/track', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify([{
        event: 'Purchase Completed',
        properties: { token, ...event },
      }]),
      signal: AbortSignal.timeout(5000),
    });
    if (!res.ok) console.error('Analytics rejected', res.status);
  } catch (err) {
    console.error('Analytics failed', err);
  }
}

The timeout matters as much as the try. Stripe wants a quick 2xx, and a slow third party should not hold your handler open.

Stripe can also deliver the same event more than once, so plan for duplicates. Mixpanel deduplicates on $insert_id, which must be 36 bytes or fewer and contain only letters, digits and hyphens. A Stripe session id breaks both limits, so my default is to hash it. Mixpanel only treats two events as duplicates when the event name, time, distinct id and insert id all match, so take the time from Stripe's event, which stays the same across retries, and avoid the clock at the moment of delivery.

One more server-side quirk: Mixpanel uses the request's IP for geolocation by default, so server events get placed where your server is unless you override it.

Anonymous, then identify, then reset

Joining the purchase only works if identity is handled the same way everywhere. The lifecycle on this site has three steps.

  • Guest: events go out under Mixpanel's anonymous id, with no account needed.
  • Login: identify is called with the user id, so earlier guest activity joins the account.
  • Logout: reset clears the identity and starts a new anonymous id. Without it, the next person on a shared computer gets counted as the last one.

The webhook slots into the same model. It behaves like a login that happens on the server, tying a device to a user at the moment of purchase. If you run reminder emails off the same purchases, the skip rules in my post on abandoned cart reminders that never double-send depend on knowing who has already bought.

Send checkout started by beacon before the redirect

Checkout started is the last event the browser sends before leaving for Stripe, and it is easy to lose. Analytics libraries batch events, and a page navigation can kill whatever is still queued. For this one event, I send it by beacon, immediately:

mixpanel.track('Checkout Started', props, {
  transport: 'sendBeacon',
  send_immediately: true,
});

sendBeacon hands the request to the browser so it can finish after the page goes away. Keep it for moments like this one, because the Mixpanel library's own notes warn that it gives you no callback. Without this event, you cannot tell how many people started paying and never finished, which is the funnel step you most want to see.

Keep tracking cheap and away from private data

The rest of the setup is about cost and restraint.

  • Admin is never tracked. Admin pages and admin users stay out entirely, so staff activity never mixes into customer funnels.
  • The library loads lazily. It weighs 35 KB gzipped and stays out of the first load. The session replay recorder comes from Mixpanel's CDN, and only when a recording starts.
  • Form fields are masked in replay. Autocapture records page views, clicks, scroll depth and form use, and replay shows how people move through a page. Typed values stay masked, and account pages carry the mp-mask class.
  • No token means no tracking. The same switch applies in the browser and on the server, so an environment without a token stays quiet.

I have no before and after figure to share here, because this was the site's first Mixpanel setup. The argument for the design is structural: a sale recorded from the webhook does not depend on the visitor's browser at all.

If your purchases come through an app store provider, the webhook is also a security boundary, which I covered in webhook security for in-app purchases. And if a webhook handler is getting slow, the same thinking as replying first and fanning out later applies: do what the caller needs, then move on.

Where I'd start

  1. Record completed purchases from the payment webhook, and keep the browser for the journey.
  2. Pass the device id through Stripe metadata, and allow for it being missing.
  3. Wrap the analytics call so it cannot throw, give it a timeout, and turn it off when the token is unset.
  4. Give the event a stable $insert_id and time so retries do not count twice.
  5. Follow anonymous, identify, reset in the browser, and send the last event before a redirect by beacon.
  6. Leave admin traffic out, load the library lazily and mask form fields in replay.

More of my backend and full stack work is on the projects page.

Want this kind of work on your product?

Get in touch