SDK Reference

Complete reference for the Databuddy SDK and JavaScript library

📦 SDK Reference

The Databuddy SDK provides both a React component and a standalone JavaScript library for tracking analytics events. This guide covers all configuration options, types, and usage patterns based on the actual implementation.

SDK Version: Defaults to the version in package.json | API: basket.databuddy.cc | CDN: app.databuddy.cc

🚀 Installation

# Using bun (recommended)
bun add @databuddy/sdk

# Using npm
npm install @databuddy/sdk

# Using yarn
yarn add @databuddy/sdk

No installation needed - load directly from CDN:

<script 
  src="https://cdn.databuddy.cc/databuddy.js"
  data-client-id="your-client-id"
  async
></script>

⚡ Quick Start

app/layout.tsx
import { Databuddy } from '@databuddy/sdk';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <Databuddy
          clientId={process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!}
          trackScreenViews // Enabled by default, shown for clarity
          trackPerformance // Enabled by default, shown for clarity
          trackWebVitals={true} // Recommended, but false by default
        />
        {children}
      </body>
    </html>
  );
}
index.html
<!DOCTYPE html>
<html>
<head>
  <title>My Website</title>
</head>
<body>
  <!-- Your content -->
  
  <script 
    src="https://cdn.databuddy.cc/databuddy.js"
    data-client-id="your-client-id"
    data-track-screen-views="true"  // Enabled by default, shown for clarity
    data-track-performance="true"  // Enabled by default, shown for clarity
    data-track-web-vitals="true"   // Recommended, but false by default
    async
  ></script>
</body>
</html>

🔧 Configuration Options

Required Settings

<Databuddy
  clientId="your-client-id"  // ✅ Required - Get from dashboard
/>
<script 
  src="https://cdn.databuddy.cc/databuddy.js"
  data-client-id="your-client-id"  <!-- Required -->
></script>

Core Tracking Features

These features are enabled by default and recommended for most websites. Refer to types.ts for the most up-to-date default values.

Optional Tracking Features

These features are disabled by default unless otherwise noted. Enable them as needed based on your tracking requirements. Refer to types.ts for the most up-to-date default values.

Performance Impact: Enabling many optional features can increase data volume and potentially impact performance. Choose only the features you need.

Performance & Reliability

Performance Configuration
<Databuddy
  clientId="your-client-id"
  
  // Batching (reduces requests)
  enableBatching={false}     // Default: false
  batchSize={10}             // Default: 10 (range: 1-50)
  batchTimeout={2000}        // Default: 2000ms (range: 100-30000)
  
  // Reliability
  enableRetries={true}       // Default: true
  maxRetries={3}             // Default: 3
  initialRetryDelay={500}    // Default: 500ms (range: 50-10000)
  
  // Sampling (for high-traffic sites)
  samplingRate={1.0}         // Default: 1.0 (range: 0.0-1.0)
  
  // Environment control
  disabled={process.env.NODE_ENV === 'development'}
/>
Performance Configuration
<script 
  src="https://cdn.databuddy.cc/databuddy.js"
  data-client-id="your-client-id"
  
  <!-- Batching -->
  data-enable-batching="false"
  data-batch-size="10"
  data-batch-timeout="2000"
  
  <!-- Reliability -->
  data-enable-retries="true"
  data-max-retries="3"
  data-initial-retry-delay="500"
  
  <!-- Sampling -->
  data-sampling-rate="1.0"
  
  <!-- Environment -->
  data-disabled="false"
></script>

Batching: Groups multiple events into single requests. Enable for high-traffic sites to reduce server load.

Advanced Configuration

💻 SDK Methods Reference

Once the Databuddy SDK is initialized (either via the <Databuddy /> component or the script tag), you can interact with it programmatically using methods available on window.databuddy or its shorter alias window.db.

These methods allow you to send custom data, manage user sessions, and control SDK behavior dynamically.

Ensure the SDK is fully loaded before calling these methods. If you're using the script tag with async, place your custom calls in a script that also asyncs or executes after the Databuddy script has loaded.


track()

Tracks a custom event with a specific name and optional properties. This is the primary method for sending most custom analytics data. It can be used for pre-defined event types (like button_click, form_submit) or any custom event name you define.

Syntax:

window.databuddy?.track(eventName, properties);
// or
window.db?.track(eventName, properties);

Parameters:

