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.

Version: 1.0.2 | 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://app.databuddy.cc/databuddy.js"
  data-client-id="your-client-id"
  defer
></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
          trackPerformance
          trackWebVitals
        />
        {children}
      </body>
    </html>
  );
}
index.html
<!DOCTYPE html>
<html>
<head>
  <title>My Website</title>
</head>
<body>
  <!-- Your content -->
  
  <script 
    src="https://app.databuddy.cc/databuddy.js"
    data-client-id="your-client-id"
    data-track-screen-views="true"
    data-track-performance="true"
    data-track-web-vitals="true"
    defer
  ></script>
</body>
</html>

🔧 Configuration Options

Required Settings

<Databuddy
  clientId="your-client-id"  // ✅ Required - Get from dashboard
/>
<script 
  src="https://app.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:

Optional Tracking Features

These features are disabled by default - enable as needed:

Performance Impact: Enabling many optional features can increase data volume and impact performance. Choose only what 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://app.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

🎯 Custom Event Tracking

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>
  );
}

Alternative Object Syntax:

// Both syntaxes work identically
db.track('event_name', { key: 'value' });
window.databuddy?.track('event_name', { key: 'value' });
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

OptionDefaultTypeRange
clientId-stringRequired
disabledfalseboolean-
trackScreenViewstrueboolean-
trackPerformancetrueboolean-
trackSessionstrueboolean-
trackWebVitalsfalseboolean-
trackErrorsfalseboolean-
trackOutgoingLinksfalseboolean-
trackScrollDepthfalseboolean-
trackEngagementfalseboolean-
enableBatchingfalseboolean-
batchSize10number1-50
batchTimeout2000number100-30000ms
samplingRate1.0number0.0-1.0
enableRetriestrueboolean-
maxRetries3number0-10
initialRetryDelay500number50-10000ms
apiUrlhttps://basket.databuddy.ccstringValid URL
scriptUrlhttps://app.databuddy.cc/databuddy.jsstringValid URL

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