SDK reference

React / Next.js

The Databuddy React SDK provides a component for script injection and hooks for custom event tracking. Works with React 18+, Next.js 13+, and other React-based frameworks.

For an installation walkthrough, use the Next.js guide, which includes a runnable App Router example and separate checks for network delivery and report visibility. This page is the component and helper reference.

Package: @databuddy/sdk | Import: @databuddy/sdk/react

Installation

bash
bun add @databuddy/sdk

Quick start

Add the Databuddy component to your root layout:

app/layout.tsxtsx
import { Databuddy } from "@databuddy/sdk/react";

export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
  <html lang="en">
    <body>
      <Databuddy
        clientId={process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!}
      />
      {children}
    </body>
  </html>
);
}

This starts with pageviews. Errors and Web Vitals are optional; enable them deliberately after reviewing your plan and collection settings. The root layout can remain a Server Component because the SDK's React entry point supplies its client boundary.

Databuddy component

The Databuddy component injects the tracking script and configures analytics. It renders nothing to the DOM.

Props

PropTypeDefaultDescription
clientIdstringAuto-detectedYour Client ID (auto-detects from NEXT_PUBLIC_DATABUDDY_CLIENT_ID)
disabledbooleanfalseDisable all tracking
debugbooleanfalseEnable debug logging

Tracking features

PropDefaultDescription
trackWebVitalsfalseFCP, LCP, INP, CLS, TTFB, and FPS
trackErrorsfalseJavaScript errors and unhandled rejections
trackOutgoingLinksfalseClicks on external links
trackInteractionstrueRage clicks, dead clicks, and abandoned forms
trackAttributesfalseElements with data-track attributes
trackHashChangesfalseHash changes in the URL

Batching and performance

PropDefaultDescription
enableBatchingtrueCompatibility option; pageviews still use the batch queue
batchSize10Events per batch (1-50)
batchTimeout5000Batch timeout in ms
samplingRate1.0Event sampling rate (0.0-1.0)

Allow for batchTimeout when checking whether pageviews were delivered. enableBatching=false does not bypass the current browser tracker's pageview queue. For a controlled test, set an explicit queue timeout and verify both the collector request and the destination report separately.

Privacy

PropTypeDescription
skipPatternsstring[]Skip tracking on matching paths
maskPatternsstring[]Mask sensitive URL segments

Session replay

PropTypeDescription
replayboolean | { maskText?: boolean; recordIframes?: boolean }Load the session replay recorder. Page text and typed input are masked; { maskText: false } records page text.

Full example

app/layout.tsxtsx
import { Databuddy } from "@databuddy/sdk/react";

export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
  <html lang="en">
    <body>
      <Databuddy
        clientId={process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!}
        trackWebVitals
        trackErrors
        trackOutgoingLinks
        enableBatching
        batchSize={20}
        disabled={process.env.NODE_ENV === "development"}
        skipPatterns={["/admin/**", "/internal/*"]}
        maskPatterns={["/users/*", "/orders/**"]}
      />
      {children}
    </body>
  </html>
);
}

Tracking events

Import tracker helpers to track custom events:

tsx
"use client";

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

function SignupButton() {
const handleClick = () => {
  track("signup_clicked", {
    source: "header",
    plan: "pro"
  });
};

return <button onClick={handleClick}>Sign Up</button>;
}

A signup_clicked event records intent, not a completed signup. Send confirmed outcomes from your backend with the Node SDK, and avoid recording the same outcome in both places. Browser track() returns void, so inspect the collector response and destination report separately.

The identity helpers (identify, setTraits, clearProfile, getProfileId) and the flags hooks (FlagsProvider, useFlag, useFlags) are also exported from @databuddy/sdk/react.

Common patterns

tsx
import { track, trackError } from "@databuddy/sdk";

// E-commerce
track("product_viewed", {
product_id: "P12345",
category: "Electronics",
price: 299.99
});

track("purchase_completed", {
order_id: "ORD-789",
revenue: 299.99,
currency: "USD"
});

// Feature usage
track("feature_used", {
feature: "export_data",
user_tier: "premium"
});

// Error tracking
try {
await riskyOperation();
} catch (error) {
trackError(error.message, {
  stack: error.stack,
  context: "checkout_flow"
});
}

Environment setup

.env.localbash
NEXT_PUBLIC_DATABUDDY_CLIENT_ID=your-client-id-here

The component auto-detects the Client ID from this environment variable.

Pages Router

For Next.js Pages Router, add to _app.tsx:

pages/_app.tsxtsx
import { Databuddy } from "@databuddy/sdk/react";
import type { AppProps } from "next/app";

export default function App({ Component, pageProps }: AppProps) {
return (
  <>
    <Databuddy
      clientId={process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!}
      trackWebVitals
    />
    <Component {...pageProps} />
  </>
);
}

Development mode

Disable tracking during development:

tsx
<Databuddy
clientId={process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!}
disabled={process.env.NODE_ENV === "development"}
/>

Data attributes

Enable automatic tracking of elements with data-track attributes:

tsx
<Databuddy
clientId={process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!}
trackAttributes
/>

{/* Automatically tracks button_click event */}
<button data-track="signup_clicked" data-plan="premium">
Sign Up
</button>

Before replacing an existing library, compare the integration trade-offs in the React and Next.js analytics SDK guide. Use the custom event measurement guide to decide which product actions your components should record.

How is this guide?