# Databuddy Documentation (Full)

> Cookieless web analytics with events, errors, funnels, and optional user identification.
> This file contains the highest-priority documentation sections for long-context agents,
> truncated at a size limit. For the rest, use the scoped indexes at
> https://www.databuddy.cc/docs/llms.txt, https://www.databuddy.cc/api/llms.txt, and
> https://www.databuddy.cc/developers/llms.txt.

## Developer Resources
- [Databuddy Developer Resources](https://www.databuddy.cc/developers): Canonical index of Databuddy API docs, OpenAPI, MCP, SDK, auth, and webhook resources.
- [Databuddy Developer Docs](https://www.databuddy.cc/docs): SDK setup, REST API guides, feature flags, Web Vitals, privacy, and integrations.
- [Databuddy API Docs](https://www.databuddy.cc/docs/api): Authentication, rate limits, analytics queries, events, and links.
- [Databuddy OpenAPI Spec](https://www.databuddy.cc/openapi.json): Machine-readable OpenAPI 3.1 schema for Databuddy's REST API.
- [Databuddy API Catalog](https://www.databuddy.cc/.well-known/api-catalog): RFC 9727 linkset catalog for Databuddy API and machine-readable specs.
- [Databuddy API Reference](https://api.databuddy.cc): Interactive API reference generated from the OpenAPI schema.
- [Databuddy API Authentication](https://www.databuddy.cc/auth.md): MCP sign-in with a Databuddy account over OAuth, API key headers for the REST API and headless MCP use, bearer tokens, scopes, and access levels.
- [Databuddy Agent Discovery](https://www.databuddy.cc/.well-known/agent.json): Machine-readable agent discovery file with capabilities, endpoints, auth, and when-to-use guidance.
- [Databuddy A2A Agent Card](https://www.databuddy.cc/.well-known/agent-card.json): Agent card that points A2A agents to the Databuddy MCP server. Databuddy has no A2A message endpoint.
- [Databuddy MCP Server](https://www.databuddy.cc/docs/api/mcp): Model Context Protocol sign-in setup for Claude, Claude Code, Codex, Cursor, VS Code, ChatGPT, and other MCP clients.
- [Databuddy MCP Manifest](https://www.databuddy.cc/.well-known/mcp.json): Machine-readable MCP discovery manifest pointing to the Streamable HTTP server.
- [Databuddy MCP Server Card](https://api.databuddy.cc/v1/mcp/server-card): MCP Server Card (SEP-2127) with the server's identity, Streamable HTTP endpoint, supported protocol versions, and sign-in hints.
- [Databuddy AI Catalog](https://www.databuddy.cc/.well-known/ai-catalog.json): AI Catalog at the well-known URI that lists the Databuddy MCP Server Card for domain-level discovery.
- [Databuddy SDK Docs](https://www.databuddy.cc/docs/sdk): React, Vue, Node.js, Nuxt, vanilla JS, and tracker SDK guides.
- [Databuddy Events Ingestion API](https://www.databuddy.cc/docs/api/events): Server-side custom event tracking through the Basket API: authentication, payloads, and batching.
- [Databuddy llms.txt](https://www.databuddy.cc/llms.txt): Compact LLM-readable index of Databuddy documentation and developer resources.
- [Databuddy skills.sh Skill](https://www.databuddy.cc/skill.md): Official SKILL.md source for agents that integrate Databuddy SDK, API, and MCP workflows.
- [Databuddy feedback.md](https://www.databuddy.cc/feedback.md): Where agents send feedback about the product, docs, API, SDK, or MCP server. No authentication required.

---

## Core

# API keys

> Create, use, and manage API keys with scopes and resource access

import { CodeBlock } from "@/components/docs";

## TL;DR

- Generate keys in [Organization settings → API keys](https://app.databuddy.cc/organizations/settings#api-keys)
- Use either `Authorization: Bearer <key>` or `x-api-key: <key>`
- Keys start with `dbdy_` followed by 48 characters
- Scopes: `read:data`, `track:events`, `read:links`, `write:links`, `read:monitors`, `write:monitors`, `read:status_pages`, `write:status_pages`, `manage:websites`, `delete:visitor_data`, `read:flags`, `manage:flags`, `manage:config`
- Access can be global or scoped to a resource like a specific `website`
- For private websites, include `website_id` and ensure the key has `read:data`
- Rotate and revoke keys in [Organization settings → API keys](https://app.databuddy.cc/organizations/settings#api-keys); only the prefix/start should be shared/logged

### What is an API key?

An API key authenticates server-to-server calls to Databuddy. It supports fine-grained scopes and optional resource scoping to enforce least-privilege access. Keys start with `dbdy_` followed by 48 characters.

### Create a key

1. Open [Organization settings → API keys](https://app.databuddy.cc/organizations/settings#api-keys)
2. Click "Add API key"
3. Choose a name, optional organization, scopes, and resource access
4. Copy the secret immediately (it’s only shown once)

We only display the `prefix` and first characters (`start`) later for identification. Never share the full secret.

### Use your key

You can authenticate with either header:

<CodeBlock 
  language="bash"
  code={`curl -X POST "https://api.databuddy.cc/v1/query?website_id={website_id}" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{"id":"summary","parameters":["summary_metrics"],"startDate":"2024-01-01","endDate":"2024-01-31"}'`}
/>

<CodeBlock 
  language="bash"
  code={`curl -X POST "https://api.databuddy.cc/v1/query?website_id={website_id}" \\
  -H "x-api-key: YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{"id":"summary","parameters":["summary_metrics"],"startDate":"2024-01-01","endDate":"2024-01-31"}'`}
/>

Notes:

- For private websites, include the `website_id` query parameter and ensure the key has `read:data` for that site.
- For link shortener analytics, use `link_id` instead of `website_id`; this requires `read:data` with global access.
- `POST /track` for event ingestion lives on `basket.databuddy.cc`, not `api.databuddy.cc`.

### Scopes

- **read:data**: Read analytics data. Covers query endpoints (`POST /v1/query`, `POST /v1/query/compile`) and listing accessible websites (`GET /v1/query/websites`). Required for any dashboard-style data retrieval.
- **track:events**: Send custom events via the SDK or the `/track` endpoint on `basket.databuddy.cc`, and MCP tool calls via `@databuddy/sdk/mcp`
- **read:links**: Read short links
- **write:links**: Create, update, and delete short links
- **read:monitors**: Read uptime monitors
- **write:monitors**: Create, update, and delete uptime monitors
- **read:status_pages**: Read status pages
- **write:status_pages**: Create, update, and delete status pages
- **manage:websites**: Create, update, and delete websites and their settings. Also exports and deletes visitor data
- **delete:visitor_data**: Delete a visitor's or group's data and check the deletion's status, without exporting data or changing the website
- **read:flags**: Read feature flag definitions and targeting rules, for server-side SDKs and DevTools
- **manage:flags**: Create, update, and delete feature flags and targeting rules
- **manage:config**: Integration config and organization settings

Grant only what you need. Prefer resource-scoped access where possible.

#### What each scope allows

| Scope | Endpoints and actions |
|-------|---------------------|
| `read:data` | `POST /v1/query`, `POST /v1/query/compile`, `GET /v1/query/websites`, `websites.list` RPC |
| `track:events` | `POST /track` and `POST /mcp` on `basket.databuddy.cc` (custom events, pageviews, sessions, MCP tool calls) |
| `read:links` | Read short links via the `/rpc/links/*` routes |
| `write:links` | Create, update, and delete short links via the `/rpc/links/*` routes |
| `read:monitors` | Read uptime monitors and their check history |
| `write:monitors` | Create, update, pause, and delete uptime monitors |
| `read:status_pages` | Read status pages and their configuration |
| `write:status_pages` | Create, update, and delete status pages and incidents |
| `manage:websites` | Create / update / delete websites, rotate tracking config, `POST /visitor-data/export`, and everything `delete:visitor_data` allows |
| `delete:visitor_data` | `POST /visitor-data/delete`, `POST /visitor-data/deletion-status`, `POST /visitor-data/delete-group`, `POST /visitor-data/group-deletion-status` |
| `read:flags` | `GET /public/v1/flags/definitions` (also allowed with `read:data` or `manage:flags`) |
| `manage:flags` | Feature flag CRUD, targeting rule edits, flag evaluation admin |
| `manage:config` | Integration config and organization-level settings |

Link analytics are queried through `POST /v1/query` with `link_id` and require `read:data` with global access, not a links scope.

Listing websites is intentionally gated by `read:data` (not a separate `read:websites` scope) because the list is only useful for picking a site to query. Any key that can list sites can already read their analytics.

### Resource access

Access can be scoped to:

- **global**: Applies to all websites in the organization
- **website**: Applies to a specific website only

Example: a key with `read:data` scoped to a single website can read analytics only for that website, not others in the organization.

### Errors

Authentication/authorization failures return structured errors:

<CodeBlock 
  language="json"
  code={`{
    "success": false,
    "error": "Authentication required",
    "code": "AUTH_REQUIRED"
  }`}
/>

<CodeBlock 
  language="json"
  code={`{
    "success": false,
    "error": "Insufficient permissions",
    "code": "FORBIDDEN"
  }`}
/>

### Rotation and revocation

- **Rotate** to generate a new secret for the same key (update your servers immediately)
- **Revoke** to immediately disable a key (cannot be undone; create a new one if needed)

Actions are available in [Organization settings → API keys](https://app.databuddy.cc/organizations/settings#api-keys) under each key’s detail view.

### Rate limits

All API endpoints are rate-limited. See [Rate limits](/docs/api/rate-limits) in the API reference. Responses include standard `X-RateLimit-*` headers where applicable.

### Audit logging

Administrative mutations on API keys are logged: created, updated, revoked, rotated, and deleted. Per-request usage is not logged.

### Best practices

- Treat API keys like passwords; don't commit them to source control
- Use environment variables or secret managers
- Share only the prefix and `start` snippet for identification
- Use least-privilege scopes and resource scoping
- Rotate keys periodically and revoke unused keys
- Monitor audit logs for suspicious activity
- Use resource-scoped keys for better security

---

# Dashboard guide

> A tour of the Databuddy dashboard and what each page shows

import { Callout, Card, Cards } from "@/components/docs";

Sign in at [app.databuddy.cc](https://app.databuddy.cc). The sidebar follows where you are: the organization view lists your websites and organization-wide tools, and opening a website switches the sidebar to that site's pages.

Analytics pages share a date range picker. Clicking a row in a table, such as a page, country, or referrer, adds it as a filter so the page shows only matching traffic.

## Organization pages

### Home

Home summarizes traffic across all your websites, lists recent insights, shows the status of your uptime monitors, and links to each website.

### Insights

Insights lists what Databuddy's investigations found on your sites. Findings that need a decision from you appear under Needs you, open investigations under Watching, and resolved ones under Done.

### Databunny

Databunny is the built-in AI analyst. Ask it about your numbers in plain language and it answers with charts and the query behind each answer. It is also available inside each website, scoped to that site.

### Links, events, MCP analytics, and monitors

- Links holds your short links and app deep links with their click analytics. See [Links](/docs/links).
- Events shows custom events across the organization, including events that aren't attached to a website, and a live event stream.
- MCP analytics shows which AI clients call your MCP servers, which tools they use, how fast calls return, and why they fail. See [MCP servers](/docs/sdk/mcp).
- Monitors holds your uptime monitors and public status pages. See [Uptime monitoring](/docs/uptime).

### Settings

Organization settings cover organization details and API keys, the business context that Insights and Databunny use, integrations, members, the audit log, and billing. Account settings cover your profile, appearance, and notifications.

## Website pages

### Dashboard

The first page for each website shows visitors, sessions, pageviews, bounce rate, and session duration with a traffic trend chart, followed by daily, weekly, and monthly active users. Below that are your top, entry, and exit pages, traffic sources (referrers and UTM sources, mediums, and campaigns), traffic from AI products, a visitor map, devices, browsers, operating systems, and outbound links.

### Map

The map shows where visitors are, with a realtime view of current visitors and a historical view for the selected date range.

### Audience

Audience breaks visitors down by country, region, city, language, and timezone, along with browsers, browser versions, and screen resolutions.

### Replays

Replays lists session recordings and highlights the ones worth watching first, such as sessions with frustration signals, long sessions, and identified users. See [Session replay](/docs/session-replay).

### AI agents

AI agents shows which AI products like ChatGPT and Claude read your pages or send you visitors. See [AI agents](/docs/sdk/ai-agents).

### Error tracking

Error tracking shows total errors, affected users and sessions, the session error rate, error types, and recent errors with their page, browser, and device. It needs error tracking turned on (`autocapture.errors` in the SDK, `data-track-errors` on the script tag, see [SDK configuration](/docs/sdk/configuration)) and the Hobby plan or higher.

### Web Vitals

Web Vitals shows a performance trend for real visitors and breaks it down by page, browser, country, region, and city. It needs Web Vitals tracking turned on (`autocapture.webVitals` in the SDK, `data-track-web-vitals` on the script tag, see [SDK configuration](/docs/sdk/configuration)). The [Core Web Vitals guide](/docs/performance/core-web-vitals-guide) explains each metric.

### Uptime

Uptime shows the monitor for this website's URL. See [Uptime monitoring](/docs/uptime).

### Events

Events summarizes the custom events this website sends, with a page per event showing its trend and property breakdowns, and a stream of individual events. Custom events come from `track()` calls in your app; see [Tracker helpers](/docs/sdk/tracker).

### Users

Users lists anonymous and identified visitors. Each user's page shows a timeline of their sessions and events, their traits and trait history, location, technology, revenue, and Web Vitals. To see your own user IDs and names, [identify users](/docs/sdk/identify-users).

### Funnels and goals

Funnels show how many users complete each step of a sequence, with conversion, drop-off, and the average time between steps. A visitor who enters during the selected dates counts as converting when they finish within the funnel's conversion window, 1 day by default, even if they finish after the range ends. Recent days can still rise until their window has passed, and the charts show those days as dashed. Change the window in the funnel's **Settings**, from 1 hour up to 30 days. Goals track a single conversion, either a page view or a custom event.

### Feature flags

Feature flags lets you add boolean, rollout, and multivariant flags, target them at groups of users, and archive them when you're done. See [Feature flags](/docs/sdk/feature-flags).

### Revenue

Revenue shows revenue, transactions, customers, refunds, and failed payments, attributed to referrers, UTM parameters, entry pages, and locations. It needs a payment provider connected through [Payments](/docs/Integrations/payments).

### Website settings

Website settings cover general details, security, transferring the site to another organization, data export, data import from other analytics tools, and the tracking setup snippet. See [Security](/docs/security) for allowed origins and access controls.

To bring supported exports from another tool, follow the [historical import guide](/docs/import-history). Preview the source format and dates first, and review the limits on reconstructed aggregate reports before replacing an earlier import.

## When a page is empty

1. If no page shows data, open the website's Setup page to confirm the tracking code, then follow the [installation troubleshooting](/docs/Integrations/nextjs#troubleshooting). If ad blockers stop the requests, [serve Databuddy from your own domain](/docs/Integrations/nextjs#serve-databuddy-from-your-own-domain).
2. Events, funnels, and event goals only fill in once your app sends custom events.
3. Error tracking and Web Vitals stay empty until you turn on the `errors` and `webVitals` autocapture options.
4. Users show your own IDs and names only after you call `identify`.
5. Revenue stays empty until a payment provider sends webhooks.

<Callout type="info">
  Need help? Ask in [Discord](https://discord.gg/JTk7a38tCZ) or email
  [support@databuddy.cc](mailto:support@databuddy.cc).
</Callout>

If you are choosing a reporting workflow, compare the [analytics dashboard options](/blog/user-friendly-dashboards-for-website-analytics-your-options-in-2026). When a report needs an action you do not yet record, use the [custom event guide](/blog/custom-event-tracking-without-cookies) to plan the missing measurement.

To bring supported exports from another tool, follow the [historical import guide](/docs/import-history). Preview the source format and dates first, and review the limits on reconstructed aggregate reports before replacing an earlier import.

## Related

<Cards>
  <Card title="SDK reference" href="/docs/sdk">
    Configuration and tracking options for every SDK
  </Card>
  <Card title="Security and privacy settings" href="/docs/security">
    Access control, allowed origins, and IP restrictions
  </Card>
</Cards>

---

# Getting started

> Add Databuddy to Next.js, React, Vue, or any site with a script tag or the npm SDK. Track pageviews and custom events without cookies, free up to 10,000 events a month.

import { Step, Steps } from "@/components/docs";
import { Tab, Tabs } from "@/components/docs";
import { Callout } from "@/components/docs";
import { Card, Cards } from "@/components/docs";
import { CodeBlock } from "@/components/docs";

This guide takes you from a new Databuddy account to your first tracked pageview. For API schemas, machine-readable references, and integration entry points, use the [developer resources hub](/developers).

<Steps>
<Step>

## Create your account

1. Go to [app.databuddy.cc](https://app.databuddy.cc)
2. Sign up for a free account
3. Create a website in the dashboard
4. The dashboard shows your install snippet with your **Client ID**

</Step>
<Step>

## Install the SDK

Choose the install method for your app. For Vue, follow the [Vue SDK guide](/docs/sdk/vue).

<Tabs items={['React/Next.js', 'Script tag']}>
<Tab value="React/Next.js">

Install the official Databuddy SDK:

<CodeBlock
  language="bash"
  code={`# Using bun (recommended)
bun add @databuddy/sdk

# Using npm
npm install @databuddy/sdk

# Using yarn
yarn add @databuddy/sdk`}
/>

</Tab>
<Tab value="Script tag">

For any website, use the script tag method:

<CodeBlock
  language="html"
  code={`<script
    src="https://cdn.databuddy.cc/databuddy.js"
    data-client-id="your-client-id"
    data-track-web-vitals
    crossorigin="anonymous"
    async
  ></script>`}
/>

</Tab>
</Tabs>

</Step>
<Step>

## Add tracking

<Tabs items={['React/Next.js', 'Script tag']}>
<Tab value="React/Next.js">

Add `<DatabuddyProvider />` once in your root layout:

<CodeBlock
  language="tsx"
  filename="app/layout.tsx"
  code={`import { DatabuddyProvider } from "@databuddy/sdk/react";

  export default function RootLayout({
    children,
  }: {
    children: React.ReactNode;
  }) {
    return (
      <html lang="en">
        <head />
        <body>
          <DatabuddyProvider
            clientId={process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!}
            autocapture={{ webVitals: true, errors: true }}
          />
          {children}
        </body>
      </html>
    );
  }`}
/>

**Environment variables:**

<CodeBlock
  language="bash"
  filename=".env.local"
  code="NEXT_PUBLIC_DATABUDDY_CLIENT_ID=your-client-id"
/>

</Tab>
<Tab value="Script tag">

Add the script to your HTML `<head>`:

<CodeBlock
  language="html"
  filename="index.html"
  code={`<!DOCTYPE html>
  <html>
    <head>
      <title>My Website</title>

      <!-- Databuddy Analytics -->
      <script
        src="https://cdn.databuddy.cc/databuddy.js"
        data-client-id="your-client-id"
        data-track-web-vitals
        data-track-errors
        crossorigin="anonymous"
        async
      ></script>
    </head>
    <body>
      <!-- Your content -->
    </body>
  </html>`}
/>

</Tab>
</Tabs>

<Callout type="info">
  Web Vitals and error tracking are off by default; error tracking requires
  the Hobby plan or higher.
</Callout>

</Step>
<Step>

## Verify installation

Check that page tracking works:

1. **Visit your website** in a new browser tab
2. **Open your Databuddy dashboard** at [app.databuddy.cc](https://app.databuddy.cc)
3. **Check real-time data**: you should see yourself as an active visitor
4. **Navigate between pages**: Databuddy records route changes automatically

<Callout type="success">
  If you see real-time data in your dashboard, congratulations! Databuddy is now
  tracking your website analytics.
</Callout>

</Step>
</Steps>

## Track your first custom event

<Tabs items={['React/Next.js', 'Script tag']}>
<Tab value="React/Next.js">

<CodeBlock
  language="tsx"
  filename="components/signup-button.tsx"
  code={`"use client";

import { track } from "@databuddy/sdk";

export function SignupButton() {
  return (
    <button
      onClick={() =>
        track("signup_clicked", {
          location: "header",
          plan: "free",
        })
      }
      type="button"
    >
      Sign up
    </button>
  );
}`}
/>

</Tab>
<Tab value="Script tag">

<CodeBlock
  language="html"
  filename="index.html"
  code={`<script>
    function trackSignupClick() {
      db.track("signup_clicked", {
        location: "header",
        plan: "free",
      });
    }
  </script>

<button onclick="trackSignupClick()">Sign up</button>`}
/>

</Tab>
</Tabs>

<Callout type="info">
  Keep custom event names stable and use properties for details like location,
  plan, status, or source.
</Callout>

For the decisions behind an integration, read the [React and Next.js SDK comparison](/blog/best-analytics-sdk-react-nextjs-2026). A WordPress site has a separate [installation and verification walkthrough](/blog/privacy-friendly-analytics-wordpress); once tracking works, follow the [UTM campaign measurement guide](/blog/utm-tracking-without-cookies) to test attribution.

## Related

<Cards>
  <Card title="API reference" href="/docs/api">
    Endpoints, authentication, and query types
  </Card>
  <Card title="SDK configuration" href="/docs/sdk/configuration">
    Explore all SDK configuration props and options
  </Card>
  <Card title="Dashboard guide" href="/docs/dashboard">
    Learn to navigate your analytics dashboard and its features
  </Card>
  <Card title="Tracker helpers" href="/docs/sdk/tracker">
    Use helper methods like track, flush, and getIds
  </Card>
  <Card title="Security and privacy" href="/docs/security">
    Configure privacy settings and GDPR compliance
  </Card>
</Cards>

## Troubleshooting

**Not seeing data in your dashboard?**

1. **Check your Client ID**: make sure it matches this website
2. **Test manually**: try `db.track('test', {})` in your browser console
3. **Check the Network tab**: look for requests to `basket.databuddy.cc`
4. **Review environment**: make sure tracking isn't disabled in production

<Callout type="info">
  Need help? Join our [Discord community](https://discord.gg/JTk7a38tCZ) or
  [contact support](mailto:support@databuddy.cc).
</Callout>

---

# Tracking recipes

> Copyable recipes for tracking custom events and user interactions

import { CodeBlock } from "@/components/docs";
import { Callout } from "@/components/docs";
import { Card, Cards } from "@/components/docs";

<Callout type="info">
  <strong>TL;DR:</strong> **Tracking recipes** you can copy and customize for custom events in your application. **Track only what you need** and **avoid duplicate events**.
</Callout>

These recipes show common ways to track user interactions and application events. Copy and customize them for your needs.

## Recipes

<Cards>
  <Card title="Toast tracking" href="/docs/hooks/toast-tracking">
    Track toast notifications automatically to understand user feedback patterns and error rates
  </Card>
  <Card title="Form tracking" href="/docs/hooks/form-tracking">
    Track form submissions with validation state and error patterns
  </Card>
  <Card title="Modal tracking" href="/docs/hooks/modal-tracking">
    Track when modals and dialogs are opened and closed
  </Card>
  <Card title="Feature usage" href="/docs/hooks/feature-usage">
    Track when users interact with specific features
  </Card>
  <Card title="Feedback tracking" href="/docs/hooks/feedback-tracking">
    Track user feedback with server actions and client hooks
  </Card>
</Cards>

## Best practices

### 1. Prevent duplicate events

Use refs or Sets to track what's already been tracked:

<CodeBlock 
  language="tsx"
  code={`const tracked = useRef(new Set<string>());

if (!tracked.current.has(eventId)) {
  tracked.current.add(eventId);
  track("event_name", { id: eventId });
}`}
/>

### 2. Track only essential data

Avoid tracking sensitive information or excessive data:

<CodeBlock 
  language="tsx"
  code={`// Good: only essential properties
track("purchase_completed", {
  order_id: "ORD-123",
  revenue: 99.99,
  currency: "USD",
});

// Avoid: too much data, includes PII
track("purchase_completed", {
  order_id: "ORD-123",
  revenue: 99.99,
  currency: "USD",
  email: "user@example.com", // PII
  full_address: "...", // Sensitive
  credit_card_last_4: "1234", // Sensitive
});`}
/>

### 3. Use consistent event names

Follow a naming convention (e.g. `snake_case`):

<CodeBlock 
  language="tsx"
  code={`// Good: consistent naming
track("button_clicked");
track("form_submitted");
track("modal_opened");

// Avoid: inconsistent naming
track("buttonClick");
track("form-submitted");
track("ModalOpened");`}
/>

### 4. Handle errors gracefully

Don't let tracking errors break your app:

<CodeBlock 
  language="tsx"
  code={`const trackSafely = useCallback((eventName: string, properties?: Record<string, unknown>) => {
  try {
    track(eventName, properties);
  } catch (error) {
    console.error("Tracking error:", error);
    // Don't throw: tracking failures shouldn't break the app
  }
}, []);`}
/>

The SDK also exports `trackError` for reporting handled errors and `flush` for sending queued events immediately.

### 5. Conditional tracking

Only track in production or when explicitly enabled. The `<DatabuddyProvider />` `disabled` prop already covers dev-environment gating; use a check like this only for tracking calls outside the provider:

<CodeBlock 
  language="tsx"
  code={`export function useToastTracking() {
  const { toasts } = useSonner();
  const tracked = useRef(new Set<string | number>());
  const isEnabled = process.env.NODE_ENV === "production";

  useEffect(() => {
    if (!isEnabled) return;

    for (const toast of toasts) {
      if (!tracked.current.has(toast.id)) {
        tracked.current.add(toast.id);
        track("toast_shown", {
          type: toast.type,
          message: toast.title,
        });
      }
    }
  }, [toasts, isEnabled]);
}`}
/>

## Related

<Cards>
  <Card title="SDK reference" href="/docs/sdk">
    Complete SDK API reference and configuration options
  </Card>
  <Card title="React SDK" href="/docs/sdk/react">
    React-specific integration guide and examples
  </Card>
  <Card title="Tracker helpers" href="/docs/sdk/tracker">
    Helper functions for tracking custom events
  </Card>
</Cards>

---

# Import analytics history

> Import supported analytics exports into Databuddy, preview dates and totals, handle overlapping data, and understand which historical reports transfer.

import { Callout, Card, Cards } from "@/components/docs";

Import history brings supported exports from Plausible, PostHog, Simple Analytics, or Umami into a Databuddy website. It is separate from installing a new tracker: an import adds historical reporting data, while the [installation guide](/docs/getting-started) sets up future collection.

Start with a small export and check its preview before importing your full history. Keep the original files so you can compare reports and investigate differences later.

## Choose a supported export

| Provider | File to use | What to expect |
| --- | --- | --- |
| Plausible | The Site Settings data-export ZIP, or a supported dashboard-download ZIP with daily totals | Aggregate traffic is reconstructed for historical reporting. A dashboard download may have approximate daily breakdowns. |
| PostHog | Event JSON lines containing `$pageview` records; gzip-compressed files are also supported | Pageviews and sessions are rebuilt from the exported pageviews and available context. Arbitrary custom events are not imported. |
| Simple Analytics | CSV data points with the `added_iso` and `is_unique` fields | Use a pageview export. The importer builds traffic reports from these rows; it does not migrate event definitions or metadata schemas. |
| Umami | The supported data export or its `website_event.csv`, optionally gzip-compressed | Pageviews and available traffic context are imported. Custom events are skipped. |

The file picker accepting `.json` or `.zip` does not mean every JSON structure or archive is supported. PostHog data must contain one event object per line; a JSON array or Parquet file is not a substitute. GA4 and Matomo exports are not supported by this importer.

Importing a provider's history does not migrate its dashboards, saved reports, goals, funnel definitions, feature flags, replay recordings, payment records, or user profiles. Configure the reports and future events you need separately.

## Try a synthetic Plausible export

[Download the synthetic Plausible sample](/examples/plausible-import-sample.zip) and use a separate test website with no existing traffic for these dates. The archive contains invented daily traffic and page totals, not customer data.

The preview should identify a **Plausible data export** covering **October 1–2, 2026**, with **20 pageviews** and **9 visitors**. The visitor figure sums the supplied daily counts; it is not evidence of nine distinct people across the period. The sample has no custom events or payment data.

Previewing the sample lets you inspect the file without importing it. Choose **Start import** only if you want these synthetic rows in that test website. The sample is an example of the supported shape, not a template for relabeling another provider's incompatible export.

## Preview and import

1. Open the destination website in Databuddy, then **Settings → Import history**. Your account needs permission to update that website.
2. Choose the export file. Databuddy identifies the format and displays its period, visitors, and pageviews. Read any format-specific note before continuing.
3. For aggregate exports such as Plausible, set **Timezone in Plausible** to the source site's timezone. A date-only total needs that timezone to land on the intended local day.
4. Decide whether this file adds another non-overlapping period or replaces an earlier import from the same provider. Leave **Replace previous import** off for a first import or for separate date-range files you intend to keep together.
5. Choose **Start import** and wait for **Import complete**. An accepted preview does not prove that the upload has finished.
6. Open the website's reports using the same historical dates and timezone. Compare daily pageviews and top paths first, then inspect the breakdowns your export actually contains.

The preview is a file summary. Your final reports can differ because of overlap protection, unsupported fields, reconstruction, or differences in metric definitions. Do not use a match on one headline total as proof that every report transferred.

## Plausible: full export versus dashboard download

For historical portability, prefer Plausible's **Site Settings → Imports & Exports → Export data** flow. Its native export includes daily report rows. Plausible notes that this export excludes data previously imported into Plausible from other sources; archive that earlier history separately. See [Plausible's export instructions](https://plausible.io/docs/export-stats).

A dashboard download follows the selected date range, filters, and chart interval. Its visitor file can contain daily totals while other files contain totals for the entire period. Databuddy spreads supported multi-day breakdowns across days in proportion to each day's traffic. Those are reconstructed allocations, not original observations for each day.

If Databuddy reports that the download is grouped by week or month, export with the chart interval set to days or use the Site Settings export. Check that your export includes page totals as well as visitor totals; an isolated visitor summary cannot populate page reports.

<Callout type="info">
  Even a full aggregate export cannot recover the original order of individual visits. Databuddy reconstructs sessions and reporting rows from the available totals. Imported combinations of dimensions, intraday timing, visitor journeys, and duration calculations should not be treated as original event-level evidence. Custom-event totals in a Plausible export do not become completed business events in Databuddy.
</Callout>

For tracker cutover, event mapping and preserving your older reports, continue with the [Plausible migration guide](/blog/migrate-plausible-to-databuddy).

## PostHog, Simple Analytics and Umami

For PostHog, use an event export with timestamps, visitor identifiers and `$pageview` records. Do not use a dashboard image, insight export, or persons-only export. [PostHog's batch export documentation](https://posthog.com/docs/data-pipelines/batch-exports) explains event models and destinations. Choose a compatible JSON-lines output; not every available destination format can be uploaded to Databuddy. The [PostHog adapter guide](/docs/sdk/posthog) covers replacing future SDK calls separately.

For Simple Analytics, export pageview data points as CSV and retain the fields required for identifying the format. A Stats API aggregate response is a different format. [Simple Analytics' export instructions](https://docs.simpleanalytics.com/export-data) describe its raw-data export options; choose CSV for this importer.

For Umami, use the supported data export from its data settings or the corresponding `website_event.csv`. Databuddy uses available pageview, visitor/session, source, location and device fields. Custom events are not imported. Export the intended website's data rather than assuming every row from a multi-site database will transfer.

These imports do not join old visitors to your new identified Databuddy profiles. Start collecting and verifying new custom outcomes using your own event definitions and the [identity guide](/docs/sdk/identify-users).

## Overlap and replacement

Databuddy protects live tracked data by skipping imported events at or after the first live tracked event on the same local date. Earlier events on that date can still be imported. For aggregate exports, reconstructed event times are not the original times, so prefer an export period ending before live tracking begins when you need a clean cutover.

Overlap protection for live tracking is not a promise that overlapping import files are automatically reconciled. Use non-overlapping date ranges when appending history, and inspect the resulting totals before adding another file.

**Replace previous import** removes earlier imported rows from the same provider in this destination website after the new run finishes. It does not remove live tracked rows. Replacement affects earlier imports from that provider, not just the dates covered by your new file. If you are importing history in several date-range files, do not turn replacement on for each file or the later file can remove the earlier imports you wanted to keep.

If an import stops partway through, some batches may already have been written. Keep the export, provider, date range and error details; do not assume the operation rolled back. Check the destination before starting a new overlapping run. Contact [support](mailto:support@databuddy.cc) if you are unsure how to recover without losing earlier imported history.

## File limits and troubleshooting

- **Unrecognized file:** use the provider's supported export, not a renamed spreadsheet, report screenshot, JSON array or unrelated archive. The preview must identify the provider and show pageviews.
- **No pageviews:** confirm the period contains traffic and that the export includes pageview/page-report rows. A custom-event-only export is not a traffic-history import.
- **File too large:** the upload limit is 64 MiB, with separate archive-entry and expansion limits. Export smaller periods and append them with replacement off. A single rollup day over 100,000 pageviews or 10,000 rows needs support rather than repeated uploads of the same day.
- **Dates shifted:** match the source site's timezone, then compare the same local dates in both tools.
- **Preview totals differ from reports:** check live-data overlap, source filters, unsupported fields, and the aggregate reconstruction limits above. A progress row count is not a pageview count because reporting rows can include page exits.
- **New data is missing:** historical import does not install the tracker. Verify your [first new events](/docs/Integrations/nextjs#verify-your-first-events) separately.

## Continue the migration

<Cards>
  <Card title="Plausible migration" href="/blog/migrate-plausible-to-databuddy">
    Preserve source exports, replace tracking, and verify the cutover.
  </Card>
  <Card title="PostHog adapter" href="/docs/sdk/posthog">
    Replace supported SDK calls and review behavior that changes.
  </Card>
  <Card title="Dashboard reports" href="/docs/dashboard">
    Check historical reports and the new events you collect after migration.
  </Card>
</Cards>

---

# What is Databuddy?

> Install Databuddy on any site, track custom events, funnels, and goals, use the SDKs and REST API, and connect Claude or Cursor to your data over MCP.

import { Card, Cards } from "@/components/docs";
import { Callout } from "@/components/docs";

Databuddy is product analytics for startups. One cookieless script tracks visitors, custom events, funnels, and goals, with opt-in error and Web Vitals tracking. Databunny, the built-in AI analyst, answers questions about your data and shows the query behind each answer. Feature flags, short links, and uptime monitoring run in the same dashboard. Free up to 10,000 events a month; error tracking starts on the Hobby plan.

## Why choose Databuddy?

<Cards>
  <Card title="One dashboard" href="/docs/dashboard">
    Collect analytics, errors, and vitals with one tracker, then manage flags,
    links, and AI analysis from the same dashboard.
  </Card>
  <Card title="Cookieless analytics" href="/docs/privacy/cookieless-analytics-guide">
    Browser storage, optional identification, and controls for what you collect.
  </Card>
  <Card title="Databunny" href="/docs/dashboard">
    Ask questions in plain English. Business and Scale plans add scheduled
    investigations.
  </Card>
  <Card title="Works with your stack" href="/docs/Integrations">
    Setup guides for Next.js, React, Vue, WordPress, and Shopify.
  </Card>
</Cards>

## Analytics features

**Essential tracking**

- Pageviews with automatic SPA routing
- Anonymous user sessions
- Traffic sources and referrers
- Real-time visitor monitoring

**Performance monitoring**

- Core Web Vitals (LCP, INP, CLS)
- Page load timing metrics
- Error tracking (Hobby plan and up)
- Custom business events

**Conversion and revenue**

- Custom events for checkout and product flows
- Revenue analytics via payment webhooks (alpha)
- Funnels and goals for conversion analysis
- Feature flags with targeting rules

**Monitoring**

- Uptime monitoring with alerts
- Public branded status pages

## Quick start

<Cards>
  <Card title="Create account" href="https://app.databuddy.cc">
    Sign up free, create a website, and install the snippet.
  </Card>
  <Card title="Install SDK" href="/docs/getting-started">
    Add a script tag or install the React package.
  </Card>
  <Card title="Read the API reference" href="/docs/api">
    Endpoints, authentication, and query types.
  </Card>
  <Card title="View analytics" href="/docs/dashboard">
    Watch real-time data in your dashboard.
  </Card>
</Cards>

## Platform integrations

<Cards>
  <Card title="React" href="/docs/Integrations/react">
    TypeScript support with React hooks and components.
  </Card>
  <Card title="Next.js" href="/docs/Integrations/nextjs">
    App Router and Pages Router with automatic route tracking.
  </Card>
  <Card title="WordPress" href="/docs/Integrations/wordpress">
    Plugin installation and manual setup options.
  </Card>
  <Card title="Shopify" href="/docs/Integrations/shopify">
    E‑commerce tracking with purchase analytics.
  </Card>
</Cards>

## Pricing

<Callout type="success">
  **Free plan: 10,000 events a month**, enough for personal projects and small
  websites.
</Callout>

Looking for plan details? See the full breakdown on the [pricing page](/pricing).

## Get support

- [Documentation](/docs/getting-started): guides and API reference
- [Email support](mailto:support@databuddy.cc): direct help from our team
- [Discord](https://discord.gg/JTk7a38tCZ): questions, bug reports, and feature requests

## Continue with this workflow

If you are still choosing a platform, compare [Google Analytics alternatives](/blog/7-privacy-first-google-analytics-alternatives-you-need-to-know-in-2026) and [free hosted or self-hosted options](/blog/best-free-privacy-friendly-analytics). For a team-specific shortlist, use the [SaaS startup guide](/blog/best-analytics-saas-startups) or the [agency analytics guide](/blog/best-analytics-agencies) before installing a tracker.

---

# Links

> Add short links and app deep links, then see who clicks them and where they come from

import { Callout } from "@/components/docs";
import { Card, Cards } from "@/components/docs";

Links turn any URL into a short `dby.sh` link and count every human click on it, so you can see which campaigns, posts, and partners actually send people to you. Open **Links** in the dashboard sidebar and choose **Add link** to add one.

## Short links

A short link needs a name and a destination URL. You can pick your own slug of 3 to 50 letters, numbers, hyphens, or underscores, or leave it empty and Databuddy generates one for you. Slugs are unique, so the form tells you when a slug is already taken.

Each link can also have:

- **Folders**: group links by campaign, channel, or customer and filter the list by folder.
- **UTM parameters**: the built-in builder adds `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, and `utm_content` to the destination so your website analytics attributes the visit correctly.
- **Device destinations**: send iPhone and iPad visitors to one URL and Android visitors to another, such as the right app store page, while everyone else goes to the main destination.
- **Expiration**: stop a link at a date and time you choose. After it expires, visitors go to the fallback URL you set, or to a Databuddy page explaining that the link has expired.
- **Social previews**: the title, description, and image that Slack, X, LinkedIn, and other apps show when the link is shared. Databuddy fills them in from the destination page, and you can override any of them.
- **External ID**: your own identifier, such as a partner or customer ID, so you can find every link for that partner through the [API](/docs/api/links).
- **QR code**: customize and download a QR code for print, packaging, or events.

## Deep links

Deep links open content directly in the visitor's app on mobile instead of in a browser tab, which keeps people signed in and makes them more likely to follow, subscribe, or reply. Choose **Add link**, then **Deep link**, pick the app, and paste an HTTPS link to the content.

Deep links support Instagram, TikTok, YouTube, X, Spotify, LinkedIn, Facebook, WhatsApp, and Telegram. On a phone the link tries to open the app and falls back to the web page when the app isn't installed, and on desktop it opens the web page.

## Click analytics

Open any link to see its clicks over the selected date range, with today's count, the referrers and devices that sent them, and the countries, regions, and cities they came from. Clicks from crawlers and other bots are left out of these numbers, so they reflect people. When a social app fetches a link to build its preview, that fetch is not counted as a click either.

<Callout type="info">
  To query link clicks from your own code, use the [link analytics
  API](/docs/api/links) with `link_id` in place of `website_id`.
</Callout>

## API access

Links are covered by two API key scopes:

- `read:links`: list and read your links
- `write:links`: add, update, and delete links

Click analytics are queried through `POST /v1/query` with `link_id`, which needs a key with `read:data` and global access rather than a links scope. See [API keys](/docs/api-keys) for how to create and scope keys.

To connect a campaign link to a website outcome, follow the [UTM campaign measurement walkthrough](/blog/utm-tracking-without-cookies). Teams managing several client sites can use the [agency analytics comparison](/blog/best-analytics-agencies) to plan access and reporting before rolling out links.

For an overview of campaign destinations and click reporting, explore [Databuddy short links](/links). Keep link clicks separate from the website visits and conversions you verify after a redirect.

## Related

<Cards>
  <Card title="Link analytics API" href="/docs/api/links">
    Query clicks for your links and filter them by external ID
  </Card>
  <Card title="API keys" href="/docs/api-keys">
    Create scoped keys for managing links from code
  </Card>
  <Card title="Dashboard guide" href="/docs/dashboard">
    Navigate your analytics dashboard and its features
  </Card>
</Cards>

---

# Security and privacy

> Configure Databuddy's collection controls, visitor IDs, opt-out behavior, origin checks, and IP restrictions.

Databuddy provides cookieless collection and controls for the information you send. This page describes those controls and their limits. See the [Privacy Policy](/privacy) and [Data Processing Agreement](/dpa) for our data-protection commitments.

## Privacy-first design

The browser tracker uses first-party localStorage for visitor information and sessionStorage for sessions. Session IDs use a 30-minute reuse window; a continuously open page can keep its current session longer.

Standard analytics event records omit raw IP addresses after request handling and approximate country, region, and city lookup. By default, ingestion hashes visitor IDs with a rotating daily salt. Your website's `anonymizeVisitorIds` setting can disable that transformation or apply it according to the visitor's country.

The [identify API](/docs/sdk/identify-users) links activity to profile IDs and traits you supply. Profile IDs are separate from visitor-ID anonymization. Page paths, titles, custom properties, and errors can also contain personal information; review those payloads before sending them.

## Privacy controls

Enable the features you need using the [SDK configuration](/docs/sdk/configuration). For example, this configuration turns off every autocapture feature, including the interaction events (rage clicks, dead clicks, abandoned forms) that are on by default:

```tsx
import { DatabuddyProvider } from "@databuddy/sdk/react";

<DatabuddyProvider
  clientId="YOUR_WEBSITE_ID"
  autocapture={false}
/>;
```

This is a collection example, not a consent configuration. Where prior consent is required, delay mounting the provider or loading the script until consent is granted.

### Local data storage and opt-out

The browser tracker honors Global Privacy Control, Do Not Track, and the stored opt-out preference. With the SDK, use its helpers:

```javascript
import { optIn, optOut } from "@databuddy/sdk";

optOut();
optIn();
```

With the script tag, call `window.databuddyOptOut()` and `window.databuddyOptIn()`.

Opting out stops tracking, clears local tracker identifiers, and stores the preference when localStorage is available. Feature flags still evaluate for these visitors, but store neither a visitor ID nor cached results, so their percentage rollouts can change between page loads. Opting in does not override GPC or DNT. These helpers do not delete information already collected on the server.

### Data deletion in practice

Visitors should contact the website owner about collected information. We assist customers with access, correction, and deletion requests; contact [privacy@databuddy.cc](mailto:privacy@databuddy.cc). Hashing an identifier or leaving identification disabled does not guarantee that no personal data was collected.

## Access control settings

Collection requires an active website ID. Origin filtering is an ingestion control, not proof of domain ownership: a non-browser client can supply an Origin header.

Open your website's **Settings → Security** to configure additional allowed origins and IP restrictions.

### Allowed origins

When a request includes an Origin, the registered hostname and its subdomains are accepted by default. Additional allowed origins broaden that set; they cannot exclude the registered domain.

Without a configured list, requests lacking an Origin are accepted. With a nonempty list, a missing or unrecognized Origin produces a 403 response.

Supported entries include:

- `example.com`: the hostname.
- `*.example.com`: the apex and its subdomains.
- `localhost`: local development.
- `*`: any parseable origin.

Matching uses the hostname, not a particular scheme or port. The origin check does not itself enforce HTTPS.

### Allowed IP addresses

An empty list imposes no IP restriction. A configured list accepts only requests with a trusted matching IP address; other requests receive a 403 response.

Supported entries include individual IPv4 or IPv6 addresses and IPv4 CIDR ranges, such as `192.0.2.10` or `192.0.2.0/24`.

This path uses the trusted `cf-connecting-ip` header. It does not fall back to arbitrary `x-forwarded-for` or `x-real-ip` values.

Test restrictions with the actual clients and infrastructure that will send events. Blocking legitimate sources prevents their data from being collected.

## Account security

### Two-factor authentication

Open **Settings → Account** in the dashboard and choose **Enable** next to two-factor authentication to protect your login with an authenticator app such as 1Password, Authy, or Google Authenticator. Accounts created with Google or GitHub set a password first, because turning two-factor authentication on or off asks for it.

Once it is on, every way of signing in asks for a code after the first step, whether you use your email and password, a magic link, or Google or GitHub. Turning it on also signs your account out on every other device within a few minutes, so a session you did not start cannot outlive the change. You can check **Trust this device** on the code screen to skip the code on that browser for 30 days.

Setup gives you single-use backup codes. Store them somewhere other than the device that runs your authenticator app, and use one on the code screen if you lose that device. You can create a fresh set from **Settings → Account** at any time, which makes the previous codes stop working.

Repeated wrong codes lock two-factor sign-in for 15 minutes. We email the account owner whenever two-factor authentication is turned on or off and whenever new backup codes are created, so an unexpected email is a reason to reset your password.

### Losing your authenticator and backup codes

If you are still signed in on any device, you do not need support: open **Settings → Account** there and turn two-factor authentication off with your password.

If you are signed out everywhere and can no longer produce a code, email [support@databuddy.cc](mailto:support@databuddy.cc) from the address on your account and tell us which of your websites you can publish a DNS record on. Because anyone who reads that inbox could send the same request, recovery also needs proof that you control that website's domain. It must belong to an organization you own, and you must have set its domain yourself at least 30 days ago. We send you a DNS TXT record named `_databuddy-recovery.<your-domain>`, and you publish it directly on that name rather than through a CNAME.

We also email you as soon as the request is opened, and the reset only happens after a two-day waiting period. Signing in to your account during that time cancels the request, so if you did not ask for it, sign in and change your password. After the waiting period, we turn two-factor authentication off, sign your account out on every device, remove trusted browsers and connected app tokens, and email you again. You can then sign in, set it up again, and delete the TXT record. Support recovery is not available for accounts without an eligible website until independent approval can be authenticated. Keep your backup codes somewhere you can access if you lose your authenticator.

## Data protection

Requests are validated, size-limited, and rate-limited. Profile display names and email addresses use AES-256-GCM field encryption when the server key is configured; production ingestion requires that key. Arbitrary event properties and profile traits are outside this field-encryption mechanism.

Infrastructure, AI, billing, and delivery services process information needed for the features you enable. See the [Data Policy](/data-policy) for their roles.

## Privacy compliance

Cookieless collection does not automatically remove consent requirements. Review browser storage, the information collected, and applicable rules. See the [web analytics privacy guide](/docs/compliance/gdpr-compliance-guide).

## Implementation security

### Content Security Policy

Allow the tracker CDN in `script-src` and the configured ingestion endpoint in `connect-src`. For the default hosted endpoints, those are `https://cdn.databuddy.cc` and `https://basket.databuddy.cc`. Merge these into your existing policy; do not replace your application's other restrictions.

## Support and questions

- [privacy@databuddy.cc](mailto:privacy@databuddy.cc) for privacy and data requests.
- [Getting started](/docs/getting-started) for installation.
- [SDK configuration](/docs/sdk/configuration) for collection options.

---

# Session replay

> Watch how visitors use your site, find where they get stuck, and let Insights and the AI agent read what happened

import { Callout } from "@/components/docs";

Session replay records what visitors see and do on your site, so you can watch a visit back instead of guessing from charts. Databuddy also reads every recording for you: it groups visits by what people were doing, scores how worth watching each one is, and flags clicks the page never answered, so you can go straight to the visits that explain a problem.

Session replay is included on every plan: 5,000 recordings a month. Paid plans pay from $0.005 per extra recording, falling to $0.0015 at volume.

## Start recording

Session replay is on for every website, so recording starts as soon as you add the recorder next to your existing Databuddy script:

```html
<script
  src="https://cdn.databuddy.cc/replay.js"
  data-client-id="YOUR_WEBSITE_ID"
  defer
></script>
```

The settings page shows this line with your website ID already filled in. If you install Databuddy with the React, Next.js, or Vue SDK, add the `replay` prop instead and the SDK loads the recorder for you:

```tsx
// React and Next.js
<DatabuddyProvider clientId="YOUR_WEBSITE_ID" replay />
```

```vue
<!-- Vue -->
<Databuddy client-id="YOUR_WEBSITE_ID" :replay="true" />
```

Pass `replay={{ maskText: false }}` to record page text. Typed input stays masked either way. Recordings appear under **Replays** in the website's sidebar a few seconds after a visitor starts interacting with the page.

The recorder only starts once a visitor moves the pointer, scrolls, taps, or types, so crawlers and tabs nobody looks at never produce a recording. It pauses after five minutes without activity and resumes when the visitor comes back.

## Privacy and masking

Recordings are masked in the visitor's browser before anything is sent, so private data never reaches Databuddy.

- **Typed input is always masked.** What visitors type into fields is never recorded, whatever else you configure.
- **Page text is masked by default.** Add `data-replay-unmask` to an element whose text is safe to show, such as your navigation, headings, or product names, and its text appears in recordings.
- **Blocked elements are left out entirely.** Add `data-replay-block` to an element, and recordings show an empty box of the same size in its place.

If your pages contain no personal data, you can record all page text with `data-mask-text="false"` on the recorder script. Typed input stays masked either way.

<Callout type="info">
  Mention session recording in your privacy policy, as you would for any
  analytics that records how people use your site.
</Callout>

Recordings are kept for 30 days and then deleted. To stop recording a website, open its **Settings**, choose **Tracking**, and switch off **Session replay**.

## Watch recordings

The **Replays** page lists recent recordings with the visitor, the page they started on, their country, browser, and device, and how long they stayed. Each row leads with the most useful thing to know, such as a button that did nothing when clicked.

You can narrow the list to recordings that are worth watching, visitors who struggled, identified users, or long visits. Search for an identified user by email, name, or user ID, then combine that with the recording date, current user traits, and the existing behavior filters:

- **User traits**: values you send with [user identification](/docs/sdk/identify-users), such as `plan = pro`. All selected traits must match the user's current profile.
- **Recording date**: when the recording started, including the start and excluding the end of the selected range. Date presets use your browser's timezone, shown in the date menu.
- **What they were doing**: browsing, evaluating, creating an account, using the product, buying, or looking for help, as judged from each visit.
- **What they did**: any custom event your site sends, such as `signup_completed`, so you can watch exactly the visits where it happened.

For example, combine a `role = editor` trait with a `report_exported` event to find recordings of editors exporting reports. Traits match the user's current profile, events match what happened in that session, and dates match when the recording started.

Filters stay in the page URL, so you can bookmark a view or share it with another workspace member. If a search reaches its candidate limit, the page says that results may be incomplete; narrow the user or date filters before treating an empty result as exhaustive.

The player shows everything the visitor did as an activity list you can click to jump to any moment. Your own custom events appear in that list at the moment they fired. Clicks the page never answered are marked in the list and on the timeline, named over the recording as they happen, and collected under **Problems**. **Details** shows how the visit went and the user's traits.

You can also reach a recording from other places in Databuddy. A visitor's profile marks the sessions that were recorded, and the events stream shows a play button next to any event whose session was recorded.

## Insights and the AI agent

Databuddy watches recordings for clicks that pages never answer, such as a button that does nothing or a card that looks clickable but isn't. When the same element fails for several visitors, Insights opens an investigation, and the investigation links straight to the recordings that show it.

The AI agent can search your recordings by identified-user email, profile ID, current user traits, recording dates, page, text in the visit, custom event, or what visitors were doing. It can ask every matching recording a question, such as whether the visitor compared pricing plans before leaving. It shows the recordings it finds in the chat, where you can play them without leaving the conversation. Agents connected through [MCP](/docs/sdk/mcp) can search recordings as well.

## Use recordings in your own dashboard

The same recording reads accept an API key with `read:data` and access to the website. Keep the key on your server. List recordings with `POST https://api.databuddy.cc/replays/list`:

```json
{
  "websiteId": "YOUR_WEBSITE_ID",
  "traits": [{ "key": "role", "value": "editor" }],
  "limit": 50
}
```

You can also supply `person` for partial email/name/user-ID search, `email` for exact email matching, `profileId`, `startedAfter`, and `startedBefore`. Date bounds are ISO timestamps with a timezone, such as `2026-10-28T00:00:00Z`. The response includes recording metadata, `hasMore` when more matching candidates remain than the requested limit, and `truncated` when the bounded candidate search may have omitted recordings. Narrow the filters when either flag is true.

When someone opens a recording, call `POST /replays/events` with its `websiteId` and `sessionId`. It returns the session and short-lived URLs for its recording chunks, a page at a time. Fetch these URLs when needed; they expire after five minutes. `POST /replays/recorded` checks a list of session IDs for processed recordings, and `POST /replays/issues` lists recurring unanswered clicks.

API-key requests use the normal [API rate limits](/docs/api/rate-limits). Cache list results when appropriate and load a recording when someone watches it, instead of repeatedly fetching every recording. Watching in Databuddy uses your signed-in session and does not consume your API key's request allowance. Reading an existing recording does not collect another recording.

See the [session replay API reference](/docs/api/replays) for all filters, authentication examples, playback responses, and result limits.

## Options

Set these as attributes on the `replay.js` script tag.

| Attribute | Default | What it does |
| --- | --- | --- |
| `data-client-id` | required | Your website ID. |
| `data-mask-text` | `true` | Set to `false` to record page text. Typed input stays masked. |
| `data-record-iframes` | `false` | Records your own embedded pages into the recording of the page that frames them. Set it on both pages, and only where the framed page allows framing by the parent alone. |

Each recording can be up to 20 MB, and each website can record up to 10 GB per day. Very large pages with more than 20,000 elements are not recorded, to keep the recorder from slowing them down.

---

# Uptime monitoring

> Monitor your endpoints with HTTP checks, transition-based alerts, and public status pages

import { Callout } from "@/components/docs";
import { Card, Cards } from "@/components/docs";

Databuddy includes uptime monitoring and public status pages on every plan. Monitor checks do not consume your event quota.

## Monitors

Each monitor performs HTTP checks against a URL at a configurable frequency, from every 60 seconds up to once per day. Every check records:

- **Status**: up or down based on the HTTP response
- **HTTP status code**: the response code returned
- **Latency**: time to first byte and total response time
- **SSL certificate**: validity and expiry date
- **Redirects and response size**: redirect count and bytes transferred

Monitors support a configurable request timeout (1 to 120 seconds), optional cache busting, and can be paused and resumed at any time.

## Alerts

Uptime alerts fire on status transitions only: when a monitor goes from up to down, and again when it recovers. Repeated failed checks during the same incident do not send additional alerts, so you get one notification per incident. Alarms can also watch a website's error rate or traffic volume; configure those in [Notifications settings](https://app.databuddy.cc/settings/notifications).

Alerts can be delivered to:

- **Slack**: via an incoming webhook URL
- **Email**: to organization members
- **Webhook**: any HTTPS endpoint you control

## Status pages

Publish a public, branded status page for your monitors:

- **Custom slug, logo, and theme**: light, dark, or system
- **Per-monitor privacy controls**: hide the URL, hide the uptime percentage, or hide latency for any monitor
- **90-day uptime history**: visitors see uptime bars for the last 90 days
- **Incidents**: publish incidents manually with a severity (minor, major, critical), a status (investigating, identified, monitoring, resolved), affected monitors, and follow-up updates as the situation evolves

## API access

Uptime resources are covered by dedicated API key scopes:

- `read:monitors`: read monitors and their check history
- `write:monitors`: create, update, pause, and delete monitors
- `read:status_pages`: read status pages and their configuration
- `write:status_pages`: create, update, and delete status pages and incidents

See [API keys](/docs/api-keys) for how to create and scope keys.

## Manage from code

Manage monitors and status pages with [Pulumi](/docs/infrastructure-as-code/pulumi). See [Infrastructure as code](/docs/infrastructure-as-code) for what's next.

<Callout type="info">
  Monitors are available on every plan and their checks do not count toward
  your monthly event quota.
</Callout>

For the product overview and supported monitoring workflows, explore [Databuddy uptime monitoring](/uptime). Use this guide for monitor setup and the API references below for programmatic management.

## Related

<Cards>
  <Card title="API keys" href="/docs/api-keys">
    Create scoped keys for programmatic monitor management
  </Card>
  <Card title="Pulumi" href="/docs/infrastructure-as-code/pulumi">
    Define monitors and status pages in code
  </Card>
  <Card title="Dashboard guide" href="/docs/dashboard">
    Navigate your analytics dashboard and its features
  </Card>
</Cards>

---

## SDK

# Accounts

> Group people by the company or workspace they use your product in, with its plan and billing

import { CodeBlock } from "@/components/docs";

The **Accounts** page groups the people using your product by the account they belong to, such as a company or workspace, and shows each account's activity, plan and billing.

## Accounts from email domains

Users you [identify](/docs/sdk/identify-users) with an `email` trait are grouped by their work email domain, with no other setup. Personal addresses (Gmail, Outlook and the like) and your own team's domain are left out.

## Put visitors in your own accounts

Call `group()` with the account's type and key once you know which account the visitor is working in, for example after sign-in or when they switch workspace:

<CodeBlock language="tsx">
  {`import { group } from "@databuddy/sdk";

group("workspace", workspace.id);

// When they leave it or sign out:
group("workspace", null);`}
</CodeBlock>

Later page views and events carry `group_workspace: workspace.id`, which puts their activity in that account. A type uses lowercase letters, digits and underscores. A visitor is in one account of each type. `group()` logs a console warning and does nothing when the key is longer than 256 characters, or when the type is `email_domain`, which is reserved for [accounts from email domains](#accounts-from-email-domains).

The SDK remembers the account across visits, so the first page view after a reload is already in it. `reset()` and `optOut()` forget it in every open tab. While the visitor is opted out, an account applies only on the page that set it and isn't remembered. Don't call `group()` before you know the account, such as while a session loads: passing `null` leaves the remembered account.

[`getGroups()`](/docs/sdk/tracker#getgroups) returns the accounts the visitor is in, such as `{ workspace: "ws_123" }`, to send to your server for `evaluateFlags()` or the Node SDK's `track()`.

In React, pass the accounts to the `groups` prop of [`DatabuddyProvider`](/docs/sdk/react#put-users-in-their-workspace) instead. In Vue, pass them to the `groups` prop of the [`<Databuddy>`](/docs/sdk/vue#props) component. For each type, a key joins the account, `null` leaves it, and `undefined` keeps the remembered account while yours loads. A type you remove from `groups` is left too.

## Name the account and say how it pays

In the browser, `group()` takes the account's display traits, such as `name`, `domain` and `logo`, and sends them when they change:

<CodeBlock language="tsx">
  {`group("workspace", workspace.id, { name: workspace.name, domain: workspace.domain });`}
</CodeBlock>

Some traits drive the Accounts page's MRR, attention and account reviews. Anyone can send requests with your website's client ID, so Databuddy accepts these traits only from your server, with an API key:

- Billing: the `billing_*` keys, and the `plan`, `status`, `mrr`, `trial_ends_at` and `customer_id` keys they fall back to
- Dates: `created_at` and `last_active_at`
- Usage: `plan_usage`, `plan_limit`, `usage_7d` and `usage_30d`

The browser's `group()` leaves them out with a console warning, and a browser request that carries them is refused.

From your server, the [Node SDK](/docs/sdk/node)'s `group()` sets any of the account's traits:

<CodeBlock language="ts">
  {`await client.group({
  groupType: "workspace",
  groupKey: workspace.id,
  traits: { name: workspace.name, billing_plan: "pro", billing_status: "active" },
});`}
</CodeBlock>

The traits the Accounts page reads, such as `domain`, `billing_mrr` and `usage_30d`, are listed under [`group(input)`](/docs/sdk/node#groupinput) and typed as `AccountTraits`; dates can be `Date` objects. Server `group()` only sets traits; people join the account through their events.

## Events from your server

Server events join an account through `groups`, sent as the same `group_<type>` property:

<CodeBlock language="ts">
  {`await client.track({
  name: "export_completed",
  groups: { workspace: workspace.id },
});`}
</CodeBlock>

## Billing from Stripe

Put `databuddy_group_<type>` on the Subscription, or in `subscription_data.metadata` with Checkout, and the subscription keeps that account's plan, billing status, MRR and trial end current. Set it on your server, for the account being billed:

<CodeBlock language="ts">
  {`await stripe.subscriptions.create({
  customer,
  items: [{ price: priceId }],
  metadata: { databuddy_group_workspace: workspace.id },
});`}
</CodeBlock>

[`getRevenueMetadata()`](/docs/sdk/tracker#getrevenuemetadataclientid) also returns these keys for each account `group()` set, but a buyer can edit what their browser sends. Passing them through from the checkout request lets a buyer put their plan on another account, so take only the visit IDs from it, as in [Payments](/docs/Integrations/payments#add-browser-identity-to-your-payments).

Stripe metadata keys are limited to 40 characters, so `getRevenueMetadata()` leaves out group types longer than 24 characters; `group()` warns, once per page, when it joins one. With a manual webhook, also enable the account events listed in Revenue settings. See [Payments](/docs/Integrations/payments).

## Feature flags

Flags are evaluated with the visitor's accounts as `group_<type>` properties, so a property rule such as `group_workspace equals ws_123` targets everyone working in that workspace. In the browser, flags are evaluated again when `group()` changes the account.

Flags rolled out by organization or team bucket by the `organization` and `team` accounts, so everyone in one gets the same result. To roll out by an account of any other type, such as `workspace`, choose its type under **Accounts** in the flag's [**Bucket by**](/docs/sdk/feature-flags#rollout-units). Users who aren't in an account of that type all get one shared result.

A [server-rendered bootstrap](/docs/sdk/feature-flags#render-flags-on-the-server) from `evaluateFlags()` with the same `groups` as the provider is used as it is. One evaluated without an account the browser knows is shown first, then evaluated again with it in the browser. On the server, pass `groups` in the [user context](/docs/sdk/server-flags#user-context).

## Recipes

### SaaS with workspaces in React or Next.js

Pass the active workspace to the provider, and the same `groups` to `evaluateFlags()` so the page renders with that workspace's flags without a request.

<CodeBlock language="tsx" filename="app/layout.tsx">
  {`import { evaluateFlags } from "@databuddy/sdk/node";
import { DatabuddyProvider } from "@databuddy/sdk/react";

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const session = await getSession();
  const user = session ? { id: session.user.id, traits: { email: session.user.email } } : null;
  const groups = { workspace: session?.activeWorkspaceId ?? null };
  const clientId = process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!;
  const bootstrap = await evaluateFlags({ clientId, user, groups });

  return (
    <html lang="en">
      <body>
        <DatabuddyProvider clientId={clientId} user={user} groups={groups} flags={{ bootstrap }}>
          {children}
        </DatabuddyProvider>
      </body>
    </html>
  );
}`}
</CodeBlock>

### API-first and server-only products

Track the calls that matter with `groups`. For activity you don't send as events, such as every API request, send `last_active_at` from a periodic job so the account isn't flagged as quiet.

<CodeBlock language="ts">
  {`await client.track({ name: "export_completed", groups: { workspace: workspaceId } });

// From an hourly job:
await client.group({
  groupType: "workspace",
  groupKey: workspaceId,
  traits: { last_active_at: lastRequestAt },
});`}
</CodeBlock>

### A company with several workspaces on one plan

Send the same `billing_customer` on every workspace one subscription pays for, so they share its plan and its payment, trial and limit are flagged once rather than on each workspace. To see the company as one account too, put people in a second group type.

<CodeBlock language="ts">
  {`for (const workspace of company.workspaces) {
  await client.group({
    groupType: "workspace",
    groupKey: workspace.id,
    traits: { name: workspace.name, billing_customer: company.stripeCustomerId },
  });
}
await client.group({ groupType: "company", groupKey: company.id, traits: { name: company.name, domain: company.domain } });

// In the browser, people are in both:
// <DatabuddyProvider groups={{ workspace: workspace.id, company: company.id }} />`}
</CodeBlock>

### Usage-based and metered plans

From a nightly job, send how much of its plan each account used this period and its use over the last 7 and 30 days, in your own unit. Accounts near their limit and accounts using less than usual are flagged.

<CodeBlock language="ts">
  {`await client.group({
  groupType: "workspace",
  groupKey: workspace.id,
  traits: {
    plan_usage: usage.thisPeriod,
    plan_limit: plan.includedUnits,
    usage_7d: usage.last7Days,
    usage_30d: usage.last30Days,
  },
});`}
</CodeBlock>

### Free trials

Send the trial's status and end date, or put the [account's key](#billing-from-stripe) on the Stripe subscription and the trial syncs from Stripe.

<CodeBlock language="ts">
  {`await client.group({
  groupType: "workspace",
  groupKey: workspace.id,
  traits: { billing_plan: "pro", billing_status: "trialing", billing_trial_ends_at: trialEndsAt },
});`}
</CodeBlock>

### People who switch between workspaces

A visitor is in one account of each type, so switching moves their later events to the new workspace. With the provider, pass the active workspace in `groups`; otherwise call `group()` when they switch.

When the workspace is in the URL, such as `/w/[workspaceId]`, read its key from the route and pass it in the provider's `groups` on the first render, rather than after a fetch. Every tab shares the remembered account. If the key arrives late, the tab's first page view, and any events its components track while mounting, go to the workspace another tab used last.

<CodeBlock language="ts">
  {`import { group } from "@databuddy/sdk";

function onWorkspaceSwitch(workspace: { id: string }) {
  group("workspace", workspace.id);
}`}
</CodeBlock>

### Coming from PostHog

The [PostHog adapter](/docs/sdk/posthog)'s `group()` puts later events and flag targeting in the account as `group_<type>`, and its properties become the account's display traits. The server adapter's `groupIdentify()` sets any of its traits, billing included.

<CodeBlock language="ts">
  {`// Browser, from @databuddy/sdk/posthog
posthog.group("company", company.id, { name: company.name });

// Server, from @databuddy/sdk/posthog/node
posthog.groupIdentify({ groupType: "company", groupKey: company.id, properties: { name: company.name } });`}
</CodeBlock>

### Script tag only

The `<script>` tag on its own has no `group()`. Once `window.databuddy` has loaded, set the property on every page; events after that are in the account, but a page view sent before it isn't. `setGroupTraits()` names the account with the same display traits the npm SDK's `group()` sends; billing and the other [traits only your server may send](#name-the-account-and-say-how-it-pays) are refused.

<CodeBlock language="js">
  {`window.databuddy.setGlobalProperties({ group_workspace: workspace.id });
window.databuddy.setGroupTraits("workspace", workspace.id, { name: workspace.name });`}
</CodeBlock>

---

# AI agents

> See which AI products read your site, which pages and formats they fetch, and how many visitors they send

import { Callout, CodeBlock } from "@/components/docs";

The AI Agents page shows ChatGPT, Claude, Perplexity, Gemini, Meta AI, Claude Code and other AI products: the pages they read, whether they fetched HTML, markdown or `llms.txt`, and the visitors they sent you.

Agents that run JavaScript and visitors referred by AI assistants show up automatically through the Databuddy script. Crawlers and coding agents like GPTBot, ClaudeBot and Claude Code don't run JavaScript, so they only show up once `@databuddy/sdk/agents` runs on your server.

<Callout type="info">
  **Package**: `@databuddy/sdk` 3.0.1+ | **Import**: `@databuddy/sdk/agents`
</Callout>

## Setup

Install the SDK, or upgrade it if you're on 2.x, which doesn't include `@databuddy/sdk/agents`, or 3.0.0, which misses signed agent browsers and markdown-first clients:

<CodeBlock language="bash">
  {`bun add @databuddy/sdk@latest`}
</CodeBlock>

No API key is needed, only your website ID. If you already use the Databuddy SDK, it's set:

<CodeBlock language="bash">
  {`NEXT_PUBLIC_DATABUDDY_CLIENT_ID=your_website_id`}
</CodeBlock>

The `NUXT_PUBLIC_`, `VITE_` and `REACT_APP_` versions of the variable work too, as does `DATABUDDY_WEBSITE_ID`. Requests are only recorded when they come from your website's domain or one of its allowed origins, so local development never shows up.

### Next.js and Fumadocs

If you don't have a proxy yet, create `proxy.ts` (Next.js 16) next to your `app` folder:

<CodeBlock language="ts">
  {`export { proxy } from "@databuddy/sdk/agents";`}
</CodeBlock>

On Next.js 15, create `middleware.ts` instead:

<CodeBlock language="ts">
  {`export { proxy as middleware } from "@databuddy/sdk/agents";`}
</CodeBlock>

If you already have a proxy, add one line to it:

<CodeBlock language="ts">
  {`import { trackAgents } from "@databuddy/sdk/agents";
import { type NextFetchEvent, type NextRequest, NextResponse } from "next/server";

export function proxy(request: NextRequest, event: NextFetchEvent) {
  event.waitUntil(trackAgents(request));
  return NextResponse.next();
}`}
</CodeBlock>

<Callout type="warn">
  If your proxy has a `matcher`, make sure it doesn't exclude `.md` and `.txt` paths. Those are the markdown pages and `llms.txt` files AI tools fetch most.
</Callout>

Fumadocs sites need nothing extra. Markdown requested through a `.md` URL or an `Accept: text/markdown` header is recorded as markdown, and `llms.txt` and `llms-full.txt` are recorded on their own.

### Vercel (any framework)

For Vite, Astro or any other site on Vercel, add `middleware.ts` at the project root:

<CodeBlock language="ts">
  {`export { proxy as default } from "@databuddy/sdk/agents";`}
</CodeBlock>

### Vercel log drain (no code)

On a Vercel Pro or Enterprise plan you can send your request logs instead of adding code. In Vercel, open **Team Settings → Drains → Add Drain**, choose **Logs** and **Custom Endpoint**, and paste:

<CodeBlock language="bash">
  {`https://basket.databuddy.cc/vercel/your_website_id`}
</CodeBlock>

Select the **Static Files**, **Functions**, **Edge Functions** and **Rewrites** sources and the **Production** environment, choose JSON or NDJSON, and leave sampling off. Databuddy keeps only requests from AI agents and search engine crawlers, from hosts that belong to your website, and stores each request once even when Vercel logs it more than once. Requests that claim to be a crawler such as GPTBot or Googlebot but come from outside the IP ranges its operator publishes are dropped. Vercel bills drains by volume.

Logs don't include the `Accept` header, so markdown is recognized from `.md` and `.mdx` paths only, and signed agent browsers look like regular Chrome. In exchange, drains also store the HTTP status each agent got, so you can ask the assistant which pages return 404 to AI crawlers.

### Cloudflare Workers, Hono, and other fetch handlers

<CodeBlock language="ts">
  {`import { trackAgents } from "@databuddy/sdk/agents";

export default {
  async fetch(request, env, ctx) {
    const websiteId = env.DATABUDDY_WEBSITE_ID;
    ctx.waitUntil(trackAgents(request, { websiteId }));
    return fetch(request);
  },
};`}
</CodeBlock>

Workers don't have `process.env`, so set the website ID as a variable in `wrangler.toml` and pass it as an option:

<CodeBlock language="bash">
  {`[vars]
DATABUDDY_WEBSITE_ID = "your_website_id"`}
</CodeBlock>

### Netlify

Add an edge function at `netlify/edge-functions/databuddy.ts`. It runs in front of every request, including static `llms.txt` and markdown files:

<CodeBlock language="ts">
  {`import { trackAgents } from "@databuddy/sdk/agents";

export default (request, context) => {
  const websiteId = Netlify.env.get("DATABUDDY_WEBSITE_ID");
  context.waitUntil(trackAgents(request, { websiteId }));
};

export const config = { path: "/*" };`}
</CodeBlock>

Set `DATABUDDY_WEBSITE_ID` under **Site configuration → Environment variables**. Returning nothing passes the request through, so your site keeps serving as before.

### Express and Node

<CodeBlock language="ts">
  {`import { trackAgents } from "@databuddy/sdk/agents";

app.use((req, _res, next) => {
  trackAgents(req);
  next();
});`}
</CodeBlock>

## What gets recorded

`trackAgents` reports `GET` and `HEAD` requests from AI agents and skips images, scripts, styles and fonts. It recognizes three kinds: known AI products by their user agent; agent browsers such as ChatGPT agent, which send a regular Chrome user agent but sign their requests with a `Signature-Agent` header; and clients that aren't browsers and rank markdown above HTML in their `Accept` header, as tools built for AI do, which are recorded as unidentified agents named after their user agent. Each request records the page path without its query string, the host, the user agent, the `Accept` header, the referrer, the agent, and the format it asked for. It also sends the request's IP address, read from `CF-Connecting-IP`, `X-Forwarded-For` or `X-Real-IP`, so Databuddy can check crawlers against the IP ranges their operators publish; the address is not stored:

| Format | When |
| --- | --- |
| Markdown | The path ends in `.md` or `.mdx`, or the request accepts `text/markdown` |
| llms.txt | The path is `llms.txt` or `llms-full.txt` |
| HTML | Anything else |

It never throws and never delays your response: requests to Databuddy run in the background and time out after 3 seconds.

### Limits to keep in mind

- **A read is not a citation.** An AI product fetching a page means it can use it, not that an answer quoted it. Visitors sent from AI are the signal that an answer linked to you.
- **User agents can be copied.** Anyone can send a request that claims to be GPTBot. Crawlers whose operators publish IP ranges (OpenAI, Anthropic, Google, Perplexity, Apple, Microsoft, Common Crawl and DuckDuckGo) are checked against them, and a request from outside those ranges isn't counted as that crawler. Other crawlers, and agents that run on a person's machine such as Claude Code, can't be checked. If another proxy or CDN sits in front of your host and replaces the client address, real crawlers can look like impersonators.
- **Requests made for a user may ignore robots.txt.** Crawlers such as GPTBot follow it; fetches a person triggers inside ChatGPT or Claude often don't.
- **Visitors from AI depend on what the AI product passes along.** Visits count when the referrer or `utm_source` names an AI product, or the visitor uses an AI app browser. Apps that strip both show up as direct traffic.
- **Failed requests aren't reads.** With a Vercel log drain, requests that got an error are listed separately, and neither errors nor redirects count as pages read. A 304 response, where a crawler checked a page it already had, does count.

## Test your setup

Deploy, then open the AI Agents page in your dashboard and click **Test setup**. Databuddy requests your homepage and `/llms.txt` as GPTBot and tells you whether each request was recorded. Test requests never show up in your data.

Static hosts without middleware (GitHub Pages, S3) and hosted docs platforms that don't let you run code can't report crawler requests. Sites on Vercel can use a log drain, and sites on Netlify an edge function.

## Weekly AI digest

Every Monday at 9:00 UTC, the owners of each organization get an email for every site that got at least one visitor from AI, or at least ten AI reads, in the previous week (Monday to Sunday, UTC). It shows the visitors AI sent compared with the week before, how many times AI read the site, how many pages AI hadn't read in the previous 90 days, each AI product's reads and visitors, where AI visitors landed, and the most read pages. Turn it off under **Settings → Notifications → Weekly AI digest**, or with your email app's Unsubscribe button.

## Continue with this workflow

For tools that help investigate the data you collect, read the [AI-assisted analytics comparison](/blog/web-analytics-tools-ai-powered-insights-2026). To ask an assistant about your existing measurements, follow the [MCP connection guide](/docs/api/mcp) and grant only the permissions the workflow needs.

---

# Configuration reference

> Complete configuration options for all Databuddy SDK platforms

import { Callout, CodeBlock, Card, Cards } from "@/components/docs";

This page documents all configuration options across the Databuddy SDK platforms: React, Vue, vanilla JavaScript, and Node.js.

## Browser options

`DatabuddyProvider`, `init()`, the Vue `<Databuddy>` component and the Nuxt module take the same options.

<CodeBlock language="tsx">
  {`import { DatabuddyProvider } from "@databuddy/sdk/react";

<DatabuddyProvider
  // Read from NEXT_PUBLIC_DATABUDDY_CLIENT_ID when omitted
  clientId="your-client-id"

  // Event endpoint
  apiUrl="https://basket.databuddy.cc"

  // What the tracker records besides pageviews
  autocapture={{
    interactions: true,   // default: true
    webVitals: true,      // default: false
    errors: true,         // default: false
    outgoingLinks: true,  // default: false
    attributes: false,    // default: false
    hashChanges: false,   // default: false
  }}

  // Batching and retries
  batching={{ size: 10, timeoutMs: 5000 }}
  retries={{ max: 3, initialDelayMs: 500 }}

  // Sampling
  sampleRate={1}          // 0 to 1

  // Privacy
  skipPaths={["/admin/**", "/private/*"]}
  maskPaths={["/users/*", "/orders/**"]}

  // Control
  disabled={false}
  debug={false}
/>`}
</CodeBlock>

### Options reference

| Option | Type | Default | Description |
|------|------|---------|-------------|
| `clientId` | `string` | Auto-detect | Client ID (auto-detects from `NEXT_PUBLIC_DATABUDDY_CLIENT_ID`) |
| `apiUrl` | `string` | `https://basket.databuddy.cc` | Event endpoint. Set it with `scriptUrl` to [serve Databuddy from your own domain](/docs/Integrations/nextjs#serve-databuddy-from-your-own-domain) |
| `scriptUrl` | `string` | SDK-pinned, date-versioned CDN URL | A self-hosted tracker build |
| `scriptIntegrity` | `string` | - | SRI hash for `scriptUrl` |
| `disabled` | `boolean` | `false` | Disable all tracking; every call becomes a no-op. On `DatabuddyProvider`, flags also serve their defaults |
| `debug` | `boolean` | `false` | Log what the tracker does and load its debug build |
| `filter` | `(event) => boolean` | - | Return `false` to skip an automatic pageview or page-exit event; `track()` events are not filtered |
| `ignoreBotDetection` | `boolean` | `false` | Track visitors that look like bots |
| `anonymizeVisitorIds` | `boolean \| "auto"` | `true` | Anonymize visitor IDs before storage |
| `usePixel` | `boolean` | `false` | Send events with an image request instead of `fetch` |

The SDK embeds a specific tracker URL and integrity hash, including debug and replay scripts. Leave `scriptUrl` unset to use these pins. Unexpected CDN changes are blocked without falling back to an unversioned URL. Upgrade the SDK to receive future tracker updates.

Custom script URLs retain self-hosting support. Supply `scriptIntegrity` to verify custom tracker bytes; a custom URL without a hash opts out of integrity verification.

#### Autocapture

`autocapture={true}` turns every feature on and `autocapture={false}` turns them all off. An object sets only the keys it names; the rest keep their defaults.

| Key | Type | Default | Description |
|------|------|---------|-------------|
| `webVitals` | `boolean` | `false` | FCP, LCP, INP, CLS, TTFB, and FPS |
| `errors` | `boolean` | `false` | JavaScript errors and unhandled rejections |
| `outgoingLinks` | `boolean` | `false` | External link clicks |
| `interactions` | `boolean` | `true` | Rage clicks, dead clicks, and abandoned forms |
| `attributes` | `boolean` | `false` | Elements with `data-track` attributes |
| `hashChanges` | `boolean` | `false` | URL hash changes |

<Callout type="info">
  Use `autocapture={{ webVitals: true }}` in React, Vue, and Nuxt, or `data-track-web-vitals` with the CDN script.
</Callout>

#### Batching and performance

| Option | Type | Default | Description |
|------|------|---------|-------------|
| `batching` | `false \| { size?: number; timeoutMs?: number }` | `{ size: 10, timeoutMs: 5000 }` | Group events into fewer requests. `size` is events per batch (1-50), `timeoutMs` the batch timeout; `false` sends each event as it happens |
| `retries` | `false \| { max?: number; initialDelayMs?: number }` | `{ max: 3, initialDelayMs: 500 }` | Retry failed requests |
| `sampleRate` | `number` | `1` | Fraction of automatic pageview and page-exit events sent, from 0 to 1, decided per event; `track()` events are not sampled |

When verifying browser pageviews, allow for the configured `batching.timeoutMs` and
retry behavior before declaring an event missing, or set `batching={false}` to send
each event as it happens (SDK versions after 3.4.7; earlier versions ignored it).
Inspect actual requests; a sent request still does not establish hosted report
visibility.

#### Privacy

| Option | Type | Description |
|------|------|-------------|
| `skipPaths` | `string[]` | Glob patterns for paths that are never tracked |
| `maskPaths` | `string[]` | Glob patterns for paths recorded with their dynamic segments masked |

#### Session replay

| Option | Type | Description |
|------|------|-------------|
| `replay` | `boolean \| { maskText?: boolean; recordIframes?: boolean; scriptUrl?: string; integrity?: string }` | Load the [session replay](/docs/session-replay) recorder. |

## Vue

<CodeBlock language="html">
  {`<script setup>
import { Databuddy } from "@databuddy/sdk/vue";
</script>

<template>
  <Databuddy
    :client-id="clientId"
    :autocapture="{ webVitals: true, errors: true }"
    :batching="{ size: 20 }"
    :disabled="isDevelopment"
  />
</template>`}
</CodeBlock>

Vue uses the same options as React but with kebab-case naming:
- `clientId` → `:client-id`
- `sampleRate` → `:sample-rate`
- `skipPaths` → `:skip-paths`

## Vanilla JavaScript

The CDN script reads its options from `data-*` attributes. To load the tracker from npm instead, call `init()` from `@databuddy/sdk` with the options above.

<CodeBlock language="html">
  {`<script
  src="https://cdn.databuddy.cc/databuddy.js"
  data-client-id="your-client-id"
  data-track-web-vitals
  data-track-errors
  data-track-outgoing-links
  data-batch-size="20"
  data-batch-timeout="5000"
  data-sampling-rate="1.0"
  data-skip-patterns='["/admin/**"]'
  data-mask-patterns='["/users/*"]'
  async
></script>`}
</CodeBlock>

### Data attributes reference

| Attribute | Type | Default | Description |
|-----------|------|---------|-------------|
| `data-client-id` | `string` | Required | Your Client ID |
| `data-track-web-vitals` | flag | `false` | FCP, LCP, INP, CLS, TTFB, and FPS |
| `data-track-errors` | flag | `false` | Track JavaScript errors |
| `data-track-outgoing-links` | flag | `false` | Track external links |
| `data-track-interactions` | flag | `true` | Rage clicks, dead clicks, and abandoned forms; set `"false"` to turn off |
| `data-track-attributes` | flag | `false` | Track data-track elements |
| `data-track-hash-changes` | flag | `false` | Track hash changes |
| `data-batch-size` | `number` | `10` | Batch size; `1` with `data-batch-timeout="0"` sends each event as it happens |
| `data-batch-timeout` | `number` | `5000` | Batch timeout (ms) |
| `data-sampling-rate` | `number` | `1.0` | Sampling rate |
| `data-skip-patterns` | `JSON` | `[]` | Paths to skip |
| `data-mask-patterns` | `JSON` | `[]` | Paths to mask |
| `data-disabled` | flag | `false` | Disable tracking |

<Callout type="info">
  **Option names**: the npm SDK groups options (`autocapture={{ webVitals: true }}`, `batching={{ size: 20 }}`, `skipPaths`); vanilla CDN installs use flat `data-*` attributes such as `data-track-web-vitals`, `data-batch-size` and `data-skip-patterns`.
</Callout>

## Node.js

<CodeBlock language="tsx">
  {`import { Databuddy } from "@databuddy/sdk/node";

const client = new Databuddy({
  // Required
  apiKey: process.env.DATABUDDY_API_KEY!,
  
  // Optional: Scope events to a specific website
  websiteId: process.env.DATABUDDY_WEBSITE_ID,
  
  // Optional: Logical grouping (e.g. 'auth', 'api', 'jobs')
  namespace: "api",
  
  // Optional: Source identifier (e.g. 'backend', 'webhook', 'cli')
  source: "backend",
  
  // API
  apiUrl: "https://basket.databuddy.cc",
  
  // Batching
  enableBatching: true,       // default: true
  batchSize: 10,              // max: 100
  batchTimeout: 2000,         // ms
  maxQueueSize: 1000,
  
  // Deduplication
  enableDeduplication: true,  // default: true
  maxDeduplicationCacheSize: 10_000,
  
  // Middleware
  middleware: [
    (event) => {
      event.properties = { ...event.properties, server: true };
      return event;
    }
  ],
  
  // Logging
  debug: false,
  logger: customLogger
});`}
</CodeBlock>

### Node.js options reference

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `apiKey` | `string` | Required | Your API key for authentication |
| `websiteId` | `string` | - | Optional default Client ID to scope events |
| `namespace` | `string` | - | Optional default namespace for logical grouping |
| `source` | `string` | - | Optional default source identifier for events |
| `apiUrl` | `string` | `https://basket.databuddy.cc` | API endpoint |
| `enableBatching` | `boolean` | `true` | Enable event batching |
| `batchSize` | `number` | `10` | Batch size (max 100) |
| `batchTimeout` | `number` | `2000` | Batch timeout in ms |
| `maxQueueSize` | `number` | `1000` | Maximum queue size |
| `enableDeduplication` | `boolean` | `true` | Deduplicate events by ID |
| `maxDeduplicationCacheSize` | `number` | `10000` | Dedup cache size |
| `middleware` | `Middleware[]` | `[]` | Event transform functions |
| `debug` | `boolean` | `false` | Enable debug logging |
| `logger` | `Logger` | - | Custom logger instance |

## Feature flags (client)

`DatabuddyProvider` serves flags. Its `user`, `userPending` and `flags` props are listed in [Feature flags: configuration](/docs/sdk/feature-flags#configuration).

## Feature flags (server)

<CodeBlock language="tsx">
  {`import { createServerFlagsManager } from "@databuddy/sdk/node";

const flags = createServerFlagsManager({
  clientId: process.env.DATABUDDY_CLIENT_ID!,
  apiUrl: "https://api.databuddy.cc",
  user: {
    userId: "user-123"
  },
  environment: "production",
  cacheTtl: 60_000,
  staleTime: 30_000,
  maxCacheSize: 5000,
  autoFetch: false,
  disabled: false
});`}
</CodeBlock>

Server flags never use storage, `autoFetch` defaults to `false`, and `maxCacheSize` caps the entries kept for per-call users. The server `user` takes `userId`, `email`, `organizationId`, `teamId` and `properties`.

## Environment variables

In Next.js the browser SDK reads the Client ID from `NEXT_PUBLIC_DATABUDDY_CLIENT_ID`, and the Nuxt module reads `NUXT_PUBLIC_DATABUDDY_CLIENT_ID`. Elsewhere, pass `clientId` yourself, for example from `import.meta.env.VITE_DATABUDDY_CLIENT_ID` in Vite.

### Next.js

<CodeBlock language="bash" filename=".env.local">
  {`NEXT_PUBLIC_DATABUDDY_CLIENT_ID=your-client-id
DATABUDDY_API_KEY=your-api-key`}
</CodeBlock>

### Vue / Vite

<CodeBlock language="bash" filename=".env">
  {`VITE_DATABUDDY_CLIENT_ID=your-client-id`}
</CodeBlock>

### Node.js / server

The Node client does not read environment variables on its own. Pass them through the constructor:

<CodeBlock language="bash" filename=".env">
  {`DATABUDDY_API_KEY=your-api-key
DATABUDDY_WEBSITE_ID=your-client-id  # Optional default Client ID
DATABUDDY_API_URL=https://basket.databuddy.cc  # Optional`}
</CodeBlock>

<CodeBlock language="tsx">
  {`import { Databuddy } from "@databuddy/sdk/node";

const client = new Databuddy({
  apiKey: process.env.DATABUDDY_API_KEY!,
  websiteId: process.env.DATABUDDY_WEBSITE_ID,
  apiUrl: process.env.DATABUDDY_API_URL
});`}
</CodeBlock>

The [cookieless analytics overview](/blog/what-does-cookieless-mean-a-complete-guide-to-privacy-first-web-analytics) explains the collection choices behind these options. Before enabling diagnostics, review the [privacy considerations in error tracking](/blog/error-tracking-privacy-first-analytics-2026) and check the actual payloads your application produces.

## Related

<Cards>
  <Card title="React SDK" href="/docs/sdk/react">
    React/Next.js integration
  </Card>
  <Card title="Node SDK" href="/docs/sdk/node">
    Server-side tracking
  </Card>
  <Card title="Feature flags" href="/docs/sdk/feature-flags">
    Client-side feature flags
  </Card>
</Cards>

---

# Databuddy DevTools

> Inspect Databuddy events, identity, queues, diagnostics, and feature flags during local development

import { Callout, CodeBlock, Card, Cards } from "@/components/docs";

Databuddy DevTools is a moveable browser overlay for local development, QA, and previews. It observes the Databuddy browser SDK already running on the page.

<Callout type="info">
  **Package**: `@databuddy/devtools` | **Shortcut**: Cmd/Ctrl + Shift + D
</Callout>

## Installation

<CodeBlock language="bash">
  {`bun add -d @databuddy/devtools`}
</CodeBlock>

## React

<CodeBlock language="tsx">
  {`import { DatabuddyDevtools } from "@databuddy/devtools/react";

export function AppShell({ children }: { children: React.ReactNode }) {
  return (
    <>
      {children}
      <DatabuddyDevtools enabled={process.env.NODE_ENV !== "production"} />
    </>
  );
}`}
</CodeBlock>

Manual mount:

<CodeBlock language="tsx">
  {`import { mountDevtools } from "@databuddy/devtools/react";

const unmount = mountDevtools();`}
</CodeBlock>

## Vue

<CodeBlock language="vue">
  {`<script setup>
import { DatabuddyDevtools } from "@databuddy/devtools/vue";
</script>

<template>
  <RouterView />
  <DatabuddyDevtools :enabled="import.meta.env.DEV" />
</template>`}
</CodeBlock>

Manual mount:

<CodeBlock language="ts">
  {`import { mountDevtools } from "@databuddy/devtools/vue";

const unmount = mountDevtools();`}
</CodeBlock>

## What it shows

- Runtime status and diagnostics
- Client, anonymous, and session IDs
- URL attribution params and storage keys
- Global properties
- Event calls: `track`, `screenView`, `flush`, and `clear` (sent by `reset()`)
- Queue lengths and flush state
- Feature flag readiness, config, values, variants, reasons, and sources
- Local feature flag overrides

## Feature flags

DevTools reads the browser flag manager that `DatabuddyProvider` creates when a component first reads a flag, or the one Vue `createFlagsPlugin` mounts. Until then, the flag panel shows flags as unavailable.

Flag sources:

| Source | Meaning |
| --- | --- |
| `server` | Result came from the flags API |
| `cache` | Cached result |
| `default` | Local fallback |
| `error` | Evaluation failed |
| `override` | Local DevTools override |

Overrides are local only. Clear overrides before validating real flag behavior.

### Flag debugging workflow

1. Open DevTools with Cmd/Ctrl + Shift + D.
2. Confirm the flag manager is ready and using the expected `clientId`, API host, and environment.
3. Confirm the user context includes the IDs your rollout needs: the user ID, `organizationId`, or `teamId`.
4. Inspect the flag source. `server` means a real API evaluation, `cache` means a cached value, and `override` means DevTools is forcing the result locally.
5. Test each UI branch with a local override, then clear the override and refresh to validate real behavior.
6. Trigger the outcome event and verify it includes `flag_key`, `variant`, and any useful status field.

## Managing flags

DevTools can create, update, and delete flag definitions when you paste an API key with `manage:flags` scope at runtime.

It uses:

- `GET /public/v1/flags/definitions`
- `POST /public/v1/flags`
- `PATCH /public/v1/flags/{id}`
- `DELETE /public/v1/flags/{id}`

The default API host is the active flag manager API URL, falling back to `https://api.databuddy.cc`. You can override it in the overlay for local or preview environments.

<Callout type="warning">
  Do not hard-code flag management API keys in source. Paste scoped keys into DevTools only when you need runtime flag management. DevTools keeps the key in session storage and clears any older local-storage copy when you disconnect.
</Callout>

## Related

<Cards>
  <Card title="Feature flags" href="/docs/sdk/feature-flags">
    React and Vue feature flag hooks
  </Card>
  <Card title="Server-side flags" href="/docs/sdk/server-flags">
    Server-side feature flag evaluation
  </Card>
  <Card title="Tracker helpers" href="/docs/sdk/tracker">
    Event helpers, IDs, and attribution utilities
  </Card>
</Cards>

---

# Feature flags (client)

> Control feature rollouts and variant splits with React and Vue hooks

import { Tab, Tabs } from "@/components/docs";
import { Callout } from "@/components/docs";
import { CodeBlock } from "@/components/docs";
import { Card, Cards } from "@/components/docs";

Feature flags allow you to control feature rollouts and split people across variants without deploying new code. Manage targeting from your dashboard. SDKs pick up changes on their next fetch or refresh.

<Callout type="info">
  **Dashboard-controlled Rollouts** | **Client-side Caching** | **Stale-While-Revalidate**
</Callout>

## Evaluation behavior

The dashboard separates **evaluation state** from **default behavior**. An enabled boolean flag can still default off; matching user rules or target groups can serve on. Rules are evaluated in order and the first match wins, followed by target groups, then the flag’s default rollout or variant assignment.

Dependencies require every ancestor to be enabled in the same environment. They check configured state, rather than the parent’s per-user result. Pausing, archiving, or deleting a parent blocks its descendants without overwriting their saved states. Enabling the parent unblocks eligible descendants; manually paused children stay paused. Flags paused by the previous cascading behavior remain paused until explicitly enabled.

Each flag is declared once with its default. `useFlag()` returns that default until flags load, while `userPending` is set, when the provider is `disabled`, on errors, and when a flag does not exist (`reason: "NOT_FOUND"`). `disabled` also ignores cached flags and suspends network evaluation. A value whose type doesn't match the declared default is ignored, and the default is served with reason `TYPE_MISMATCH`.

On an initial evaluation failure, `useFlagDetails()` returns `status: "error"` and `loading: false`. Browser managers retry retryable failures automatically with exponential backoff (5 seconds, doubling to 60 seconds). An API `Retry-After` takes precedence, with a 1-second minimum. You can also call `refresh()` from `useFlagsStatus()`. A failed background refresh preserves the last-known value. Use `useFlagsStatus().error` for service diagnostics, and handle error states alongside loading states.

```tsx
const { value: enabled, loading, status } = useFlagDetails(newCheckout);
if (loading) return <Skeleton />;
if (status === 'error') return <ExistingCheckout />;
return enabled ? <NewCheckout /> : <ExistingCheckout />;
```

## Quick start

<Tabs items={['React with user context', 'Vue', 'Setup']}>

<Tab>
<CodeBlock language="ts" filename="flags.ts">
  {`import { defineFlag } from '@databuddy/sdk';

  export const darkMode = defineFlag('dark-mode', { default: false });
  export const newDashboard = defineFlag('new-dashboard', { default: false });`}
</CodeBlock>

<CodeBlock language="tsx" filename="app.tsx">
  {`'use client';

  import { DatabuddyProvider, useFlag, useFlagsStatus } from '@databuddy/sdk/react';
  import { darkMode, newDashboard } from './flags';
  // Replace with your app's auth/session hook.
  import { useCurrentUser } from '@/lib/auth-client';

  function App() {
    const { user, isLoading } = useCurrentUser();

    return (
      <DatabuddyProvider
        clientId={process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!}
        userPending={isLoading}
        user={user ? {
          id: user.id,
          organizationId: user.organizationId,
          teamId: user.teamId,
          traits: {
            role: user.role,
            workspace_type: user.workspaceType,
            region: user.region,
          }
        } : null}
      >
        <MyComponent />
      </DatabuddyProvider>
    );
  }

  function MyComponent() {
    const isDarkMode = useFlag(darkMode);
    const showNewDashboard = useFlag(newDashboard);
    const { isReady } = useFlagsStatus();

    if (!isReady) return <Skeleton />;

    return (
      <div className={isDarkMode ? 'dark' : ''}>
        {showNewDashboard ? <NewDashboard /> : <OldDashboard />}
      </div>
    );
  }`}
</CodeBlock>
</Tab>

<Tab>
<CodeBlock language="ts" filename="main.ts">
  {`import { createApp } from 'vue';
  import { createFlagsPlugin } from '@databuddy/sdk/vue';
  import App from './App.vue';

  // currentUser should come from your app's auth/session store.
  createApp(App)
    .use(createFlagsPlugin({
      clientId: import.meta.env.VITE_DATABUDDY_CLIENT_ID,
      apiUrl: 'https://api.databuddy.cc',
      user: {
        userId: currentUser.id,
        organizationId: currentUser.organizationId,
        teamId: currentUser.teamId,
        properties: {
          role: currentUser.role,
          workspace_type: currentUser.workspaceType,
        },
      },
    }))
    .mount('#app');`}
</CodeBlock>

<CodeBlock language="vue" filename="FeatureGate.vue">
  {`<script setup lang="ts">
  import { useFlag } from '@databuddy/sdk/vue';

  const newNav = useFlag('new-nav');
  </script>

  <template>
    <Skeleton v-if="newNav.loading.value" />
    <NewNav v-else-if="newNav.on.value" />
    <OldNav v-else />
  </template>`}
</CodeBlock>
</Tab>

<Tab>
<CodeBlock language="bash" filename="terminal">
  {`# Install the SDK
  bun add @databuddy/sdk`}
</CodeBlock>
</Tab>

</Tabs>

## Hooks API

<Callout type="info">
  **React vs Vue API differences**: The Vue plugin reads flags by key. Its `useFlag(key)` returns `{ on, loading, state }` as refs; read the value, status and variant from `state` (e.g. `flag.state.value.variant`). Vue's `useFlags` returns `{ getFlag, fetchAllFlags, updateUser, refresh, updateConfig, memoryFlags, lastError }`. `defineFlag`, `useFlagDetails` and `useFlagsStatus` below are React-only. The Vue plugin requires Vue 3.5 or later.
</Callout>

### `defineFlag(key, { default })`: declare a flag

Declare each flag once, with its type and default, and import it wherever you read it. The default is served until flags load, when the flag is missing, and on errors.

<CodeBlock language="ts" filename="flags.ts">
  {`import { defineFlag } from '@databuddy/sdk';

  export const newDashboard = defineFlag('new-dashboard', { default: false });
  export const maxItems = defineFlag('max-items', { default: 10 });
  export const theme = defineFlag<'light' | 'dark'>('theme', { default: 'light' });`}
</CodeBlock>

### `useFlag(flag)`: flag value

The primary hook for checking feature flags. Returns the flag's value, typed by its default, and never `undefined`.

<CodeBlock language="tsx">
  {`import { useFlag } from '@databuddy/sdk/react';
  import { newDashboard } from './flags';

  function MyComponent() {
    const enabled = useFlag(newDashboard);
    return enabled ? <NewDashboard /> : <OldDashboard />;
  }`}
</CodeBlock>

### `useFlagDetails(flag)`: value and status

Returns `{ value, loading, status, variant, reason, error }` for more granular control:

<CodeBlock language="tsx">
  {`import { useFlagDetails } from '@databuddy/sdk/react';
  import { experiment } from './flags';

  function MyComponent() {
    const flag = useFlagDetails(experiment);

    switch (flag.status) {
      case 'loading':
        return <Skeleton />;
      case 'error':
        return <ErrorFallback />;
      case 'ready':
        return flag.value ? <NewFeature /> : <OldFeature />;
      case 'pending':
        return <LoadingState />;
    }
  }`}
</CodeBlock>

### `useFlagsStatus()`: readiness

Returns `{ isReady, error, refresh }` for the provider's flags as a whole.

<CodeBlock language="tsx">
  {`import { useFlagsStatus } from '@databuddy/sdk/react';

  function FlagsBanner() {
    const { isReady, error, refresh } = useFlagsStatus();

    if (error) {
      return <button onClick={() => refresh()}>Retry loading flags</button>;
    }
    return isReady ? null : <Spinner />;
  }`}
</CodeBlock>

## Flag types

### Boolean flags
Simple on/off switches for features.

<CodeBlock language="tsx">
  {`const myFeature = defineFlag('my-feature', { default: false });
  const enabled = useFlag(myFeature); // boolean`}
</CodeBlock>

### String/number flags
For configuration values and multivariate testing. The default sets the type:

<CodeBlock language="tsx">
  {`const maxUsers = defineFlag('max-users', { default: 100 });
  const theme = defineFlag<'light' | 'dark'>('theme', { default: 'light' });

  const limit = useFlag(maxUsers); // number
  const mode = useFlag(theme);     // 'light' | 'dark'`}
</CodeBlock>

### Rollout flags
Gradually roll out features to a percentage of users.

<CodeBlock language="tsx">
  {`// Set rollout percentage in dashboard (e.g. 25%)
  const newUiRollout = defineFlag('new-ui-rollout', { default: false });
  const enabled = useFlag(newUiRollout);`}
</CodeBlock>

#### Rollout units

Control how users are grouped for rollouts. In the dashboard, choose what the rollout should **Bucket by**:

| Unit | Description | Use case |
|------|-------------|----------|
| **User** | Each user individually | Standard per-user rollouts |
| **Organization** | All org members together | Organization-wide launches |
| **Team** | All team members together | Team-specific features |
| **An account type**, such as `workspace` | Everyone in one [account](/docs/sdk/accounts) of that type together | Per-account launches for the accounts you send with `group()` |

<CodeBlock language="tsx" filename="org-rollout.tsx">
  {`// Pass organizationId for org-level rollouts
  <DatabuddyProvider
    clientId="your-client-id"
    user={{
      id: "user_123",
      organizationId: "org_abc",  // All org members get same result
      teamId: "team_456",         // All team members get same result
    }}
  >
    <App />
  </DatabuddyProvider>`}
</CodeBlock>

If you pass [`groups`](/docs/sdk/accounts) with `organization` or `team` accounts, those are used when `organizationId` or `teamId` isn't set. To roll out by an account of any other type, such as `workspace`, choose its type under **Accounts** in **Bucket by**; the list shows the other account types your website sends. Flags evaluate with the user's accounts as `group_<type>` properties, so each workspace's members get the same result. Users who aren't in an account of that type all get one shared result. If you passed a workspace's key as `organizationId` to roll out by workspace, sending the same key in `groups` and switching the flag to `workspace` keeps every workspace's result.

<Callout type="info">
  **Consistent Group Rollouts**: When using organization, team, or account rollouts, all members with the same ID get the same flag result. If `org_abc` falls within the 25% rollout, all its members see the feature.
</Callout>

### Multivariant flags (A/B/n testing)

Split people across multiple variants. Assignment uses the configured identifier and variant weights. Both variants can have `on: true`, so render from the `variant` field of `useFlagDetails`. In **Feature Flags → Experiments**, choose a conversion goal to compare recorded browser evaluations:

<CodeBlock language="tsx" filename="export-flow.tsx">
  {`import { defineFlag } from '@databuddy/sdk';
  import { useFlagDetails } from '@databuddy/sdk/react';

  export const exportFlow = defineFlag('export-flow', { default: 'control' });

  function ExportPanel() {
    const { variant, loading } = useFlagDetails(exportFlow);

    if (loading) return <Skeleton />;

    switch (variant) {
      case 'control':
        return <DefaultExportPanel />;
      case 'compact':
        return <CompactExportPanel />;
      case 'guided':
        return <GuidedExportPanel />;
      default:
        return <DefaultExportPanel />;
    }
  }`}
</CodeBlock>

**Adding multivariant flags in the dashboard:**

1. Select "multivariant" as the flag type
2. Add your variants with keys and values (string, number, or JSON)
3. Add traffic weights when you need a weighted split, or omit weights for even assignment
4. Avoid using force targeting rules to assign variants; rules are gates or overrides, not variant selectors

<Callout type="info">
  **Consistent Assignment**: Users are deterministically assigned to variants based on their userId or email, ensuring they always see the same variant across sessions.
</Callout>

<Callout type="info">
  **Variant weights**: If no variant weights are configured, users are split evenly. If you add weights, they must total exactly 100; the dashboard rejects flags whose weights do not sum to 100.
</Callout>

**Use cases:**
- **A/B Testing**: Compare two versions of a feature
- **UI variations**: Test layouts, colors, copy
- **Onboarding flows**: Compare guided vs. compact setup paths
- **Feature configuration**: Ship string, number, or JSON values without a deploy
- **A/B/n experiments**: Run experiments with 3+ variants

## Configuration

`DatabuddyProvider` serves flags with its `clientId`. Flags load the first time a component reads one, so apps that don't use flags make no flag requests.

<CodeBlock language="tsx" filename="provider.tsx">
  {`<DatabuddyProvider
    clientId="your-client-id"
    user={{
      id: currentUser.id,
      organizationId: currentUser.organizationId,  // For org-level rollouts
      teamId: currentUser.teamId,                  // For team-level rollouts
      traits: {
        email: currentUser.email,
        role: currentUser.role || 'user',
        workspace_type: currentUser.workspaceType || 'personal',
        region: currentUser.region || 'us-east',
        created_at: currentUser.createdAt,
      }
    }}
    userPending={isLoadingSession}
    flags={{
      apiUrl: 'https://api.databuddy.cc',
      environment: 'production',
      persist: true,          // Keep values in localStorage for the next visit
    }}
  >
    <App />
  </DatabuddyProvider>`}
</CodeBlock>

### Configuration options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `clientId` | string | Auto-detected | Your Databuddy Client ID from the dashboard |
| `user` | object \| null | `undefined` | The signed-in user for targeting, or `null` when signed out |
| `userPending` | boolean | `false` | Defer evaluation while session loads |
| `disabled` | boolean | `false` | Disable tracking and all flag evaluation |
| `flags.apiUrl` | string | `https://api.databuddy.cc` | Flags API endpoint |
| `flags.clientId` | string | The provider's `clientId` | Serve another website's flags |
| `flags.environment` | string | `undefined` | Environment name |
| `flags.persist` | boolean | `true` | Keep flag values in localStorage so the next visit starts with them |

### User options

| Option | Type | Description |
|--------|------|-------------|
| `id` | string | Unique user identifier for per-user rollouts |
| `email` | string | Flag targeting only, never sent with events. Defaults to `traits.email`; put the email in `traits` to also store it on the profile |
| `organizationId` | string | Organization ID for org-level rollouts. Defaults to the provider's `groups.organization` |
| `teamId` | string | Team ID for team-level rollouts. Defaults to the provider's `groups.team` |
| `traits` | object | Scalar profile traits, also used by targeting rules |

The Vue plugin takes `user: { userId, email, organizationId, teamId, properties }` and the `isPending`, `disabled`, `environment`, `cacheTtl`, `staleTime`, `autoFetch` and `skipStorage` options directly.

### Environments

Pass `environment` when you maintain separate flag definitions for production, staging, or previews. If `environment` is omitted, the SDK fetches definitions that do not have an environment assigned.

<CodeBlock language="tsx">
  {`<DatabuddyProvider
    clientId={process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!}
    flags={{ environment: process.env.NEXT_PUBLIC_VERCEL_ENV ?? "production" }}
  >
    <App />
  </DatabuddyProvider>`}
</CodeBlock>

## Flag states

The `FlagDetails` object returned by `useFlagDetails`:

<CodeBlock language="tsx">
  {`interface FlagDetails<T> {
    value: T;                 // The flag's value, or its default
    loading: boolean;         // Whether the flag is loading
    status: FlagStatus;       // 'loading' | 'ready' | 'error' | 'pending'
    variant?: string;         // Variant for A/B tests
    reason?: string;          // Why this value was served, e.g. 'MATCH', 'ERROR' or 'TYPE_MISMATCH'
    error?: FlagsRequestFailure;
  }`}
</CodeBlock>

## Render flags on the server

Evaluate flags while rendering on the server and pass them to the provider. The page renders with real values instead of a loading state, hydration shows the same, and the browser starts from them without a request until they go stale.

<CodeBlock language="tsx">
  {`// app/layout.tsx (a Server Component)
import { evaluateFlags } from "@databuddy/sdk/node";
import { DatabuddyProvider } from "@databuddy/sdk/react";

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const session = await getSession();
  const user = session
    ? { id: session.user.id, traits: { email: session.user.email } }
    : null;
  const bootstrap = await evaluateFlags({
    clientId: process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!,
    user,
  });

  return (
    <html lang="en">
      <body>
        <DatabuddyProvider
          clientId={process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!}
          user={user}
          flags={{ bootstrap }}
        >
          {children}
        </DatabuddyProvider>
      </body>
    </html>
  );
}`}
</CodeBlock>

- Pass the same `user`, `groups`, client ID and `environment` to `evaluateFlags` and the provider. Flags evaluated for anything else are ignored. With [accounts](/docs/sdk/accounts), the browser evaluates again when it remembers one the server didn't get.
- For visitors who aren't signed in, the server can't know the browser's anonymous ID. The server's values show until the browser's own evaluation arrives, so a percentage rollout or variant split can change then.
- If the evaluation fails or takes longer than `timeoutMs` (2 seconds by default), `evaluateFlags` returns `null` and the browser loads flags as usual. A flags outage never breaks the render.
- Server evaluations count against the public flags rate limit for the server's IP (600 per minute per website), so on busy or serverless deployments `evaluateFlags` may return `null`. Results for visitors who aren't signed in are the same for every visitor, so cache them per environment.
- Reading the session per request makes the page dynamic in Next.js.

## Performance features

### Stale-while-revalidate
Flags return cached values immediately while revalidating in the background.

<CodeBlock language="tsx">
  {`// Returns cached value instantly, revalidates if stale
  const enabled = useFlag(myFeature);  // Instant!`}
</CodeBlock>

Values restored from `localStorage` render immediately and are revalidated on the first fetch or read.

### Request batching
Multiple flag requests within 10ms are batched into a single API call.

<CodeBlock language="tsx">
  {`// These 3 reads become 1 API request
  const feature1 = useFlag(featureOne);
  const feature2 = useFlag(featureTwo);
  const feature3 = useFlag(featureThree);`}
</CodeBlock>

### Visibility API
Pauses background revalidation when the tab is hidden to save bandwidth and battery. Initial fetches still run.

### Request deduplication
Identical requests are deduplicated automatically. After the initial fetch, flags it did not return resolve locally as `NOT_FOUND` without another request.

## Why userPending matters

The `userPending` prop prevents race conditions during authentication:

<CodeBlock language="tsx">
  {`// Bad: Flags evaluate with wrong user context
  <DatabuddyProvider user={null}>
    <App /> // Shows anonymous features, then switches
  </DatabuddyProvider>

  // Good: Waits for session before evaluating
  <DatabuddyProvider
    userPending={isPending}
    user={session?.user ? {...} : null}
  >
    <App /> // Shows correct features immediately
  </DatabuddyProvider>`}
</CodeBlock>

**Benefits:**
- Prevents flash of incorrect content
- Avoids unnecessary API calls
- Consistent user experience
- Better performance

## User targeting

Target specific users or groups from your dashboard:

- **User ID**: Target specific users by their unique identifier
- **Email**: Target by email address or domain (e.g. `@company.com`)
- **Organization**: Roll out to entire organizations at once
- **Team**: Roll out to specific teams
- **Custom Properties**: Target by user attributes

### Organization and team rollouts

For launches that should apply to all members of an organization:

<CodeBlock language="tsx">
  {`<DatabuddyProvider
    user={{
      id: "user-123",
      organizationId: "org_abc",  // All org members get same result
      teamId: "team_456",         // All team members get same result
    }}
  >`}
</CodeBlock>

Then in the dashboard, set **Bucket by** to "Organization" or "Team" when configuring your rollout flag. For another account type, such as `workspace`, put users in their account with [`groups`](/docs/sdk/accounts) and choose that type instead.

### Target groups

Target groups are reusable audiences you can attach to flags. They can match:

- `userId`
- `email`
- custom `properties` fields (the provider's `traits`)

Supported rule operators include `equals`, `contains`, `starts_with`, `ends_with`, `in`, and `not_in`. Property rules also support `exists` and `not_exists`.

Evaluation order matters:

1. Direct user targeting rules
2. Attached target group rules
3. Multivariant assignment
4. Rollout percentage
5. Boolean default value

Direct rules and target group matches short-circuit evaluation as force on/off rules. For A/B/n experiments, use them to control eligibility carefully, but do not rely on them to choose a specific variant. If you need both strict eligibility and variant measurement, use a boolean eligibility flag plus a separate multivariant assignment flag.

### Advanced targeting with custom properties

<CodeBlock language="tsx">
  {`<DatabuddyProvider
    user={{
      id: "user-123",
      organizationId: "org_abc",
      teamId: "team_456",
      traits: {
        role: 'admin',             // Role-based rollouts
        workspace_type: 'team',    // Workspace targeting
        region: 'us-east',         // Geographic targeting
        created_at: '2024-01-01',  // Time-based targeting
        cohort: 'activation-a',    // Experiment or onboarding cohort
        reports_viewed: 25,        // Behavioral targeting
      }
    }}
  >`}
</CodeBlock>

**Targeting Examples:**
- **Role-based**: `role: 'admin'` → Show admin workflows
- **Workspace-based**: `workspace_type: 'team'` → Group-specific experience
- **Geographic**: `region: 'us-east'` → Test in specific regions
- **Behavioral**: `reports_viewed > 10` → Target power users
- **Time-based**: `created_at > '2024-01-01'` → New vs. existing users

## Best practices

### Measure flag outcomes

Treat flag metrics as two separate questions: who was evaluated, and what changed afterward. When the tracker is available, the browser SDK emits a deduplicated `$flag_evaluated` event when a flag is read through `useFlag`, `useFlagDetails`, or the Vue plugin. The feature flags dashboard uses those events to show observed visitors, identified visitors, evaluation count, and the last observed evaluation time.

These dashboard numbers are directional estimates, not guaranteed complete or exact counts of people who used a feature. They only include browser evaluations that Databuddy observed, so blockers, consent or opt-out settings, event sampling, missing tracker coverage, server-side evaluations, and incomplete identity linkage can make the numbers lower than reality. The visitor count should be read as “observed visitors evaluated,” not “people who used the feature.” Passing `user` to `DatabuddyProvider` also identifies the tracker, so those evaluations carry your profile ID.

To compare variants, open **Feature Flags → Experiments**, select the flag, and pick a conversion goal. The goal and comparison options stay in the results URL; there is no saved experiment lifecycle or automatic completion. Each group counts observed visitors and goal conversions at or after their first recorded evaluation inside the selected period. Multivariant flags count only evaluations with a named variant, so non-enrolled fallback reads are left out. Visitors with multiple recorded versions are excluded and reported separately.

Boolean and rollout reports are observed On/Off comparisons. They do not establish randomized assignment, and an Off record can include a missing-flag fallback. Results do not separate environments or configuration revisions; keep the flag and goal definitions stable while comparing. A statistical difference is evidence for one pair, not proof of causality or an overall winner.

An evaluation is not proof that a feature was rendered or used, and server-side flag evaluations are not automatically sent as analytics events. For experiments where rendered exposure or product usage must be measured, track one explicit exposure event when the meaningful flagged view appears, then track the downstream outcome. Such custom exposure events support your own event analysis; they do not replace the built-in results view's `$flag_evaluated` enrollment event.

<CodeBlock language="tsx">
  {`import { track } from "@databuddy/sdk";
import { useEffect, useRef } from "react";
import { useFlagDetails } from "@databuddy/sdk/react";
import { exportFlow } from "./flags";

function ExportPanel() {
  const { loading, variant } = useFlagDetails(exportFlow);
  const trackedExposure = useRef(false);

  useEffect(() => {
    if (loading || trackedExposure.current) {
      return;
    }

    trackedExposure.current = true;
    track("feature_exposed", {
      flag_key: "export-flow",
      variant: variant ?? "control",
      feature: "report_export",
    });
  }, [loading, variant]);

  return variant === "compact" ? (
    <CompactExportPanel />
  ) : (
    <DefaultExportPanel />
  );
}`}
</CodeBlock>

Then track the downstream outcome and include the same flag key and variant.

<CodeBlock language="tsx">
  {`import { track } from "@databuddy/sdk";
import { useFlagDetails } from "@databuddy/sdk/react";
import { exportFlow } from "./flags";

function ExportButton() {
  const { variant } = useFlagDetails(exportFlow);

  async function handleExport() {
    const result = await runExport();

    track("report_exported", {
      flag_key: "export-flow",
      variant: variant ?? "control",
      status: result.ok ? "success" : "failed",
      format: result.format,
    });
  }

  return variant === "compact" ? (
    <CompactExportButton onClick={handleExport} />
  ) : (
    <DefaultExportButton onClick={handleExport} />
  );
}`}
</CodeBlock>

Use one meaningful exposure event and one meaningful outcome event. Avoid tracking every render of a flagged component.

### Flag planning checklist

Before adding a flag, decide:

- **Owner**: who removes or expands the flag later
- **Default**: what users see if evaluation fails
- **Rollout unit**: user, organization, team, or an account type such as `workspace`
- **Targeting inputs**: which IDs and low-cardinality properties are required
- **Success metric**: the one outcome event that proves the rollout helped
- **Cleanup date**: when the flag should be removed or made permanent

### Use the right API

<CodeBlock language="tsx">
  {`// The value, the most common case
  const enabled = useFlag(darkMode);

  // Full control with status
  const flag = useFlagDetails(experiment);
  if (flag.status === 'ready') { ... }

  // A/B test variants
  const { variant } = useFlagDetails(exportFlow);

  // Typed values come from the default
  const limit = useFlag(maxItems); // number

  // Whether all flags have loaded
  const { isReady } = useFlagsStatus();`}
</CodeBlock>

### Handle loading states

<CodeBlock language="tsx">
  {`function FeatureComponent() {
    const { value: enabled, loading } = useFlagDetails(newFeature);

    if (loading) return <Skeleton />;
    return enabled ? <NewFeature /> : <OldFeature />;
  }`}
</CodeBlock>

### Multiple flags

<CodeBlock language="tsx">
  {`function Dashboard() {
    const isDarkMode = useFlag(darkMode);
    const showNewLayout = useFlag(newLayout);
    const limit = useFlag(maxItems);

    return (
      <div className={isDarkMode ? 'dark' : ''}>
        {showNewLayout ? <NewLayout items={limit} /> : <OldLayout />}
      </div>
    );
  }`}
</CodeBlock>

### Update user context

Flags follow the provider's `user` prop. Pass the active workspace in it, and switching workspaces clears flags from the previous context and fetches the new one:

<CodeBlock language="tsx">
  {`function Providers({ children }: { children: React.ReactNode }) {
    const { user, workspace } = useSession();

    return (
      <DatabuddyProvider
        clientId={process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!}
        user={user ? {
          id: user.id,
          organizationId: workspace.organizationId,
          teamId: workspace.teamId,
          traits: {
            role: workspace.role,
            workspace_type: workspace.type
          }
        } : null}
      >
        {children}
      </DatabuddyProvider>
    );
  }`}
</CodeBlock>

Inline `user` and `traits` objects are compared by value, so re-rendering with the same values keeps the current context.

## Debug with DevTools

Install DevTools in local development to inspect the flag manager on the page: `DatabuddyProvider` creates it when a component first reads a flag, and Vue `createFlagsPlugin` mounts it with the plugin.

<CodeBlock language="bash">
  {`bun add -d @databuddy/devtools`}
</CodeBlock>

<CodeBlock language="tsx">
  {`import { DatabuddyDevtools } from "@databuddy/devtools/react";

export function AppShell({ children }: { children: React.ReactNode }) {
  return (
    <>
      {children}
      <DatabuddyDevtools enabled={process.env.NODE_ENV !== "production"} />
    </>
  );
}`}
</CodeBlock>

Use the flag panel to verify:

- `clientId`, API host, environment, and readiness
- user context used for targeting
- evaluated values, variants, reasons, and sources
- whether a value came from API, cache, default, error, or local override
- local overrides before you ship a UI branch

When you paste an API key with `manage:flags` scope at runtime, DevTools can also create, edit, and delete flag definitions. Do not hard-code management keys in source, and clear local overrides before validating production-like behavior.

Before a rollout, decide which outcome to measure using the [feature flags and analytics guide](/blog/feature-flags-privacy-first-analytics). If you are moving an existing PostHog integration, read the [SDK migration guide](/docs/sdk/posthog) before changing imports or flag callbacks. Using `useFlag("key")` or `useFlags()`? They still work; see [Upgrade to DatabuddyProvider](/docs/sdk/upgrade#feature-flags).

## Related

<Cards>
  <Card title="Server-side flags" href="/docs/sdk/server-flags">
    Feature flags for Node.js and API routes
  </Card>
  <Card title="React SDK" href="/docs/sdk/react">
    React component and integration
  </Card>
  <Card title="Vue SDK" href="/docs/sdk/vue">
    Vue component and composables
  </Card>
  <Card title="SDK configuration" href="/docs/sdk/configuration">
    All configuration options
  </Card>
  <Card title="DevTools" href="/docs/sdk/devtools">
    Inspect flag values, variants, and local overrides
  </Card>
</Cards>

---

Ready to get started? [Add your first feature flag in the dashboard →](https://app.databuddy.cc/register)

---

# Identify users

> Link tracked activity to your own user IDs and see real names in your dashboard

import { Callout, CodeBlock, Tab, Tabs } from "@/components/docs";

By default, Databuddy tracks visitors with an anonymous device ID. Calling `identify()` links that activity to a user ID from your own system, so the same person is recognized across sessions and devices, and your dashboard shows real names and emails instead of anonymous visitors.

<Callout type="warn">
  User identification processes personal data. Make sure you have a lawful
  basis (typically consent), disclose it in your privacy policy, and only send
  traits you are allowed to process.
</Callout>

## Quick start

<Tabs items={['React / Next.js', 'Script tag', 'Node.js']}>
<Tab value="React / Next.js">
Pass the signed-in user to `DatabuddyProvider`, or `null` when signed out. The provider calls `identify()` when the user signs in or their traits change, and `reset()` when they sign out.

<CodeBlock language="tsx">
  {`import { DatabuddyProvider } from "@databuddy/sdk/react";

function Providers({ children }: { children: React.ReactNode }) {
  const { data: session, isPending } = authClient.useSession();
  const user = session?.user;

  return (
    <DatabuddyProvider
      user={
        user
          ? { id: user.id, traits: { email: user.email, name: user.name } }
          : null
      }
      userPending={isPending}
    >
      {children}
    </DatabuddyProvider>
  );
}`}
</CodeBlock>

To manage identity yourself, omit `user` and call `identify()` when your auth state resolves and `reset()` on logout. Calling `identify()` on every page load is fine: repeat calls are deduplicated to one request per session.

<CodeBlock language="tsx">
  {`import { identify, reset } from "@databuddy/sdk";

identify(session.user.id, {
  email: session.user.email,
  name: session.user.name,
});

// On logout
reset();`}
</CodeBlock>
</Tab>
<Tab value="Script tag">
The same methods live on the global object once the script loads.

<CodeBlock language="js">
  {`// On login or signup
window.databuddy.identify("user_12345", {
  email: "jo@acme.com",
  name: "Jo Doe",
  plan: "pro",
});

// On logout
window.databuddy.clearProfile();`}
</CodeBlock>
</Tab>
<Tab value="Node.js">
Backends can identify users with an API key that has the `track:events` scope for the target website. Pass the client's anonymous ID (readable in the browser via `getIds().anonymousId`) to link the device's activity.

<CodeBlock language="ts">
  {`import { Databuddy } from "@databuddy/sdk/node";

const client = new Databuddy({
  apiKey: process.env.DATABUDDY_API_KEY,
  websiteId: "your-website-id",
});

await client.identify({
  profileId: user.id,
  anonymousId: cookies.get("did"),
  traits: { email: user.email, plan: "pro" },
});`}
</CodeBlock>
</Tab>
</Tabs>

<Callout type="info">
  Pass an opaque, stable ID from your database (max 128 characters, stored
  verbatim), not an email address. Emails belong in traits.
</Callout>

## How it works

- Every visitor has an anonymous ID stored on their device.
- `identify(profileId, traits)` links that ID to your user and attaches the user ID to every subsequent event, including earlier pageviews from the same session.
- The profile ID persists in localStorage across reloads. Call `reset()` on logout (or pass `user={null}` to the React provider) to return to anonymous tracking.
- Identified users appear on the **Users** page with their name and email, and collapse into one person across all their devices.

## Traits

Traits are flat key/value metadata about the user. Values must be strings, numbers, booleans, or `null`. Nested objects are rejected. Limits: 50 keys, 2KB serialized.

| Trait | Behavior |
|-------|----------|
| `username` | Primary display name in the dashboard |
| `name` | Fallback display name when `username` is absent |
| `email` | Shown under the user's name; lowercased |
| anything else | Stored on the profile and shown in the user detail view |

Display names and emails are encrypted at rest (AES-256-GCM). Custom traits are stored as regular values so you can filter and segment by them.

Update traits by calling `identify()` again with the same ID, and remove one by setting it to `null`. With the React provider, change the user's `traits` instead.

<CodeBlock language="ts">
  {`import { identify } from "@databuddy/sdk";

identify(user.id, { plan: "enterprise", trial_ends_at: null });`}
</CodeBlock>

## Accounts from email domains

Users identified with an `email` are grouped by their work email domain on the **Accounts** page, with no other setup. Everyone signing in with an `@acme.com` address becomes one account, with the company's public name, logo and industry when they can be looked up. Personal addresses (Gmail, Outlook and the like) and your own team's domain are left out.

To group users by your own workspaces or organizations instead, with plan and billing, see [Accounts](/docs/sdk/accounts).

## Revenue attribution

If you use the [Stripe or Paddle integration](/docs/Integrations/payments), include the user ID in your payment metadata and transactions are attributed to the identified user:

<Tabs items={['Stripe', 'Paddle']}>
<Tab value="Stripe">
<CodeBlock language="ts">
  {`await stripe.paymentIntents.create({
  amount,
  currency,
  metadata: {
    databuddy_profile_id: user.id,
  },
});`}
</CodeBlock>
</Tab>
<Tab value="Paddle">
<CodeBlock language="ts">
  {`{ custom_data: { profile_id: user.id } }`}
</CodeBlock>
</Tab>
</Tabs>

## API reference

### `identify(profileId, traits?)`

Links the browser to a user ID. Persists across sessions, attaches to every subsequent event. Safe to call on every page load: repeat calls with the same ID and no traits send one request per session. Calling it again with traits merges them into the profile.

### `reset()`

Forgets the identified user and starts new anonymous and session IDs, so subsequent activity is tracked anonymously as a new visitor. Call it on logout.

### `getIds()`

Returns `{ anonymousId, sessionId, profileId }`. `profileId` is the currently identified user ID, or `null` when anonymous.

---

# SDK overview

> SDK documentation for tracking analytics across web and server runtimes

import { Card, Cards, Callout, CodeBlock } from "@/components/docs";

The Databuddy SDK provides framework-specific components, helper functions, server-side tracking, and a vanilla JavaScript library for tracking analytics events. Choose your preferred integration method.

<Callout type="info">
  **SDK Version**: 3.5.0+ | **Package**: `@databuddy/sdk` | **CDN**: cdn.databuddy.cc
</Callout>

## Installation

<CodeBlock language="bash">
  {`# Using bun (recommended)
bun add @databuddy/sdk

# Using npm
npm install @databuddy/sdk`}
</CodeBlock>

For vanilla JavaScript, no installation is needed. Load it directly from the CDN.

## Quick start

<Cards>
  <Card title="React SDK" href="/docs/sdk/react">
    Component and hooks for React applications
  </Card>
  <Card title="Nuxt module" href="/docs/sdk/nuxt">
    First-class Nuxt module for script injection, SPA navigation, and optional error tracking
  </Card>
  <Card title="Vue SDK" href="/docs/sdk/vue">
    Component and composables for Vue applications
  </Card>
  <Card title="Vanilla JavaScript" href="/docs/sdk/vanilla-js">
    CDN script for any website without dependencies
  </Card>
  <Card title="Node SDK" href="/docs/sdk/node">
    Server-side tracking for APIs, webhooks, and background jobs
  </Card>
</Cards>

## Core features

<Cards>
  <Card title="Tracker helpers" href="/docs/sdk/tracker">
    Helper functions: track, identify, getIds, getTrackingParams
  </Card>
  <Card title="Feature flags" href="/docs/sdk/feature-flags">
    Control feature rollouts and A/B testing in React and Vue
  </Card>
  <Card title="Server-side flags" href="/docs/sdk/server-flags">
    Server-side feature flag evaluation for Node.js
  </Card>
  <Card title="DevTools" href="/docs/sdk/devtools">
    Local overlay for events, identity, queues, diagnostics, and flags
  </Card>
  <Card title="SDK configuration" href="/docs/sdk/configuration">
    All configuration options across platforms
  </Card>
</Cards>

## Import paths

The SDK is organized into submodules for tree-shaking:

| Import | Description |
|--------|-------------|
| `@databuddy/sdk` | Core functions (track, identify, reset, init, defineFlag, etc.) |
| `@databuddy/sdk/react` | `DatabuddyProvider` and flag hooks |
| `@databuddy/sdk/vue` | Vue component and composables |
| `@databuddy/sdk/node` | Node.js server-side SDK |

The Nuxt integration ships as a separate package, [`@databuddy/nuxt`](/docs/sdk/nuxt), not an `@databuddy/sdk` subpath.

## Example: React/Next.js

<CodeBlock language="tsx">
  {`import { DatabuddyProvider } from "@databuddy/sdk/react";
import { track } from "@databuddy/sdk";

// In your root layout
export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <DatabuddyProvider
          clientId={process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!}
          autocapture={{ webVitals: true, errors: true }}
        />
        {children}
      </body>
    </html>
  );
}

// In any component
function SignupButton() {
  return (
    <button onClick={() => track("signup_clicked", { source: "header" })}>
      Sign Up
    </button>
  );
}`}
</CodeBlock>

## Example: Node.js

<CodeBlock language="tsx">
  {`import { Databuddy } from "@databuddy/sdk/node";

const client = new Databuddy({
  apiKey: process.env.DATABUDDY_API_KEY!,
  websiteId: process.env.DATABUDDY_WEBSITE_ID,
  enableBatching: true
});

await client.track({
  name: "api_call",
  properties: { endpoint: "/api/users", method: "GET" }
});

await client.flush(); // Important in serverless!`}
</CodeBlock>

## TypeScript support

The SDK is fully typed. Declare your events to type-check `track()` calls; until you declare any, `track()` accepts any name and properties:

<CodeBlock language="tsx">
  {`import { track } from "@databuddy/sdk";

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

track("signup_completed", { plan: "pro" });`}
</CodeBlock>

Choosing the SDK is easier once you know the events and rendering behavior you need. Compare [analytics SDKs for React and Next.js](/blog/best-analytics-sdk-react-nextjs-2026), or review [open-source analytics alternatives](/blog/best-open-source-google-analytics-alternatives-2026) if licensing and hosting are part of the decision.

## Related

<Cards>
  <Card title="Getting started" href="/docs/getting-started">
    Quick setup guide and basic configuration
  </Card>
  <Card title="API reference" href="/docs/api">
    Direct HTTP API for custom implementations
  </Card>
  <Card title="Dashboard guide" href="/docs/dashboard">
    Navigate your analytics dashboard
  </Card>
</Cards>

---

# MCP servers

> See which AI clients call your MCP servers, which tools they use, how fast they answer, and where they fail

import { Callout, CodeBlock, Tab, Tabs } from "@/components/docs";

The MCP page shows every tool call that Claude, Claude Code, Cursor, ChatGPT, Codex and other AI clients make to your MCP servers: which tools they reach for, how long each call takes, how much context it hands back to the model, and which calls fail and why.

Arguments and successful results never leave your server; only the length of the text a tool returns is recorded. Failed calls send their error message, and Databuddy stores up to 512 characters of it, unless you [keep error messages private](#keep-error-messages-private).

<Callout type="info">
  **Package**: `@databuddy/sdk` 3.2.0+ | **Import**: `@databuddy/sdk/mcp`
</Callout>

## Setup

Install the SDK:

<CodeBlock language="bash">
  {`bun add @databuddy/sdk@latest`}
</CodeBlock>

Create an API key with the **Event Tracking** scope in [Organization Settings → API keys](https://app.databuddy.cc/organizations/settings#api-keys) and set it in your server's environment:

<CodeBlock language="bash" filename=".env">
  {`DATABUDDY_API_KEY=dbdy_your_key`}
</CodeBlock>

Wrap your server once, before or after you register tools:

<CodeBlock language="ts">
  {`import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { trackMcp } from "@databuddy/sdk/mcp";

const server = trackMcp(
  new McpServer({ name: "my-server", version: "1.0.0" })
);`}
</CodeBlock>

`trackMcp` returns the server you pass it, and also accepts the low-level `Server`. With `@modelcontextprotocol/server` 2.x, `createMcpHandler` and `serveStdio` build servers from a factory, so call `trackMcp` inside the factory, as in the [serverless examples](#serverless).

Long-running servers send calls in batches every second, and a stdio server that exits on its own sends its last batch before it exits. If your server ends itself with `process.exit`, for example in a SIGINT or SIGTERM handler, send the last batch first:

<CodeBlock language="ts">
  {`import { flushMcp } from "@databuddy/sdk/mcp";

process.on("SIGTERM", async () => {
  await flushMcp();
  process.exit(0);
});`}
</CodeBlock>

A client that starts your server over stdio, such as Claude Desktop, passes it only a few variables like `PATH` and `HOME`, not the ones from your shell. Set the key, and `NODE_ENV` to label the environment, in the server's `env` in the client config:

<CodeBlock language="json" filename="claude_desktop_config.json">
  {`{
  "mcpServers": {
    "my-server": {
      "command": "node",
      "args": ["/path/to/server.js"],
      "env": {
        "DATABUDDY_API_KEY": "dbdy_your_key",
        "NODE_ENV": "production"
      }
    }
  }
}`}
</CodeBlock>

## Serverless

A serverless function can stop before the batch goes out. Pass your platform's `waitUntil` and each call is sent before the function stops:

<Tabs items={['Vercel', 'Cloudflare Workers']}>
<Tab value="Vercel">
<CodeBlock language="ts" filename="app/api/mcp/route.ts">
  {`import { createMcpHandler, McpServer } from "@modelcontextprotocol/server";
import { waitUntil } from "@vercel/functions";
import { trackMcp } from "@databuddy/sdk/mcp";

const handler = createMcpHandler(() =>
  trackMcp(new McpServer({ name: "my-server", version: "1.0.0" }), {
    waitUntil,
  })
);

export const POST = (request: Request) => handler.fetch(request);`}
</CodeBlock>

With Vercel's `mcp-handler`, wrap the server it passes you, before or after you register your tools. Name it with `serverInfo`, or it shows up as `mcp-typescript server on vercel`:

<CodeBlock language="ts" filename="app/api/mcp/route.ts">
  {`import { waitUntil } from "@vercel/functions";
import { createMcpHandler } from "mcp-handler";
import { trackMcp } from "@databuddy/sdk/mcp";

const handler = createMcpHandler(
  (server) => {
    trackMcp(server, { waitUntil });
  },
  { serverInfo: { name: "my-server", version: "1.0.0" } }
);

export { handler as GET, handler as POST };`}
</CodeBlock>
</Tab>
<Tab value="Cloudflare Workers">
<CodeBlock language="ts">
  {`import { createMcpHandler, McpServer } from "@modelcontextprotocol/server";
import { env, waitUntil } from "cloudflare:workers";
import { trackMcp } from "@databuddy/sdk/mcp";

const handler = createMcpHandler(() =>
  trackMcp(new McpServer({ name: "my-server", version: "1.0.0" }), {
    apiKey: env.DATABUDDY_API_KEY,
    waitUntil,
  })
);

export default {
  fetch: (request: Request) => handler.fetch(request),
};`}
</CodeBlock>

Store the key with `wrangler secret put DATABUDDY_API_KEY`. Workers without `nodejs_compat` have no `process.env`, so pass `websiteId` and `environment` the same way if you use them.
</Tab>
</Tabs>

## Servers, websites and environments

Calls belong to the organization that owns the API key, and the MCP page shows all of them. Three things separate them, with no setup:

- **Server**: the `name` your MCP server registers with. Give each server its own name.
- **Website**: the `websiteId` option, or else the first Databuddy website ID in your server's environment: `NEXT_PUBLIC_DATABUDDY_CLIENT_ID`, its `NUXT_PUBLIC_`, `VITE_` and `REACT_APP_` versions, then `DATABUDDY_WEBSITE_ID`.
- **Environment**: `VERCEL_ENV`, or `NODE_ENV`, so local and preview calls stay apart from production.

The page shows a picker for each one as soon as there's more than one value. Click a tool or a client to see only its calls.

## Options

| Option | Default | Description |
| --- | --- | --- |
| `apiKey` | `DATABUDDY_API_KEY` | API key with the Event Tracking scope |
| `websiteId` | Detected from your Databuddy website ID | Website to link calls to |
| `environment` | `VERCEL_ENV` or `NODE_ENV` | Environment label |
| `apiUrl` | `https://basket.databuddy.cc` | Ingestion endpoint |
| `beforeSend` | | Edit a call before it's sent, or return `null` to drop it |
| `waitUntil` | | Your platform's `waitUntil`, so serverless functions send each call before they stop |
| `debug` | `false` | Log a missing API key, an unsupported server, a call that fails to record (for example when `beforeSend` throws), and every rejected or failed send to stderr |

Without an API key, `trackMcp` leaves the server untouched. An API key limited to some websites can only send calls linked to one of them. If the website ID is unknown, inactive, or belongs to another organization, Databuddy rejects the whole batch. To keep calls unlinked, use an API key for the whole organization and clear the website in `beforeSend`: `(call) => ({ ...call, websiteId: undefined })`.

## What gets recorded

Each tool call records the tool name, whether it failed, its error code and its error message, how long your handler took, how many characters of text the tool returned (divide by about 4 for tokens), the client's name and version, your server's name and version, the MCP session ID when your server keeps sessions, and the user agent.

The error message is the first text of an `isError` result or the thrown message. The MCP page groups failures by error code: return an `isError` result whose text is JSON such as `{"error": {"code": "not_found", "message": "Website not found"}}`, and the `code` groups the call while the message is unwrapped. A good code is stable, short and snake_case, like `not_found` or `rate_limited`, and never holds IDs or other per-call values, because each distinct code is its own group. Codes are cut to 64 characters. `McpServer` turns an error your tool throws into plain text, so its `code` is lost, unless it is an `McpError` from `@modelcontextprotocol/sdk` 1.x, which puts the code in its message.

Databuddy reads protocol error codes from the message, so they work with any `@databuddy/sdk` version: `invalid_params` for bad arguments, `method_not_found`, and `invalid_output` for output schema failures on `@modelcontextprotocol/server` 2.x (1.x reports those as `invalid_params`). Codes from JSON bodies, from the `code` or name of an error your low-level `Server` handler throws, and `cancelled` for calls the client cancels need `@databuddy/sdk` 3.2.1 or later.

A call that asks the client for more input is recorded once, when it returns its final result. On `@databuddy/sdk` 3.2.1 or later this includes URL elicitations, which 3.2.0 records as a failed call. Calls that a client runs as a background task aren't recorded.

Clients are named from the `clientInfo` they send. Stateless servers, which build a new server per request, don't see it on tool calls unless the client uses the 2026-07-28 protocol and your server runs `@modelcontextprotocol/server` 2.x. Otherwise Databuddy falls back to the user agent: ChatGPT sends `openai-mcp`, claude.ai sends `Claude-User`. Clients it can't name show up as **Unknown client** with their most common user agents. The user agent needs `@modelcontextprotocol/sdk` 1.13.2 or later, or `@modelcontextprotocol/server` 2.x; on older versions, stateless servers show every call as **Unknown client**.

Tracking never changes what a client receives. It doesn't throw, doesn't delay responses, and sends in the background with a 5 second timeout. If Databuddy rejects the calls, for example because of a wrong API key, `trackMcp` logs the reason once to stderr. Each recorded call counts as one event on your plan.

### Keep error messages private

Error messages can include input your handler put in them. To keep them on your server and still count the call as failed, blank the message:

<CodeBlock language="ts">
  {`trackMcp(server, {
  beforeSend: (call) => (call.error === undefined ? call : { ...call, error: "" }),
});`}
</CodeBlock>

Codes read from the message, such as a JSON body's `code` or `invalid_params`, go with it. On `@databuddy/sdk` 3.2.1 or later, the codes of thrown errors and cancelled calls are still sent.

---

# Node SDK reference

> Complete reference for the Databuddy Node.js SDK for server-side analytics tracking

import { Tab, Tabs, Callout, Card, Cards, CodeBlock } from "@/components/docs";

The Databuddy Node SDK provides a type-safe way to track server-side analytics events from Node.js, Bun, Deno, and serverless environments.

<Callout type="info">
  **SDK Version**: 2.0.0+ | **Package**: `@databuddy/sdk` | **API**: basket.databuddy.cc
</Callout>

## TL;DR

The Node SDK is perfect for tracking server-side events like API calls, background jobs, webhooks, and more. It supports batching and explicit flushes for serverless environments.

<CodeBlock language="tsx">
  {`import { Databuddy } from '@databuddy/sdk/node';

const client = new Databuddy({
  apiKey: process.env.DATABUDDY_API_KEY!,
  enableBatching: true
});

await client.track({
  name: 'api_call',
  properties: { endpoint: '/api/users', method: 'GET' }
});

await client.flush(); // Important in serverless!`}
</CodeBlock>

## Installation

<CodeBlock language="bash">
  {`bun add @databuddy/sdk`}
</CodeBlock>

## Quick start

### Basic usage

<CodeBlock language="tsx">
  {`import { Databuddy } from '@databuddy/sdk/node';

// Initialize the client
const client = new Databuddy({
  apiKey: process.env.DATABUDDY_API_KEY!
});

// Track an event
await client.track({
  name: 'user_signup',
  properties: {
    plan: 'pro',
    source: 'api'
  }
});`}
</CodeBlock>

### Serverless usage

In serverless environments, always flush before the function exits:

<CodeBlock language="tsx">
  {`import { Databuddy } from '@databuddy/sdk/node';

const client = new Databuddy({
  apiKey: process.env.DATABUDDY_API_KEY!,
  enableBatching: true
});

export async function handler(event) {
  await client.track({
    name: 'lambda_invocation',
    properties: { source: event.source }
  });
  
  // Ensure events are sent before function exits
  const flushResult = await client.flush();
  if (!flushResult.success) {
    console.error("Failed to flush analytics:", flushResult.error);
  }
  
  return { statusCode: 200 };
}`}
</CodeBlock>

## Configuration

<CodeBlock language="tsx">
  {`interface DatabuddyConfig {
    apiKey: string;               // Required: Your API key for authentication
    websiteId?: string;           // Optional: Default Client ID to scope events
    namespace?: string;           // Optional: Default namespace for logical grouping
    source?: string;              // Optional: Default source identifier for events
    apiUrl?: string;              // Default: 'https://basket.databuddy.cc'
    debug?: boolean;              // Enable debug logging
    logger?: Logger;              // Custom logger instance
    enableBatching?: boolean;     // Default: true
    batchSize?: number;           // Default: 10, Max: 100
    batchTimeout?: number;        // Default: 2000ms
    maxQueueSize?: number;        // Default: 1000
    enableDeduplication?: boolean; // Default: true
    maxDeduplicationCacheSize?: number; // Default: 10000
    requestTimeoutMs?: number;    // Default: 10000ms request deadline
    middleware?: Middleware[];     // Transform or drop events before send
  }`}
</CodeBlock>

<CodeBlock language="tsx">
  {`import { Databuddy } from '@databuddy/sdk/node';

const client = new Databuddy({
  apiKey: process.env.DATABUDDY_API_KEY!,
  enableBatching: true,
  batchSize: 20,
  batchTimeout: 5000
});`}
</CodeBlock>

## Core methods

### `track(event)`

Track custom events with optional properties, session IDs, and anonymous IDs:

<CodeBlock language="tsx">
  {`await client.track({
  name: 'purchase_completed',
  eventId: 'purchase-ORD-789',
  anonymousId: 'anon_123',
  sessionId: 'sess_456',
  properties: {
    order_id: 'ORD-789',
    revenue: 299.99,
    currency: 'USD',
    items: 3
  }
});`}
</CodeBlock>

**Response:**

<CodeBlock language="tsx">
  {`interface EventResponse {
  success: boolean;
  eventId?: string;
  error?: string;
  delivery?: "delivered" | "queued" | "skipped";
  code?: string;         // e.g. "NETWORK_ERROR", "VALIDATION_ERROR", "QUEUE_FULL"
  why?: string;
  fix?: string;
  requestId?: string;
  retryable?: boolean;
  statusCode?: number;
}`}
</CodeBlock>

With `enableBatching: true`, `track()` usually confirms that the event was queued. It returns a delivery failure only when the call immediately sends the event, such as `enableBatching: false` or when the queue reaches `batchSize` or `maxQueueSize`. Call `flush()` when you need the final delivery result.

Use `eventId` when your code may retry the same logical event. The SDK uses it as a local deduplication key for queued or already delivered events.

Put an event in [accounts](/docs/sdk/accounts) with `groups`, sent as `group_<type>` properties that win over the same keys in `properties`:

<CodeBlock language="tsx">
  {`await client.track({ name: 'export_completed', groups: { workspace: 'ws_123' } });`}
</CodeBlock>

`groups` takes the same shape as the browser's, so you can pass the accounts the page was in: a `null` or `undefined` key puts the event in no account of that type. A group type that isn't lowercase letters, digits and underscores, the type `email_domain` (used by the accounts Databuddy makes from email domains), or a key that is blank or longer than 256 characters fails with `VALIDATION_ERROR` and sends nothing; in `batch()`, nothing in the batch is sent.

<Callout type="warn">
Server-side events are stored as custom events. They do not create the pageview
sessions that referrer, campaign, country, and device reporting is built on, and
[revenue attribution](/docs/Integrations/payments) cannot join to them. Passing a
`sessionId` you generated on the server does not change this. To attribute
server-side activity, take the real `sessionId` from `getIds()` in the
browser and send it to your server.
</Callout>

### `batch(events)`

Send multiple events in a single batch (max 100 events):

<CodeBlock language="tsx">
  {`await client.batch([
  {
    type: 'custom',
    name: 'event1',
    properties: { foo: 'bar' }
  },
  {
    type: 'custom',
    name: 'event2',
    anonymousId: 'anon_123',
    sessionId: 'sess_456',
    properties: { baz: 'qux' }
  }
]);`}
</CodeBlock>

### `identify(input)`

Link your user's stable ID to their tracked activity and set profile traits:

<CodeBlock language="tsx">
  {`await client.identify({
  profileId: 'user-123',
  anonymousId: 'anon_...',  // Optional: link pre-login device activity
  traits: {
    email: 'jane@example.com',
    plan: 'pro'
  }
});`}
</CodeBlock>

`profileId` is required. `websiteId` comes from the config default or can be passed per call. Pass the client's raw `anonymousId` (from the web SDK's `getIds().anonymousId`) to connect pre-login events from that device. Requires an API key with the `track:events` scope for the target website. Identify calls send immediately and are not batched. See [Identify users](/docs/sdk/identify-users) for concepts and trait rules.

### `group(input)`

Set traits on an account, company, or team:

<CodeBlock language="tsx">
  {`await client.group({
  groupType: 'company',
  groupKey: 'acme',
  traits: {
    name: 'Acme',
    domain: 'acme.com',
    billing_plan: 'enterprise',
    billing_status: 'active',
    billing_mrr: 990,
    billing_customer: 'cus_8f2k',
    created_at: '2025-03-14',
    last_active_at: '2026-11-10',
    usage_7d: 1840,
    usage_30d: 7920
  }
});`}
</CodeBlock>

`groupType` uses lowercase letters, digits, and underscores. As in `track()`'s `groups`, a type that doesn't, the type `email_domain`, or a key that is blank, longer than 256 characters or contains a NUL character fails with `VALIDATION_ERROR` and sends nothing. Visitors join a group through events: call [`group()`](/docs/sdk/accounts) in the browser, or pass `groups: { company: 'acme' }` to `track()`, and their activity counts toward that group. Traits are typed as `AccountTraits` and follow the same flat-value rules as profile traits; a `Date` is sent as an ISO string, and an invalid one fails with `VALIDATION_ERROR`. Requires an API key with the `track:events` scope for the target website. Group calls send immediately and are not batched.

The Accounts view reads these traits when you send them:

- `name`, `domain` and `logo` name the account; `domain` also looks up the company behind it.
- `billing_plan`, `billing_status` (a Stripe subscription status such as `active`, `trialing` or `past_due`), `billing_mrr` and `billing_trial_ends_at` say how it pays.
- `billing_customer` is who pays, such as a Stripe customer ID. Accounts that send the same one share a plan: its payment, trial and limit are flagged once, on the most used of them, and a spare workspace isn't flagged as paying for nothing while another of them is in use. Subscriptions synced from Stripe send it for you.
- `created_at` is when the account was created, so an account older than your tracking isn't mistaken for a new one.
- `last_active_at` is its last activity your events don't see, such as API calls or background jobs, so an account in use isn't flagged as quiet. Once you send it for some accounts, a new account without it is flagged as not started.
- `usage_7d` and `usage_30d` are how much it used your product over the last 7 and 30 days, the 30 including the 7, in your own unit (API calls, messages, page views). Use this week is never quiet, and a week well below the three before it is flagged, urgently for an account that pays.
- `plan_usage` and `plan_limit` are how much of its plan it used this period and what the plan includes, in your own unit (events, seats, credits), so an account near or over its limit is flagged for an upgrade talk.

### `flush()`

Manually flush all queued events. **Critical for serverless environments:**

<CodeBlock language="tsx">
  {`await client.track({ name: 'event1' });
await client.track({ name: 'event2' });
await client.track({ name: 'event3' });

// Flush all queued events before function exits
const flushResult = await client.flush();
if (!flushResult.success) {
  console.error("Failed to flush analytics:", flushResult.error);
}`}
</CodeBlock>

## Event tracking patterns

### Per-event options

You can override the default `websiteId`, `namespace`, and `source` for individual events:

<CodeBlock language="tsx">
  {`// Set defaults in config
const client = new Databuddy({
  apiKey: process.env.DATABUDDY_API_KEY!,
  websiteId: "default-website",
  namespace: "api",
  source: "backend"
});

// Override per-event
await client.track({
  name: 'payment_processed',
  websiteId: 'billing-service',  // Override default websiteId
  namespace: 'payments',          // Override default namespace
  source: 'stripe-webhook',       // Override default source
  properties: {
    amount: 99.99,
    currency: 'USD'
  }
});

// Mix defaults and overrides
await client.track({
  name: 'user_login',
  namespace: 'auth',  // Only override namespace
  properties: {
    method: 'oauth',
    provider: 'google'
  }
});`}
</CodeBlock>

**Use Cases:**

- **websiteId**: Scope events to different websites within your organization
- **namespace**: Group events logically (e.g. `billing`, `auth`, `api`, `webhook`)
- **source**: Identify where the event originated (e.g. `backend`, `webhook`, `cli`, `cron-job`)

### E-commerce events

<CodeBlock language="tsx">
  {`// Product viewed
await client.track({
  name: 'product_viewed',
  anonymousId: userId,
  sessionId: sessionId,
  properties: {
    product_id: 'P12345',
    category: 'Electronics',
    price: 99.99,
    currency: 'USD'
  }
});

// Purchase completed
await client.track({
  name: 'purchase_completed',
  anonymousId: userId,
  sessionId: sessionId,
  properties: {
    order_id: 'ORD-789',
    revenue: 299.99,
    currency: 'USD',
    items: 3,
    payment_method: 'credit_card'
  }
});`}
</CodeBlock>

### API and backend events

<CodeBlock language="tsx">
  {`// API call tracking
await client.track({
  name: 'api_call',
  properties: {
    endpoint: '/api/users',
    method: 'GET',
    status_code: 200,
    duration_ms: 45
  }
});

// Background job tracking
await client.track({
  name: 'job_completed',
  properties: {
    job_name: 'email_digest',
    duration_ms: 5400,
    emails_sent: 1250,
    status: 'success'
  }
});`}
</CodeBlock>

### Webhook events

<CodeBlock language="tsx">
  {`// Stripe webhook
await client.track({
  name: 'stripe_webhook_received',
  properties: {
    event_type: 'payment_intent.succeeded',
    amount: 2999,
    currency: 'usd'
  }
});

// Generic webhook
await client.track({
  name: 'webhook_received',
  properties: {
    source: 'github',
    event_type: 'push',
    repository: 'my-repo'
  }
});`}
</CodeBlock>

### Authentication events

<CodeBlock language="tsx">
  {`// User signup
await client.track({
  name: 'user_signup',
  anonymousId: userId,
  properties: {
    method: 'email',
    plan: 'free',
    source: 'landing_page'
  }
});

// User login
await client.track({
  name: 'user_login',
  anonymousId: userId,
  sessionId: sessionId,
  properties: {
    method: 'oauth',
    provider: 'google',
    success: true
  }
});`}
</CodeBlock>

## Session and anonymous IDs

The Node SDK supports optional `anonymousId` and `sessionId` fields to track user sessions across requests. **These IDs should match the IDs generated by the web SDK** to enable unified tracking across client and server.

<Callout type="warn">
**Important**: When tracking server-side events for a user session, you must use the **same anonymousId and sessionId** that the web SDK generated on the client. This ensures events are properly attributed to the same user and session.
</Callout>

### Getting IDs from the web SDK

The web SDK automatically generates and manages these IDs. You need to pass them to your backend to use in server-side tracking.

**Client-Side (React/Next.js):**

<CodeBlock language="tsx" filename="app/components/checkout-button.tsx">
  {`import { getIds } from '@databuddy/sdk';

export function CheckoutButton() {
  const handleCheckout = async () => {
    const { anonymousId, sessionId } = getIds();
    
    if (anonymousId || sessionId) {
      await fetch('/api/checkout', {
        method: 'POST',
        body: JSON.stringify({ anonymousId, sessionId, cart: [...] })
      });
    }
  };
  
  return <button onClick={handleCheckout}>Checkout</button>;
}`}
</CodeBlock>

**Server-Side (API Route):**

<CodeBlock language="tsx" filename="app/api/checkout/route.ts">
  {`import { Databuddy } from '@databuddy/sdk/node';
import { NextResponse } from 'next/server';

const client = new Databuddy({
  apiKey: process.env.DATABUDDY_API_KEY!
});

export async function POST(request: Request) {
  const { anonymousId, sessionId, cart } = await request.json();
  
  await client.track({
    name: 'checkout_started',
    anonymousId,
    sessionId,
    properties: {
      cart_value: calculateTotal(cart),
      items_count: cart.length
    }
  });
  
  return NextResponse.json({ success: true });
}`}
</CodeBlock>

### Web SDK ID access methods

<CodeBlock language="tsx">
  {`import { getIds } from '@databuddy/sdk';

const { anonymousId, sessionId, profileId } = getIds();

// IDs passed from another domain in the URL take precedence
const fromUrl = getIds(new URLSearchParams(window.location.search));`}
</CodeBlock>

<Callout type="info">
**ID Format**: 
- Anonymous IDs: `anon_xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`
- Session IDs: `sess_xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`

These are UUID v4 strings with a prefix. The web SDK stores them in localStorage (anonymousId) and sessionStorage (sessionId).
</Callout>

## Environment-specific usage

### Next.js API routes

<CodeBlock language="tsx" filename="app/api/track/route.ts">
  {`import { Databuddy } from '@databuddy/sdk/node';
import { NextResponse } from 'next/server';

const client = new Databuddy({
  apiKey: process.env.DATABUDDY_API_KEY!,
  enableBatching: false
});

export async function POST(request: Request) {
  const body = await request.json();
  
  await client.track({
    name: 'api_endpoint_called',
    properties: {
      endpoint: '/api/track',
      payload_size: JSON.stringify(body).length
    }
  });
  
  return NextResponse.json({ success: true });
}`}
</CodeBlock>

### Express.js middleware

<CodeBlock language="tsx">
  {`import express from 'express';
import { Databuddy } from '@databuddy/sdk/node';

const client = new Databuddy({
  apiKey: process.env.DATABUDDY_API_KEY!
});

const app = express();

app.use(async (req, res, next) => {
  const start = Date.now();
  
  res.on('finish', async () => {
    await client.track({
      name: 'http_request',
      properties: {
        method: req.method,
        path: req.path,
        status_code: res.statusCode,
        duration_ms: Date.now() - start
      }
    });
  });
  
  next();
});

process.on('SIGTERM', async () => {
  await client.flush();
  process.exit(0);
});`}
</CodeBlock>

### AWS Lambda

<CodeBlock language="tsx">
  {`import { Databuddy } from '@databuddy/sdk/node';

const client = new Databuddy({
  apiKey: process.env.DATABUDDY_API_KEY!,
  enableBatching: true
});

export const handler = async (event: any) => {
  try {
    await client.track({
      name: 'lambda_invoked',
      properties: {
        function_name: process.env.AWS_LAMBDA_FUNCTION_NAME,
        event_source: event.source
      }
    });
    
    const result = await processEvent(event);
    
    await client.track({
      name: 'lambda_success',
      properties: { result_count: result.length }
    });
    
    return { statusCode: 200, body: JSON.stringify(result) };
  } catch (error) {
    await client.track({
      name: 'lambda_error',
      properties: { error: error.message, stack: error.stack }
    });
    throw error;
  } finally {
    await client.flush();
  }
};`}
</CodeBlock>

### Cloudflare Workers

<Callout type="info">
  The Node SDK imports `node:crypto`, so Cloudflare Workers require the `nodejs_compat` compatibility flag in your `wrangler.toml`.
</Callout>

<CodeBlock language="tsx">
  {`import { Databuddy } from '@databuddy/sdk/node';

export default {
  async fetch(request: Request, env: Env) {
    const client = new Databuddy({
      apiKey: env.DATABUDDY_API_KEY,
      enableBatching: false
    });
    
    await client.track({
      name: 'worker_request',
      properties: { url: request.url, method: request.method }
    });
    
    return new Response('Hello World');
  }
};`}
</CodeBlock>

### Bun server

<CodeBlock language="tsx">
  {`import { Databuddy } from '@databuddy/sdk/node';

const client = new Databuddy({
  apiKey: process.env.DATABUDDY_API_KEY!
});

Bun.serve({
  port: 3000,
  async fetch(req) {
    await client.track({
      name: 'bun_request',
      properties: { url: req.url, method: req.method }
    });
    
    return new Response('Hello from Bun!');
  }
});`}
</CodeBlock>

## Batching

Events are automatically batched when batch size or timeout is reached:

<CodeBlock language="tsx">
  {`const client = new Databuddy({
    apiKey: process.env.DATABUDDY_API_KEY!,
    websiteId: process.env.DATABUDDY_WEBSITE_ID,
    namespace: "api",
    source: "backend",
    enableBatching: true,
    batchSize: 20,
    batchTimeout: 5000
  });

// These will be batched automatically
await client.track({ name: 'event1' });
await client.track({ name: 'event2' });
await client.track({ name: 'event3' });

const flushResult = await client.flush();
if (!flushResult.success) {
  console.error("Failed to deliver analytics:", flushResult.error);
}`}
</CodeBlock>

## Deduplication

When `enableDeduplication` is enabled, events with the same `eventId` are dropped if they are already queued or were delivered successfully. Failed sends do not poison the deduplication cache, so you can retry the same `eventId` after a temporary network or API failure.

<CodeBlock language="tsx">
  {`const response = await client.track({
  name: "invoice_paid",
  eventId: \`stripe-\${stripeEvent.id}\`,
  properties: { invoice_id: invoice.id }
});

if (!response.success) {
  // Safe to retry later with the same eventId
  await retryAnalyticsEvent();
}`}
</CodeBlock>

## Debugging

Enable debug logging:

<CodeBlock language="tsx">
  {`const client = new Databuddy({
  apiKey: process.env.DATABUDDY_API_KEY!,
  debug: true
});`}
</CodeBlock>

## Error handling

The SDK returns success/failure status for delivery errors instead of throwing:

<CodeBlock language="tsx">
  {`const response = await client.track({
  name: 'test_event',
  properties: { test: true }
});

if (!response.success) {
  console.error('Failed to track event:', response.error);
}`}
</CodeBlock>

The constructor still throws for invalid configuration, such as a missing or blank `apiKey`.

## TypeScript support

The SDK is fully typed:

<CodeBlock language="tsx">
  {`import { Databuddy, type CustomEventInput } from '@databuddy/sdk/node';

const client = new Databuddy({
  apiKey: process.env.DATABUDDY_API_KEY!,
  enableBatching: true
});

const event: CustomEventInput = {
  name: 'user_signup',
  anonymousId: 'anon_123',
  sessionId: 'sess_456',
  properties: { plan: 'pro', source: 'api' }
};

await client.track(event);`}
</CodeBlock>

## Best practices

### Always flush in serverless

<CodeBlock language="tsx">
  {`// Good
export async function handler(event: any) {
  await client.track({ name: 'event' });
  await client.flush();
  return { statusCode: 200 };
}

// Avoid: events may be lost
export async function handler(event: any) {
  await client.track({ name: 'event' });
  return { statusCode: 200 };
}`}
</CodeBlock>

### Use consistent property names

<CodeBlock language="tsx">
  {`// Good: consistent naming
await client.track({
  name: 'api_call',
  properties: {
    endpoint: '/api/users',
    method: 'GET',
    status_code: 200
  }
});

// Avoid: inconsistent naming
await client.track({
  name: 'API_CALL',
  properties: {
    EndPoint: '/api/users',
    METHOD: 'GET',
    statusCode: 200
  }
});`}
</CodeBlock>

## Troubleshooting

| Issue | Solution |
|-------|----------|
| Events not appearing | Verify `apiKey`, check network in logs with `debug: true` |
| Authentication errors | Ensure `apiKey` is valid and has proper permissions |
| TypeScript errors | Ensure TypeScript 4.5+, check `@databuddy/sdk` version |
| Serverless events missing | Always call `await client.flush()` before function exits |
| High latency | Enable batching: `enableBatching: true, batchSize: 50` |
| Temporary network failures | Check `response.success` and retry from your application when the event is safe to send again |
| Memory issues | Reduce `maxQueueSize`, flush more frequently |
| Wrong website/namespace | Check per-event `websiteId`, `namespace`, and `source` values |

## Related

<Cards>
  <Card title="React SDK" href="/docs/sdk/react">
    Client-side tracking with React component
  </Card>
  <Card title="Tracker helpers" href="/docs/sdk/tracker">
    Helper functions for tracking
  </Card>
  <Card title="Server-side flags" href="/docs/sdk/server-flags">
    Server-side feature flag evaluation
  </Card>
  <Card title="API reference" href="/docs/api">
    Direct HTTP API for custom implementations
  </Card>
</Cards>

---

# Nuxt

> Zero-config Nuxt module with auto-imports, SPA tracking, and TypeScript support

import { Callout, CodeBlock, Card, Cards } from "@/components/docs";

`@databuddy/nuxt` is a first-class Nuxt module. Add it to `nuxt.config.ts` once and you're done. Pageviews and SPA navigation work automatically with no `app.vue` changes. Set `autocapture: { errors: true }` to also capture JavaScript and Vue component errors.

## Install

Run this in your project root. It installs the package **and** adds it to your `nuxt.config.ts` automatically:

<CodeBlock language="bash">
  {`npx nuxi module add @databuddy/nuxt`}
</CodeBlock>

Or install manually:

<CodeBlock language="bash">
  {`bun add @databuddy/nuxt
# npm install @databuddy/nuxt
# yarn add @databuddy/nuxt
# pnpm add @databuddy/nuxt`}
</CodeBlock>

## Setup

Add your Client ID to `nuxt.config.ts`:

<CodeBlock language="ts" filename="nuxt.config.ts">
  {`export default defineNuxtConfig({
  modules: ["@databuddy/nuxt"],
  databuddy: {
    clientId: process.env.NUXT_PUBLIC_DATABUDDY_CLIENT_ID,
  },
})`}
</CodeBlock>

<CodeBlock language="bash" filename=".env">
  {`NUXT_PUBLIC_DATABUDDY_CLIENT_ID=your-client-id`}
</CodeBlock>

The module tracks pageviews and route changes without any `app.vue` edits or plugins.

<Callout type="info">
  Nuxt automatically maps the `NUXT_PUBLIC_DATABUDDY_CLIENT_ID` environment variable to `runtimeConfig.public.databuddy.clientId`, so no extra configuration is needed.
</Callout>

## Tracking events

`useDatabuddy` is auto-imported in every component:

<CodeBlock language="html" filename="pages/index.vue">
  {`<script setup>
const { track } = useDatabuddy()

function handleSignup() {
  track("signup_clicked", {
    source: "hero",
    plan: "pro",
  })
}
</script>

<template>
  <button @click="handleSignup">Get started</button>
</template>`}
</CodeBlock>

### Full composable API

All functions are available from `useDatabuddy()`:

| Function | Description |
|----------|-------------|
| `track(name, properties?)` | Track a custom event |
| `trackError(error, properties?)` | Track an error, from an `Error` or a message |
| `screenView(properties?)` | Manually trigger a pageview |
| `setGlobalProperties(properties)` | Attach properties to all future events |
| `identify(userId, traits?)` | Link this browser to a user ID from your system |
| `reset()` | Forget the user and reset anonymous and session IDs (call after logout) |
| `flush()` | Force-send all queued events immediately |
| `getIds()` | Get `{ anonymousId, sessionId, profileId }` |
| `getTrackingParams()` | Get IDs as a URL query string for cross-domain tracking |
| `optOut()`, `optIn()` | Stop or resume tracking this visitor; visitors with Global Privacy Control or Do Not Track stay untracked |

## Options API and templates

`$databuddy` is available directly in templates and Options API components with no import needed:

<CodeBlock language="html">
  {`<template>
  <button @click="$databuddy.track('cta_clicked')">Sign up</button>
</template>`}
</CodeBlock>

<CodeBlock language="ts">
  {`export default defineComponent({
  methods: {
    handleClick() {
      this.$databuddy.track("cta_clicked")
    },
  },
})`}
</CodeBlock>

## Feature flags

Add the `flags` config to enable the flag composables:

<CodeBlock language="ts" filename="nuxt.config.ts">
  {`export default defineNuxtConfig({
  modules: ["@databuddy/nuxt"],
  databuddy: {
    clientId: process.env.NUXT_PUBLIC_DATABUDDY_CLIENT_ID,
    flags: {}, // clientId is inherited automatically
  },
})`}
</CodeBlock>

Then use `useFlag` and `useFlags`, which are auto-imported everywhere:

<CodeBlock language="html">
  {`<script setup>
const { on: isNewCheckout, loading } = useFlag("new-checkout")
</script>

<template>
  <template v-if="loading">
    <CheckoutSkeleton />
  </template>
  <template v-else-if="isNewCheckout">
    <NewCheckout />
  </template>
  <template v-else>
    <LegacyCheckout />
  </template>
</template>`}
</CodeBlock>

## Module options

All options are passed under the `databuddy` key in `nuxt.config.ts`. The grouped names (`autocapture`, `batching`, `retries`, `sampleRate`, `skipPaths`, `maskPaths`) need `@databuddy/nuxt` 3.1.0 or later; the flat names they replace still work.

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `clientId` | `string` | - | Your Databuddy Client ID |
| `disabled` | `boolean` | `false` | Disable all tracking |
| `debug` | `boolean` | `false` | Enable verbose logging |
| `autocapture` | `boolean \| object` | `{ interactions: true }` | What to record besides pageviews: `webVitals`, `errors` (JS errors + Vue component errors), `outgoingLinks`, `interactions`, `attributes`, `hashChanges` |
| `maskPaths` | `string[]` | `[]` | Glob patterns to anonymise paths |
| `skipPaths` | `string[]` | `[]` | Glob patterns to skip entirely |
| `sampleRate` | `number` | `1` | Fraction of automatic pageview and page-exit events sent, from 0 to 1, decided per event; `track()` events are not sampled |
| `flags` | `FlagsConfig` | - | Feature flag configuration |

The module also accepts the other [browser options](/docs/sdk/configuration) (`batching`, `retries`, `replay`, `scriptUrl`, ...) except `filter`, because runtime config can't hold functions.

## Privacy

<CodeBlock language="ts" filename="nuxt.config.ts">
  {`export default defineNuxtConfig({
  modules: ["@databuddy/nuxt"],
  databuddy: {
    clientId: process.env.NUXT_PUBLIC_DATABUDDY_CLIENT_ID,
    // Never track admin or internal routes
    skipPaths: ["/admin/**", "/internal/*"],
    // Anonymise user IDs in paths
    maskPaths: ["/users/*", "/orders/**"],
  },
})`}
</CodeBlock>

## Disable in development

<CodeBlock language="ts" filename="nuxt.config.ts">
  {`export default defineNuxtConfig({
  modules: ["@databuddy/nuxt"],
  databuddy: {
    clientId: process.env.NUXT_PUBLIC_DATABUDDY_CLIENT_ID,
    disabled: process.env.NODE_ENV !== "production",
  },
})`}
</CodeBlock>

## Related

<Cards>
  <Card title="Vue SDK" href="/docs/sdk/vue">
    Component-based integration for plain Vue 3 apps
  </Card>
  <Card title="Feature flags" href="/docs/sdk/feature-flags">
    Complete feature flag documentation
  </Card>
  <Card title="Tracker helpers" href="/docs/sdk/tracker">
    track, flush, getIds, and more
  </Card>
  <Card title="SDK configuration" href="/docs/sdk/configuration">
    Full configuration reference
  </Card>
</Cards>

---

# Migrate from PostHog

> Move a PostHog integration to Databuddy by changing imports, with PostHog's method names kept for events, identify, and feature flags

import { Callout, CodeBlock } from "@/components/docs";

If your product already calls PostHog for events, identify, and feature flags, you can move it to Databuddy without rewriting those call sites. The `@databuddy/sdk` package ships adapters that keep PostHog's method names and argument shapes, so most of the migration is changing three import paths.

## Change the imports

<CodeBlock language="bash">
  {`bun remove posthog-js posthog-node
bun add @databuddy/sdk`}
</CodeBlock>

| PostHog import | Databuddy import |
| --- | --- |
| `posthog-js` | `@databuddy/sdk/posthog` |
| `posthog-js/react` | `@databuddy/sdk/posthog/react` |
| `posthog-node` | `@databuddy/sdk/posthog/node` |

## Browser

Pass your Databuddy client ID where PostHog expected a project token. PostHog transport options such as `api_host`, `defaults`, and `person_profiles` still compile and are ignored, because events always go to Databuddy.

<CodeBlock language="tsx">
  {`import posthog from '@databuddy/sdk/posthog';

posthog.init(process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!, {
  capture_exceptions: true,
  capture_performance: true,
});

posthog.identify(user.id, { email: user.email, plan: user.plan });
posthog.capture('checkout_completed', { total: 49 });

posthog.onFeatureFlags(() => {
  if (posthog.isFeatureEnabled('new-checkout')) {
    showNewCheckout();
  }
});`}
</CodeBlock>

`capture_exceptions` and `capture_performance` turn on error and Web Vitals tracking. The second argument also accepts the other [Databuddy configuration options](/docs/sdk/configuration), such as `maskPaths`, `sampleRate`, `batching` or `replay`, so you can set them in the same call. Databuddy's grouped `autocapture` object (`errors`, `webVitals`, `outgoingLinks`, ...) wins over the flat names; PostHog's own `autocapture: true` and its allowlist keys are ignored.

Feature flags load asynchronously, so read them inside `onFeatureFlags()`, which runs once flags are ready and again after every reload. Calling `identify()` or `group()` re-evaluates flags for that user and group, and the callback runs again with the new values, so targeting rules on traits such as `plan` apply as soon as the user signs in.

## React

<CodeBlock language="tsx">
  {`import {
  PostHogProvider,
  useFeatureFlagEnabled,
} from '@databuddy/sdk/posthog/react';

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <PostHogProvider apiKey={process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!}>

---

## Additional Documentation

This single-file agent corpus is capped below 200,000 characters for one-request ingestion. Continue with the scoped indexes at https://www.databuddy.cc/docs/llms.txt, https://www.databuddy.cc/api/llms.txt, and https://www.databuddy.cc/developers/llms.txt.
