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
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>
);
}
<!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
<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'}
/>
<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:
Name | Type | Optional | Description |
---|---|---|---|
eventName | string | No | The 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. |
properties | object | Yes | An 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:
Name | Type | Optional | Description |
---|---|---|---|
eventName | string | No | The name of the custom event (e.g., 'newsletter_subscribed' , 'feature_engagement_time' ). |
properties | object | Yes | An 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:
Name | Type | Optional | Description |
---|---|---|---|
path | string | Yes | The path of the screen to track (e.g., '/profile/settings' ). Defaults to window.location.pathname if not provided. |
properties | object | Yes | Additional 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:
Name | Type | Optional | Description |
---|---|---|---|
properties | object | No | An 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 inBaseEventProperties
. - Custom Properties: Any additional key-value pairs you provide in the
properties
object when callingdb.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 viadb.screenView()
ordb.track('screen_view', ...)
.
Specific Properties:
Property | Type | Optional | Description |
---|---|---|---|
time_on_page | number | Yes | Time spent on the page in milliseconds. Often added when the view ends or a new view starts. |
scroll_depth | number | Yes | Maximum scroll depth percentage reached on the page (e.g., 75 for 75%). |
interaction_count | number | Yes | Number of significant user interactions on the page (e.g., clicks, form submissions). |
has_exit_intent | boolean | Yes | true if exit intent was detected before the user left the page. Requires trackExitIntent={true} . |
is_bounce | 0 | 1 | Yes | 1 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:
Property | Type | Optional | Description |
---|---|---|---|
time_on_page | number | No | Total time spent on the page in milliseconds. |
scroll_depth | number | No | Maximum scroll depth percentage reached. |
interaction_count | number | No | Total number of significant user interactions. |
has_exit_intent | boolean | No | true if exit intent was detected. |
page_count | number | No | Number of pages viewed in the current session up to this point. |
is_bounce | 0 | 1 | No | 1 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, ortrackAttributes={true}
for elements withdata-track
attributes. Can also be sent manually.
Specific Properties:
Property | Type | Optional | Description |
---|---|---|---|
button_text | string | Yes | The text content of the button. |
button_type | string | Yes | The type attribute of the button (e.g., 'submit', 'button'). |
button_id | string | Yes | The id attribute of the button. |
element_class | string | Yes | The 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
});
});
link_out
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:
Property | Type | Optional | Description |
---|---|---|---|
href | string | No | The URL of the outgoing link. |
text | string | Yes | The anchor text of the link. |
target_domain | string | Yes | The 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:
Property | Type | Optional | Description |
---|---|---|---|
form_id | string | Yes | The id attribute of the form. |
form_name | string | Yes | The name attribute of the form. |
form_type | string | Yes | A custom descriptor for the form's purpose (e.g., 'contact', 'signup', 'search'). |
success | boolean | Yes | Indicates 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:
Property | Type | Optional | Description |
---|---|---|---|
fcp | number | Yes | First Contentful Paint (milliseconds). |
lcp | number | Yes | Largest Contentful Paint (milliseconds). |
cls | string | Yes | Cumulative Layout Shift score (typically a float, represented as string or number). |
fid | number | Yes | First Input Delay (milliseconds). |
ttfb | number | Yes | Time to First Byte (milliseconds). |
load_time | number | Yes | Total page load time (milliseconds). |
dom_ready_time | number | Yes | DOMContentLoaded time (milliseconds). |
render_time | number | Yes | Time to render critical path (custom metric, if applicable). |
request_time | number | Yes | Time 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:
Property | Type | Optional | Description |
---|---|---|---|
message | string | No | The error message. |
filename | string | Yes | The name of the file where the error occurred. |
lineno | number | Yes | The line number where the error occurred. |
colno | number | Yes | The column number where the error occurred. |
stack | string | Yes | The error stack trace. |
error_type | string | Yes | A 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:
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 insnake_case
.properties
: This object is where you add context to your event.
The examples below illustrate common use cases.
<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
.
Option | Default | Type | Range | Description |
---|---|---|---|---|
clientId | - | string | Required | Your Databuddy project client ID. |
clientSecret | undefined | string | - | Client secret for server-side operations (NEVER expose in browser). |
apiUrl | https://basket.databuddy.cc | string | Valid URL | Custom API endpoint for event ingestion. |
scriptUrl | https://cdn.databuddy.cc/databuddy.js | string | Valid URL | Custom script URL for the browser bundle. |
sdk | 'web' | string | - | SDK name for analytics (advanced). |
sdkVersion | package.json version | string | - | SDK version (advanced). |
disabled | false | boolean | - | Disable all tracking if true. |
waitForProfile | false | boolean | - | Wait for user profile before sending events (advanced). |
trackScreenViews | true | boolean | - | Automatically track screen/page views. |
trackHashChanges | false | boolean | - | Track hash changes in the URL. |
trackSessions | true | boolean | - | Track user sessions. |
trackAttributes | false | boolean | - | Track data-* attributes on element clicks. |
trackOutgoingLinks | false | boolean | - | Track clicks on outgoing links. |
trackInteractions | false | boolean | - | Track user interactions (e.g., button clicks). |
trackEngagement | false | boolean | - | Track user engagement metrics. |
trackScrollDepth | false | boolean | - | Track scroll depth. |
trackExitIntent | false | boolean | - | Track exit intent. |
trackBounceRate | false | boolean | - | Track bounce rate. |
trackPerformance | true | boolean | - | Track page performance metrics. |
trackWebVitals | false | boolean | - | Track Web Vitals metrics. |
trackErrors | false | boolean | - | Track JavaScript errors. |
samplingRate | 1.0 | number | 0.0 - 1.0 | Sampling rate for events (e.g., 0.5 = 50%). |
enableRetries | true | boolean | - | Enable retries for failed requests. |
maxRetries | 3 | number | e.g., 0-10 | Max number of retries. |
initialRetryDelay | 500 | number | e.g., 50-10000ms | Initial retry delay in milliseconds. |
enableBatching | false | boolean | - | Enable event batching. |
batchSize | 10 | number | 1 - 50 | Number of events to batch. |
batchTimeout | 2000 | number | 100 - 30000ms | Batch timeout in milliseconds. |
filter | undefined | (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:
# 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
<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