NameTypeOptionalDescription
eventNamestringNoThe name of the event to track (e.g., 'product_viewed', 'signup_completed'). Use snake_case for consistency. Refer to EventTypeMap in types.ts for some predefined event names and their specific expected properties.
propertiesobjectYesAn object containing key-value pairs of custom data to associate with the event. Values can be strings, numbers, or booleans. Avoid sending Personally Identifiable Information (PII).

Returns: Promise<void> - A promise that resolves when the event has been processed (e.g., queued or sent).

Example:

// Tracking a product view
window.db?.track('product_viewed', {
  product_id: 'P12345',
  product_name: 'Wireless Noise-Cancelling Headphones',
  category: 'Electronics',
  price: 299.99,
  currency: 'USD'
});

// Tracking a button click (using a predefined event type)
window.db?.track('button_click', {
  button_text: 'Add to Cart',
  button_id: 'add-to-cart-btn',
  page_location: '/products/P12345'
});

// Tracking an error event
window.db?.track('error', {
  message: 'Failed to load user profile',
  filename: 'UserProfile.js',
  lineno: 42,
  colno: 10,
  error_type: 'APIError',
  stack: 'Error: API request failed at UserProfile.js:42:10'
});

For general JavaScript error tracking, consider using the trackErrors={true} configuration option, which automatically captures unhandled errors. The track('error', ...) method is for manual error reporting.


trackCustomEvent()

This method is an alias for track(). It's provided for clarity when you are explicitly tracking an event that is not one of the predefined EventTypeMap names. Functionally, it behaves identically to track().

Syntax:

window.databuddy?.trackCustomEvent(eventName, properties);
// or
window.db?.trackCustomEvent(eventName, properties);

Parameters:

NameTypeOptionalDescription
eventNamestringNoThe name of the custom event (e.g., 'newsletter_subscribed', 'feature_engagement_time').
propertiesobjectYesAn object of custom data associated with the event.

Returns: Promise<void>

Example:

window.db?.trackCustomEvent('early_access_requested', {
  feature_name: 'New Dashboard Analytics',
  user_segment: 'power_users'
});

screenView()

Manually tracks a screen or page view. This is useful in Single Page Applications (SPAs) if the automatic trackScreenViews option is disabled or if you need to trigger a screen view under specific conditions. If trackScreenViews is enabled, this is usually not needed.

Syntax:

window.databuddy?.screenView(path, properties);
// or
window.db?.screenView(path, properties);

Parameters:

NameTypeOptionalDescription
pathstringYesThe path of the screen to track (e.g., '/profile/settings'). Defaults to window.location.pathname if not provided.
propertiesobjectYesAdditional custom properties to associate with this screen view event.

Returns: void

Example:

// Manually track a screen view after a custom navigation event in an SPA
function handleRouteChange(newPath) {
  // ... your routing logic ...
  window.db?.screenView(newPath, { navigation_type: 'custom_spa_router' });
}

// If called without arguments, it uses current path
// window.db?.screenView();

setGlobalProperties()

Sets global properties that will be automatically included with every event tracked by the SDK during the current user session (or until clear() is called or the page is reloaded). This is useful for setting persistent user traits or application versions.

Syntax:

window.databuddy?.setGlobalProperties(properties);
// or
window.db?.setGlobalProperties(properties);

Parameters:

NameTypeOptionalDescription
propertiesobjectNoAn object containing key-value pairs to be set as global properties. These will be merged with existing global properties. To remove a global property, set its value to undefined.

Returns: void

Example:

// Set user properties after login
window.db?.setGlobalProperties({
  user_id: 'user-98765',
  user_role: 'administrator',
  app_version: '2.5.1'
});

// Later, to update a global property
window.db?.setGlobalProperties({
  app_version: '2.5.2'
});

// To remove a global property (e.g., on logout)
window.db?.setGlobalProperties({
  user_role: undefined
});

Global properties are not persisted across different browser sessions or if the user clears their site data. They are stored in memory for the current page lifecycle.


clear()

Clears the current user session and generates new session IDs. This is typically used when a user logs out, to ensure subsequent activity is not associated with the previous user's session. It also clears any global properties set by setGlobalProperties.

Syntax:

window.databuddy?.clear();
// or
window.db?.clear();

Parameters: None

Returns: void

Example:

function handleLogout() {
  // ... your application logout logic ...

  window.db?.clear(); // Clears session and global properties

  // ... redirect to login page ...
}

flush()

Forces the SDK to immediately send any queued events to the server. This can be useful in scenarios where you need to ensure events are sent before a page unloads, but use with caution as frequent flushing can negate the benefits of batching if it's enabled.

