Tracking recipes

Toast tracking

Mount one hook near the root, and every Sonner toast is tracked once.

hooks/use-toast-tracking.ts
import { track } from "@databuddy/sdk";
import { useEffect, useRef } from "react";
import { useSonner } from "sonner";

export function useToastTracking() {
  const { toasts } = useSonner();
  const tracked = useRef(new Set<string | number>());

  useEffect(() => {
    for (const toast of toasts) {
      if (tracked.current.has(toast.id)) continue;
      tracked.current.add(toast.id);
      track("toast_shown", {
        type: toast.type ?? "default",
        message: typeof toast.title === "string" ? toast.title : undefined,
      });
    }
  }, [toasts]);
}
app/providers.tsx
"use client";

function ToastTracker() {
  useToastTracking();
  return null;
}

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <>
      <ToastTracker />
      {children}
    </>
  );
}

What it sends

EventPropertyValue
toast_showntypeSonner's type, such as success, error or default
messageThe toast's title, when it's text

Leave message out if your toasts can include personal data.

How is this guide?