Track events
Import these functions from @databuddy/sdk to track what people do in the browser. Calls made before the tracker loads are queued, and every call does nothing on the server.
import { captureException, track } from "@databuddy/sdk";
track("checkout_started", { cart_size: 3 });
try {
await pay();
} catch (error) {
captureException(error);
}Track events and errors
captureException() follows the rules for automatic errors. Consent and opt-out apply, beforeSend sees an error event, and maskPaths masks its page and stack. A fetch that returns 404 or 500 doesn't throw, so call it where you handle the response.
Type-check your events
Declare your events once and track() checks every call. Until you declare any, it accepts any name and properties.
import "@databuddy/sdk";
declare module "@databuddy/sdk" {
interface Events {
signup_completed: { plan: "free" | "pro" };
invite_sent: { role: string } | undefined;
}
}Identify users and their accounts
import { group, identify, reset } from "@databuddy/sdk";
identify(user.id, { email: user.email, plan: "pro" });
group("workspace", workspace.id, { name: workspace.name });
// On sign-out
reset();The anonymous ID lives in localStorage, and a session ends after 30 minutes without activity. A buyer can edit what their browser sends. Your server should keep only the session and anonymous IDs from getRevenueMetadata(), and set the profile and accounts itself. See Payments.
Let visitors opt out
import { isOptedOut, optIn, optOut } from "@databuddy/sdk";
banner.onDecline(() => optOut());
banner.onAccept(() => optIn());
if (!isOptedOut()) startSupportChat();optOut() stops tracking at once, forgets the visitor's IDs, accounts and cached flags, and is remembered across visits. optIn() resumes tracking with a new visitor; browsers that send Global Privacy Control stay untracked. isOptedOut() is true after optOut() or with Global Privacy Control, and false on the server. Feature flags keep working for opted-out visitors without their stored IDs.
Do Not Track doesn't opt anyone out, because browsers have retired it. To keep honoring it, call optOut() when navigator.doNotTrack === "1".
Ask for consent
When consent is decided elsewhere, such as by a consent tool or a cookie shared with your other websites, pass a consent function instead. It is read before every event, request and retry, and nothing is stored.
import { init } from "@databuddy/sdk";
init({
clientId: "your-client-id",
consent: () => !document.cookie.includes("site_consent=denied"),
});A consent cookie that says no, optOut() and Global Privacy Control always count as a withdrawal. A function that throws withholds consent. DatabuddyProvider and the Vue component read the latest consent and beforeSend props without restarting the tracker. A script tag reads them from window.databuddyConfig, or takes a consent cookie.
An undecided no is never reported, so events your server sends for that visitor are still stored. When your consent tool records a no, call optOut() too.
Use a consent cookie
When your consent tool stores the choice in a cookie, name it instead of writing a consent function: name=value, where value is what the cookie holds when the visitor said yes.
The cookie is read as often as consent, so a banner that changes it takes effect on the next event without a reload. Values are compared after URL decoding, so granted%20all matches granted all, and a rule with no = allows only an empty value. With both consentCookie and consent set, both must allow an event. getStatus() reports a cookie that withholds as consent. Session replay follows the tracker's cookie; set data-consent-cookie on the replay script too when replay loads without the tracker.
When a withdrawal takes effect
optOut() forgets the visitor at once. Everything else that withholds tracking, such as consent and Global Privacy Control, is read again at each input, scroll, ID read, event and delivery. The first observation that finds tracking withheld forgets the visitor and drops unsent events. To withdraw at a known moment, call optOut() rather than writing the opt-out key to localStorage yourself.
Server events after an opt-out
A browser opt-out also stops the events your server sends with that browser's anonymous ID, the one getIds() returns. The browser reports its anonymous ID, and Databuddy drops events naming it on that website.
Events your server sends with only a profileId are still stored, because anyone with your client ID could claim to be any profile from a browser. To stop those for a signed-in visitor who opts out, call optOut({ profileId }) from your server too.
When consent lives in your own records, record it with the Node SDK's optOut(). Databuddy then drops the visitor's events even if no browser reports it.
A full reset() or optOut() also stops the forgotten visitor's ad click IDs, such as gclid, from joining the next visitor. It stores a one-way fingerprint of each until the site data is cleared. UTM parameters name a campaign, not a visitor, so they carry on.
Continue a visit on your other domains
List the other domains you own in linkDomains, and links and forms leading there carry the visitor's IDs as they are clicked or submitted. The other website needs Databuddy too.
import { init } from "@databuddy/sdk";
init({ clientId: "your-client-id", linkDomains: ["shop.databuddy.cc", "dby.sh"] });For a redirect, a form you send with fetch or anything else you build yourself, add getTrackingParams():
import { getTrackingParams } from "@databuddy/sdk";
const params = getTrackingParams();
window.location.href = `https://shop.databuddy.cc/cart${params ? `?${params}` : ""}`;On the receiving page
The other website's tracker adopts the carried IDs, unless the visitor already has their own there, then removes them from the address bar without a new pageview. If your router owns the URL, pass cleanUrl a function that replaces it, or false to leave it alone.
"use client";
import { DatabuddyProvider } from "@databuddy/sdk/react";
import { useRouter } from "next/navigation";
export function Providers({ children }: { children: React.ReactNode }) {
const router = useRouter();
return (
<DatabuddyProvider
cleanUrl={(href) => {
const { pathname, search, hash } = new URL(href);
router.replace(pathname + search + hash, { scroll: false });
}}
>
{children}
</DatabuddyProvider>
);
}Load the tracker and check it's running
import { getStatus, init, ready } from "@databuddy/sdk";
const stop = init({ clientId: "your-client-id", autocapture: { webVitals: true } });
const status = await ready();
if (status.state === "disabled") console.info("Not tracking:", status.reason);init(options) loads the tracker without a framework component, with the same options as DatabuddyProvider, and returns a function that stops it. ready() resolves once the tracker has loaded or can't, within 15 seconds, and never rejects. getStatus() reads the same answer at any time.
When several init() calls or providers run at once, they share one tracker, and every one's consent, beforeSend and disabled must allow an event.
Related
How is this guide?