Syntax:

window.databuddy?.flush();
// or
window.db?.flush();

Parameters: None

Returns: void

Example:

// Example: Attempt to send any remaining events before user navigates away
// Note: `navigator.sendBeacon` is often a more reliable way to send data on page unload.
// The SDK might use sendBeacon internally if available.
window.addEventListener('beforeunload', () => {
  window.db?.track('app_closing', { reason: 'user_navigation' });
  window.db?.flush();
});

If enableBatching is false, events are typically sent immediately or with a very short delay, making manual flush() calls less necessary.

📖 Standard Event Reference

The Databuddy SDK defines a set of standard event types, each with a specific structure and purpose. These events are often tracked automatically by the SDK when certain configuration options are enabled (e.g., trackScreenViews, trackErrors). You can also track these events manually using the db.track('event_name', properties) method.

Understanding these standard events can help you interpret your analytics data and decide when to track them manually.

Extensible Properties

All standard events documented below can also include:

  • Base Properties: Common properties like __path, __title, sessionId, utm_source, etc., defined in BaseEventProperties.
  • Custom Properties: Any additional key-value pairs you provide in the properties object when calling db.track(). This allows you to enrich standard events with context specific to your application.

screen_view

Tracks a view of a page or a screen in a single-page application.

  • Typically triggered by: Enabled by trackScreenViews={true} configuration, or can be sent manually via db.screenView() or db.track('screen_view', ...).

Specific Properties:

PropertyTypeOptionalDescription
time_on_pagenumberYesTime spent on the page in milliseconds. Often added when the view ends or a new view starts.
scroll_depthnumberYesMaximum scroll depth percentage reached on the page (e.g., 75 for 75%).
interaction_countnumberYesNumber of significant user interactions on the page (e.g., clicks, form submissions).
has_exit_intentbooleanYestrue if exit intent was detected before the user left the page. Requires trackExitIntent={true}.
is_bounce0 | 1Yes1 if the page view is considered a bounce (single page session), 0 otherwise. Requires trackBounceRate={true}.

Example (Manual Tracking):

window.db?.track('screen_view', {
  __path: '/products/cool-widget',
  __title: 'Cool Widget Product Page',
  time_on_page: 30000, // e.g., if tracked at page unload or transition
  scroll_depth: 50,
  interaction_count: 3
});

page_exit

Tracks when a user navigates away from a page, often capturing final engagement metrics for that page view.

  • Typically triggered by: Can be part of automatic engagement tracking or sent manually. This event consolidates metrics at the end of a page view.

Specific Properties:

PropertyTypeOptionalDescription
time_on_pagenumberNoTotal time spent on the page in milliseconds.
scroll_depthnumberNoMaximum scroll depth percentage reached.
interaction_countnumberNoTotal number of significant user interactions.
has_exit_intentbooleanNotrue if exit intent was detected.
page_countnumberNoNumber of pages viewed in the current session up to this point.
is_bounce0 | 1No1 if this page view was a bounce.

Example (Manual Tracking):

// Usually tracked automatically if relevant features are enabled.
// Manual tracking might be for specific scenarios.
window.db?.track('page_exit', {
  __path: '/checkout/step1',
  time_on_page: 120000,
  scroll_depth: 100,
  interaction_count: 5,
  has_exit_intent: false,
  page_count: 3,
  is_bounce: 0
});

button_click

Tracks a click on a button element.

  • Typically triggered by: Can be automatically tracked if trackInteractions={true} is configured for generic clicks, or trackAttributes={true} for elements with data-track attributes. Can also be sent manually.

Specific Properties:

PropertyTypeOptionalDescription
button_textstringYesThe text content of the button.
button_typestringYesThe type attribute of the button (e.g., 'submit', 'button').
button_idstringYesThe id attribute of the button.
element_classstringYesThe CSS class(es) of the button.

Example (Manual Tracking):

document.getElementById('myButton').addEventListener('click', () => {
  window.db?.track('button_click', {
    button_text: 'Learn More',
    button_id: 'myButton',
    page_section: 'hero' // Custom property
  });
});

Tracks a click on a link that navigates to an external domain.

  • Typically triggered by: Enabled by trackOutgoingLinks={true} configuration. Can also be sent manually.

Specific Properties:

PropertyTypeOptionalDescription
hrefstringNoThe URL of the outgoing link.
textstringYesThe anchor text of the link.
target_domainstringYesThe domain name of the link's target.

Example (Manual Tracking):

