SDK reference

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.

checkout.ts
import { captureException, track } from "@databuddy/sdk";

track("checkout_started", { cart_size: 3 });

try {
  await pay();
} catch (error) {
  captureException(error);
}

Track events and errors

FunctionWhat it does
track(name, properties?)Sends a custom event. Use snake_case names and leave personal data out of properties.
captureException(error)Reports an error you caught to the Errors page, with its message, type and stack. Works whether or not autocapture.errors is on.
setGlobalProperties(properties)Adds these properties to every later event.
flush()Sends queued events now, such as before you send the visitor to another site.
trackError(error, properties?)Deprecated. Sends a custom event named error, which doesn't reach the Errors page.

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.

analytics.d.ts
import "@databuddy/sdk";

declare module "@databuddy/sdk" {
  interface Events {
    signup_completed: { plan: "free" | "pro" };
    invite_sent: { role: string } | undefined;
  }
}

Identify users and their accounts

auth.ts
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();
FunctionWhat it does
identify(userId, traits?)Links this browser to your user ID. Safe on every page load; calling it again with traits updates them. See Identify users.
group(groupType, groupKey, traits?)Puts the visitor in an account, remembered across visits. null leaves it. Billing and usage traits are left out with a warning; send those from your server.
getGroups()The visitor's accounts, such as { workspace: "ws_1" }, to send to your server for evaluateFlags() or the Node SDK. {} while tracking is withheld.
reset({ keepVisitor? })Forgets the user and their accounts and starts new anonymous and session IDs. keepVisitor: true keeps the anonymous visit going after sign-out.
getIds(urlParams?){ anonymousId, sessionId, profileId }. IDs passed in urlParams from another of your domains win. All null while the tracker loads or tracking is withheld.
getRevenueMetadata(clientId?)The IDs to put in Stripe metadata (databuddy_client_id, databuddy_session_id, databuddy_profile_id, databuddy_anonymous_id, databuddy_group_<type>), so revenue is credited to this visit.

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

consent-banner.ts
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".

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.

analytics.ts
import { init } from "@databuddy/sdk";

init({
  clientId: "your-client-id",
  consent: () => !document.cookie.includes("site_consent=denied"),
});
While consent returns falseWhat happens
Before it has returned true on the pageUndecided, as while a consent tool loads. Nothing is sent, but the visitor's IDs are kept and nothing is reported.
After it returned trueA withdrawal. The visitor is forgotten, unsent events are dropped and their opt-out is reported. true again starts a new visitor.
Calls such as track() and identify()Dropped, including ones queued before the script loaded.
getIds(), getTrackingParams(), getGroups()Return nothing.
Session replayStops recording and uploading; it starts again from a full snapshot.

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.

index.html
<script
  src="https://cdn.databuddy.cc/databuddy.js"
  data-client-id="your-client-id"
  data-consent-cookie="analytics_consent=granted"
  async
></script>
Cookie in the browserWhat the tracker does
None with that nameTracks. Set the cookie before the script loads if your website needs consent first.
analytics_consent=grantedTracks.
analytics_consent with any other value, such as deniedSends nothing and forgets the visitor, as a withdrawal does. Tracking starts again, as a new visitor, once it says granted.
Cookies the browser won't let the page readSends nothing.

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.

  1. Visitor opts out
  2. Browser reports its anonymous ID
  3. Databuddy drops events naming it
  4. From browser and server

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.

CaseWhat happens
The SDK knows your client ID, even with disabled: trueoptOut() is reported at once, without a tracker.
It doesn'tThe next page with the tracker or a client ID reports it. Unreported IDs are deleted after 30 days.
Report can't get throughRetried, then sent again from a later page.
More than 30 browser opt-outs an hour from one network on a websiteRefused as rate limited and sent again later. Opt-outs your server records aren't limited.
Session replay recorder older than SDK 3.9.0Keeps uploading recordings of opted-out visitors until you update.

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.

analytics.ts
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}` : ""}`;
FunctionWhat it does
getTrackingParams(urlParams?)The IDs as a query string, databuddy_anonymous_id=…&databuddy_session_id=…, or "" while tracking is withheld.
parseTrackingParams(params)Reads those IDs from a query string or URLSearchParams. Also exported from @databuddy/sdk/node for your server.
TRACKING_PARAMSThe parameter names, for forwarding the IDs through a form field or a server redirect.
linkDomains coversIt doesn't cover
Clicks, middle-clicks, modifier-clicks and links that open a new tab"Open in new tab" from the context menu
GET forms (as fields) and POST forms (in the action's query)form.submit(); use requestSubmit()
Subdomains of each listed domainYour own origin, and non-http(s) links

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.

app/providers.tsx
"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>
  );
}

The IDs are in the address when the page is requested, so your server and its logs can see them. Keep the referrer policy at strict-origin-when-cross-origin, and remove the parameters on your server when that matters.

Load the tracker and check it's running

analytics.ts
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.

statereason
loadingThe script was added and hasn't run yet.
trackingEvents are being sent.
disabledconfig (disabled), opt_out, gpc, storage (site data blocked), consent, bot, localhost (never recorded, except by the debug build), stopped, or unsupported_script (the script is too old for consent or beforeSend).
unavailableserver, not_loaded or script_failed.

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.

How is this guide?