SDK reference

Node.js

Create one client with an API key and track what happens on your server.

lib/databuddy.ts
import { Databuddy } from "@databuddy/sdk/node";

export const databuddy = new Databuddy({
  apiKey: process.env.DATABUDDY_API_KEY!,
  websiteId: process.env.DATABUDDY_WEBSITE_ID,
});

await databuddy.track({ name: "invoice_paid", properties: { plan: "pro" } });

The API key needs the track:events scope for the website, from API keys. The client never reads environment variables itself.

Send events from serverless functions

Events are batched, so call flush() before a function returns or they can be lost.

app/api/export/route.ts
import { databuddy } from "@/lib/databuddy";

export async function POST() {
  await databuddy.track({ name: "export_completed", groups: { workspace: "ws_1" } });
  await databuddy.flush();
  return Response.json({ ok: true });
}

With batching on, track() usually only confirms the event was queued; flush() returns the delivery result. Delivery failures are returned, never thrown. Only the constructor throws, for a missing apiKey.

Call the client

MethodSendsWhat it does
track(event)QueuedSends a custom event. Returns EventResponse.
batch(events)At onceSends up to 100 events, each with type: "custom".
identify(input)At onceLinks a profileId to the browser's anonymousId and sets traits. See Identify users.
group(input)At onceSets an account's traits, including billing and usage.
optOut(input), optIn(input)At onceRecords or clears a visitor's opt-out. See below.
flush()Sends everything queued. Returns BatchEventResponse.
setGlobalProperties(properties)Adds properties to every later event.
addMiddleware(fn)Edits each event before it's sent; return null to drop it.
track() fieldWhat it does
nameEvent name, required
propertiesEvent properties
eventIdDeduplication key. Databuddy keeps one event per eventId per website for 24 hours, whichever server sent it.
anonymousId, sessionIdThe browser's IDs from getIds(), to join the event to that visitor and session
profileIdThe user ID you passed to identify()
groupsAccounts, such as { workspace: "ws_1" }, sent as group_<type>
websiteId, namespace, sourceOverride the client's defaults for this event
timestampTime in ms

Failed responses carry code (such as NETWORK_ERROR, VALIDATION_ERROR or QUEUE_FULL), why, fix, retryable and statusCode. A group type that isn't lowercase letters, digits and underscores, the reserved type email_domain, or a key over 256 characters fails with VALIDATION_ERROR.

Server events are custom events. They don't create the sessions that referrer, campaign, country and device reports use, and revenue attribution can't join to them. To attribute server activity, send the browser's sessionId from getIds() to your server.

app/api/checkout/route.ts
import { parseTrackingParams } from "@databuddy/sdk/node";
import { databuddy } from "@/lib/databuddy";

export async function POST(request: Request) {
  const { anonymousId, sessionId } = await request.json();
  await databuddy.track({ name: "checkout_started", anonymousId, sessionId });
  return Response.json({ ok: true });
}

export async function GET(request: Request) {
  const ids = parseTrackingParams(new URL(request.url).searchParams);
  await databuddy.track({ name: "signup_link_opened", ...ids });
  return Response.json({ ok: true });
}

parseTrackingParams() reads the IDs a cross-domain link carried, with null for any that is missing or isn't a Databuddy ID.

Configure the client

OptionTypeDefaultWhat it does
apiKeystringRequiredAPI key with track:events
websiteIdstringDefault website for every call
namespacestringDefault namespace, such as billing or auth
sourcestringDefault source, such as webhook or cron
enableBatchingbooleantruefalse sends every track() at once and returns its delivery result
batchSizenumber10Sends the queue at this many events; at most 100
batchTimeoutnumber2000Sends the queue this many ms after the first event; also the first retry wait
maxQueueSizenumber1000Past this many pending events, track() fails with QUEUE_FULL
maxRetriesnumber10Retries after a network error, 429 or 5xx. 0 sends once
requestTimeoutMsnumber10000Most time one send, with its retries, can take
enableDeduplicationbooleantrueSkips an eventId this client already queued or delivered
maxDeduplicationCacheSizenumber10000Event IDs remembered for deduplication
middlewareMiddleware[][]Functions that edit or drop events
anonymizeVisitorIdsboolean | "auto"trueAnonymizes visitor IDs before storage
debugbooleanfalseLogs to the console
loggerLoggerYour own logger
apiUrlstringhttps://basket.databuddy.ccWhere events are sent

Retries send the same event IDs, so an event is stored once. Other 4xx answers, such as an invalid event or key, aren't retried. A failed send doesn't poison the deduplication cache, so you can retry with the same eventId.

Set account traits

jobs/sync-accounts.ts
await databuddy.group({
  groupType: "workspace",
  groupKey: workspace.id,
  traits: {
    name: workspace.name,
    domain: "databuddy.cc",
    billing_plan: "pro",
    billing_status: "active",
    billing_mrr: 49,
    billing_currency: "USD",
    usage_30d: 7920,
    usage_unit: "API calls",
  },
});

People join an account through their events, not through group(). The traits the Accounts page reads are typed as AccountTraits; dates can be Date objects or ISO strings.

TraitWhat the Accounts page does with it
name, domain, logoNames the account; domain also looks up the company
billing_plan, billing_status, billing_trial_ends_atShows how it pays. billing_status takes a Stripe status, or canceling
billing_mrr, billing_currencyMRR in the currency's major unit. Without a currency, it shows as a plain number
billing_customerWho pays; accounts with the same one share a plan
billing_source: nullTakes billing back from a Stripe subscription
created_atKeeps an account older than your tracking from looking new
last_active_atWhen it last used your product, including use your events don't see. Once most accounts seen in the last 28 days have it, one without it is flagged as not started
usage_7d, usage_30d, usage_unitUse over 7 and 30 days in your unit; a week well below the three before is flagged
plan_usage, plan_limitUse against the plan's limit, to flag accounts near it

Record opt-outs from your server

app/settings/actions.ts
await databuddy.optOut({ profileId: user.id });
await databuddy.optIn({ profileId: user.id });

Name the visitor by profileId, the browser's anonymousId, or both. From then on Databuddy drops events naming either ID on that website, from any SDK.

An opt-outCovers
EventsYour server's track(), batch() and identify(), MCP tool calls, and the browser's events, errors, web vitals and recordings
By profileIdEvery browser identify() linked, or later links, to that profile
Events without a website IDDropped too when the visitor opts out on any of your organization's websites
Stripe paymentsStill count as revenue, but aren't credited to the visitor's sessions or traffic source
Session recordingsStop only with the replay recorder from SDK 3.9.0 or later
Stored dataNot removed; see visitor data requests

optIn() clears what optOut() recorded; an opt-out made in the visitor's own browser stays until they opt in there. Opt-outs are per website and logged on your organization's audit log without the visitor's IDs. If Databuddy can't read its opt-out list within a second, it accepts the event rather than hold up ingestion.

How is this guide?