// If trackOutgoingLinks is false, or for special cases:
document.getElementById('externalLink').addEventListener('click', function(event) {
  const href = event.target.href;
  window.db?.track('link_out', {
    href: href,
    text: event.target.innerText,
    target_domain: new URL(href).hostname
  });
});

form_submit

Tracks the submission of a form.

  • Typically triggered by: Can be automatically tracked if trackInteractions={true} is configured. Can also be sent manually for more control or to add specific properties.

Specific Properties:

PropertyTypeOptionalDescription
form_idstringYesThe id attribute of the form.
form_namestringYesThe name attribute of the form.
form_typestringYesA custom descriptor for the form's purpose (e.g., 'contact', 'signup', 'search').
successbooleanYesIndicates if the form submission was successful (e.g., passed client-side or server-side validation).

Example (Manual Tracking):

document.getElementById('contactForm').addEventListener('submit', (event) => {
  // Assuming validation logic here
  const isSuccess = true; // Replace with actual validation result

  window.db?.track('form_submit', {
    form_id: 'contactForm',
    form_type: 'contact_inquiry',
    success: isSuccess,
    // Add other form-specific data, carefully avoiding PII
    inquiry_topic: document.getElementById('topicSelect').value
  });
});

web_vitals

Tracks Core Web Vitals and other performance metrics.

  • Typically triggered by: Enabled by trackWebVitals={true} configuration. Manual tracking is generally not recommended as these are browser-reported metrics.

Specific Properties:

PropertyTypeOptionalDescription
fcpnumberYesFirst Contentful Paint (milliseconds).
lcpnumberYesLargest Contentful Paint (milliseconds).
clsstringYesCumulative Layout Shift score (typically a float, represented as string or number).
fidnumberYesFirst Input Delay (milliseconds).
ttfbnumberYesTime to First Byte (milliseconds).
load_timenumberYesTotal page load time (milliseconds).
dom_ready_timenumberYesDOMContentLoaded time (milliseconds).
render_timenumberYesTime to render critical path (custom metric, if applicable).
request_timenumberYesTime for primary request/response (custom metric, if applicable).

Example (Illustrative - usually automatic):

// This is typically handled automatically by the SDK when trackWebVitals=true.
// Manual tracking would be unusual.
window.db?.track('web_vitals', {
  fcp: 1200.5,
  lcp: 2500.0,
  cls: "0.102", // As per types.ts, CLS is string. Industry often uses number.
  fid: 50.2,
  ttfb: 300.0
});

The cls (Cumulative Layout Shift) property is defined as string in types.ts. While the raw value from browser APIs is a number, it might be formatted as a string by the SDK.


error

Tracks JavaScript errors or other manually reported errors.

  • Typically triggered by: Enabled by trackErrors={true} for automatic capture of unhandled JavaScript errors and promise rejections. Can also be sent manually for handled errors or custom error reporting.

Specific Properties:

PropertyTypeOptionalDescription
messagestringNoThe error message.
filenamestringYesThe name of the file where the error occurred.
linenonumberYesThe line number where the error occurred.
colnonumberYesThe column number where the error occurred.
stackstringYesThe error stack trace.
error_typestringYesA custom type for the error (e.g., 'APIError', 'ValidationError', 'TypeError').

Example (Manual Tracking for a Handled Error):

try {
  // Some operation that might fail
  let data = JSON.parse(invalidJsonString);
} catch (e) {
  window.db?.track('error', {
    message: e.message,
    filename: 'dataProcessor.js', // Or dynamically get filename
    lineno: 25, // Or dynamically get line number if possible
    stack: e.stack,
    error_type: 'SyntaxError',
    severity: 'warning', // Custom property
    operation: 'parseUserData' // Custom property
  });
  // Handle the error gracefully in the UI
}

🎯 Custom Event Tracking

This section focuses on the strategy and best practices for tracking custom business events to gain valuable insights. For the detailed syntax of the track() and trackCustomEvent() methods, please refer to the SDK Methods Reference. When tracking events, you can use the standard event types documented above if they fit your use case, or define completely custom event names.

Track custom business events with detailed properties for comprehensive analytics:

Custom Events with Properties
import { useEffect } from 'react';

function ProductPage({ product }: { product: Product }) {
  useEffect(() => {
    // Track product view with detailed properties
    window.databuddy?.track('product_viewed', {
      product_id: product.id,
      product_name: product.name,
      category: product.category,
      price: product.price,
      currency: 'USD',
      brand: product.brand,
      in_stock: product.availability > 0
    });
  }, [product]);

  const handlePurchase = () => {
    // Track conversion with purchase details
    window.databuddy?.track('purchase_completed', {
      product_id: product.id,
      revenue: product.price,
      currency: 'USD',
      payment_method: 'credit_card',
      shipping_method: 'standard',
      coupon_used: false
    });
  };

  const handleAddToCart = (quantity: number) => {
    // Track cart actions with context
    window.databuddy?.track('add_to_cart', {
      product_id: product.id,
      quantity: quantity,
      value: product.price * quantity,
      currency: 'USD',
      source: 'product_page'
    });
  };

  return (
    <div>
      <h1>{product.name}</h1>
      <button onClick={() => handleAddToCart(1)}>Add to Cart</button>
      <button onClick={handlePurchase}>Buy Now - ${product.price}</button>
    </div>
  );
}

Understanding Event Naming and Properties:

When using db.track('your_event_name', { property: 'value' }):

  • your_event_name: Choose clear, consistent names in snake_case.
  • properties: This object is where you add context to your event.

The examples below illustrate common use cases.

Custom Events with Rich Properties
<script>
// Track user actions with detailed context
function trackSignup(plan, source) {
  db.track('signup_completed', {
    plan: plan,
    source: source,
    trial_days: plan === 'pro' ? 14 : 7,
    referrer: document.referrer,
    utm_source: new URLSearchParams(window.location.search).get('utm_source')
  });
}

function trackFeatureUsage(feature, context) {
  db.track('feature_used', {
    feature: feature,
    page: window.location.pathname,
    user_tier: context.userTier,
    session_duration: context.sessionTime,
    previous_action: context.lastAction
  });
}

// Track complex interactions
function trackVideoEngagement(videoId, action, timestamp) {
  db.track('video_engagement', {
    video_id: videoId,
    action: action, // 'play', 'pause', 'complete', 'seek'
    timestamp: timestamp,
    duration: document.querySelector('#video').duration,
    quality: document.querySelector('#video').videoQuality,
    fullscreen: document.fullscreenElement !== null
  });
}

// Track form interactions with validation context
document.getElementById('contact-form').addEventListener('submit', (e) => {
  const formData = new FormData(e.target);
  db.track('contact_form_submitted', {
    form_id: 'contact-form',
    fields_completed: Array.from(formData.keys()).length,
    inquiry_type: formData.get('inquiry_type'),
    page: window.location.pathname,
    time_to_complete: Date.now() - window.formStartTime
  });
});
</script>

<button onclick="trackSignup('pro', 'pricing_page')">Upgrade to Pro</button>
<button onclick="trackFeatureUsage('export', {userTier: 'premium'})">Export Data</button>

Custom Event Best Practices

Event Naming: Use snake_case for event names (e.g., signup_completed, product_viewed) Properties: Include rich context for detailed analytics but avoid PII (personally identifiable information) Property Keys: Use consistent naming across events for better analysis

Rich Property Tracking

// ✅ Detailed properties for comprehensive analysis
db.track('purchase_completed', {
  product_category: 'software',    // Groupable property
  payment_method: 'credit_card',   // Behavior analysis
  plan_type: 'annual',            // Business metric
  discount_applied: true,         // Conversion tracking
  value: 299.99,                 // Revenue tracking
  currency: 'USD',               // Standardization
  source: 'pricing_page'         // Attribution
});

// ✅ Consistent property names across events
db.track('add_to_cart', {
  product_category: 'software',   // Same key as purchase
  value: 299.99,                // Same key format
  currency: 'USD',              // Consistent currency
  source: 'product_page'        // Consistent attribution
});

Avoid These Patterns

// ❌ Don't include PII
db.track('signup', {
  email: 'user@example.com',     // PII violation
  phone: '+1234567890',         // PII violation
  ip_address: '192.168.1.1'     // PII violation
});

// ❌ Don't use inconsistent naming
db.track('purchase', {
  productCat: 'software',        // camelCase instead of snake_case
  'payment method': 'card',      // spaces in keys
  Price: 299.99                 // inconsistent capitalization
});

// ❌ Don't use vague event names
db.track('click');              // Too generic
db.track('User Action');        // Spaces + vague

📊 Property Breakdown Analytics

Your custom event properties are automatically analyzed in the dashboard with:

Automatic Property Analysis:

  • 🏷️ Property keys - All custom properties are extracted and categorized
  • 📊 Value distributions - See how property values are distributed
  • 🎯 Usage frequency - Track which properties appear most often
  • 📈 Trend analysis - Monitor how property values change over time

Example Dashboard View:

Event: purchase_completed (247 events)
├── 📂 product_category (247 values)
│   ├── software: 156 (63%)
│   ├── hardware: 78 (32%)
│   └── services: 13 (5%)
├── 📂 payment_method (247 values)  
│   ├── credit_card: 198 (80%)
│   ├── paypal: 35 (14%)
│   └── bank_transfer: 14 (6%)
└── 📂 plan_type (247 values)
    ├── annual: 186 (75%)
    └── monthly: 61 (25%)

Dashboard Features:

  • 🔍 Expandable categories - Click to explore property breakdowns
  • 📊 Scrollable lists - Handle large property value lists efficiently
  • 🎯 Individual toggles - Open/close each property category independently
  • 📈 Percentage calculations - Automatic percentage distribution
  • 🔢 Value counts - Total occurrences for each property value

Visual Hierarchy:

  • Event Level - Overall event metrics and counts
  • Property Level - Property categories with aggregate counts
  • Value Level - Individual property values with percentages

📋 Configuration Reference

Default Values Table

This table provides a comprehensive list of all configuration options available in DatabuddyConfig, their default values, types, and allowed ranges where applicable, based on packages/sdk/src/types.ts.

OptionDefaultTypeRangeDescription
clientId-stringRequiredYour Databuddy project client ID.
clientSecretundefinedstring-Client secret for server-side operations (NEVER expose in browser).
apiUrlhttps://basket.databuddy.ccstringValid URLCustom API endpoint for event ingestion.
scriptUrlhttps://cdn.databuddy.cc/databuddy.jsstringValid URLCustom script URL for the browser bundle.
sdk'web'string-SDK name for analytics (advanced).
sdkVersionpackage.json versionstring-SDK version (advanced).
disabledfalseboolean-Disable all tracking if true.
waitForProfilefalseboolean-Wait for user profile before sending events (advanced).
trackScreenViewstrueboolean-Automatically track screen/page views.
trackHashChangesfalseboolean-Track hash changes in the URL.
trackSessionstrueboolean-Track user sessions.
trackAttributesfalseboolean-Track data-* attributes on element clicks.
trackOutgoingLinksfalseboolean-Track clicks on outgoing links.
trackInteractionsfalseboolean-Track user interactions (e.g., button clicks).
trackEngagementfalseboolean-Track user engagement metrics.
trackScrollDepthfalseboolean-Track scroll depth.
trackExitIntentfalseboolean-Track exit intent.
trackBounceRatefalseboolean-Track bounce rate.
trackPerformancetrueboolean-Track page performance metrics.
trackWebVitalsfalseboolean-Track Web Vitals metrics.
trackErrorsfalseboolean-Track JavaScript errors.
samplingRate1.0number0.0 - 1.0Sampling rate for events (e.g., 0.5 = 50%).
enableRetriestrueboolean-Enable retries for failed requests.
maxRetries3numbere.g., 0-10Max number of retries.
initialRetryDelay500numbere.g., 50-10000msInitial retry delay in milliseconds.
enableBatchingfalseboolean-Enable event batching.
batchSize10number1 - 50Number of events to batch.
batchTimeout2000number100 - 30000msBatch timeout in milliseconds.
filterundefined(event: any) => boolean-Custom function to filter events before sending.

Note: Ranges for maxRetries and initialRetryDelay are based on common usage patterns and comments in types.ts rather than strict programmatic enforcement within the type itself.

Environment Variables

For React/Next.js projects, set up environment variables:

.env.local
# Required
NEXT_PUBLIC_DATABUDDY_CLIENT_ID=your-client-id-here

# Optional - only for self-hosted instances
NEXT_PUBLIC_DATABUDDY_API_URL=https://your-api.example.com

Security: Never include clientSecret in client-side code. It's only for server-side usage.

🔍 Debugging & Testing

Development Mode

Disable tracking in development
<Databuddy
  clientId={process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!}
  disabled={process.env.NODE_ENV === 'development'}
  // ... other props
/>

Browser Console Testing

Test custom events in your browser console:

// Test if SDK is loaded
console.log(window.databuddy ? 'SDK loaded ✅' : 'SDK not loaded ❌');

// Send test event
db.track('test_event', { source: 'console', timestamp: Date.now() });

// Check network requests
// Look for requests to basket.databuddy.cc in Network tab

Common Issues