Datablit JavaScript SDK
A comprehensive JavaScript SDK for integrating Datablit's analytics, rules, and experiments into your applications. It offers functionalities such as event tracking, user identification, rule evaluation, and experiment variant retrieval.
Installation
Install the package using npm:
npm install @datablit/datablit-js
Quick Start
Here's how to get started with the Datablit JavaScript SDK:
import datablit from "@datablit/datablit-js";
// Initialize the SDK (must be called in an async function)
async function initializeDatablit() {
await datablit.init({
apiKey: "your-api-key-here",
});
// Track an event
datablit.track("Button Clicked", { buttonId: "signup-button" });
// Identify a user
datablit.identify("user123", { email: "user@example.com", plan: "premium" });
}
// Call the initialization function
initializeDatablit();
API Reference
datablit.init(config)
Initializes the Datablit SDK. You should initialize this library once before using any other functions.
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
config.apiKey | string | Yes | Your Datablit API key. Get this from the Datablit project source Create new project/source if its not created yet |
config.endpoint | string | No | API endpoint to send analytics data. Default: https://event.datablit.com/v1/batch |
config.batchSize | number | No | Number of events to batch before sending. Default: 20 |
config.flushInterval | number | No | Interval (in milliseconds) to flush batch events. Default: 30000 |
config.enablePageTracking | boolean | No | Enables automatic page view tracking. Default: false |
Analytics API
datablit.track(eventName, properties)
Tracks an event with associated properties.
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
eventName | string | Yes | Name of the event. |
properties | object | No | Key-value pairs of event properties. |
Example:
datablit.track("button_click", { button: "subscribe", user: "user_123" });
// More complex example
datablit.track("Purchase Completed", {
productId: "prod_123",
amount: 99.99,
currency: "USD",
});
datablit.identify(userId, traits)
Identifies a user with optional traits.
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
userId | string | Yes | Unique user ID. |
traits | object | No | Additional user attributes. |
Example:
datablit.identify("user_123", {
name: "John Doe",
email: "john.doe@example.com",
age: 30,
plan: "premium",
});
Rules API
datablit.rule.evalRule(request)
Evaluates a rule for a given user and context. This allows you to make dynamic decisions based on user attributes and rule logic.
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
request.key | string | Yes | The rule key identifier. |
request.userId | string | Yes | Unique user ID. |
request.params | object | No | Additional parameters for rule evaluation. |
Returns:
- Promise that resolves to an object with
result
(boolean) indicating whether the rule passed.
Example:
const ruleResult = await datablit.rule.evalRule({
key: "feature_flag",
userId: "user_123",
params: {
os_name: "android",
user_plan: "premium",
},
});
if (ruleResult.result) {
console.log("Rule evaluated to true - show feature");
} else {
console.log("Rule evaluated to false - hide feature");
}
Experiments API
datablit.experiment.getVariant(request)
Retrieves the experiment variant for a user. This is useful for A/B testing and feature experimentation.
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
request.expId | string | Yes | The experiment ID. |
request.entityId | string | Yes | Unique entity/user ID. |
Returns:
- Promise that resolves to an object with
variant
(string) indicating the assigned variant.
Example:
const variant = await datablit.experiment.getVariant({
expId: "01K2JKVXR0J0ZWPX40XY8CAWBS",
entityId: "user_123",
});
console.log("User is in variant:", variant.variant); // "control", "variant_a", etc.
// Use the variant to show different UI
if (variant.variant === "variant_a") {
// Show new feature
} else {
// Show control version
}
Auto Track Events
Page tracking
If config.enablePageTracking
is true
, the SDK will automatically track all page navigations.
For example, if a user navigates to http://localhost:3001/test
, the SDK will send the following track event:
{
"anonymousId": "3c42f2ca-d237-4acc-b9ce-773bd26f99e1",
"userId": "user_123",
"messageId": "228c9a87-891c-4ab2-9732-eddedc391f69",
"type": "track",
"context": {
"userAgentData": {
"architecture": "arm",
"bitness": "64",
"brands": [
{
"brand": "Chromium",
"version": "136"
},
{
"brand": "Google Chrome",
"version": "136"
},
{
"brand": "Not.A/Brand",
"version": "99"
}
],
"mobile": false,
"model": "",
"platform": "macOS",
"platformVersion": "15.4.1",
"uaFullVersion": "136.0.7103.114"
},
"library": {
"name": "@datablit/datablit-js",
"version": "1.0.3"
},
"userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
"timezone": "Asia/Calcutta",
"locale": "en-GB",
"page": {
"path": "/test",
"referrer": "",
"search": "",
"title": "",
"url": "http://localhost:3001/test"
}
},
"originalTimestamp": "2025-05-30T21:45:30.186Z",
"event": "Page View",
"properties": {
"url": "http://localhost:3001/test",
"title": "",
"referrer": ""
}
}
Error Handling
The SDK provides comprehensive error handling mechanisms:
try {
const ruleResult = await datablit.rule.evalRule({
key: "feature_flag",
userId: "user_123",
});
} catch (error) {
console.error("Failed to evaluate rule:", error.message);
}
try {
const variant = await datablit.experiment.getVariant({
expId: "01K2JKVXR0J0ZWPX40XY8CAWBS",
entityId: "user_123",
});
} catch (error) {
console.error("Failed to get variant:", error.message);
}
try {
datablit.track("Event", { data: "value" });
} catch (error) {
console.error("Failed to track event:", error.message);
}
Features
-
Analytics:
- Event Tracking: Monitor user interactions and custom events
- User Identification: Link events to specific users
- Automatic Page Tracking: Capture page views automatically
- Batch Processing: Efficiently batch events with retry logic
- Offline Support: Queue events locally when offline
-
Rules:
- Rule Evaluation: Assess rules against user context in real-time
- Context-based Decisions: Make dynamic decisions based on user attributes
-
Experiments:
- A/B Testing: Retrieve experiment variants for users
- Context-aware Assignment: Assign variants based on user context
- Statistical Analysis: Built-in support for experiment analysis
Usage in React
Here's how to use the Datablit SDK in a React application:
"use client";
import React, { useEffect } from "react";
import datablit from "@datablit/datablit-js";
function DatablitTest() {
useEffect(() => {
datablit.init({
apiKey: "your-api-key-here",
enablePageTracking: true,
});
}, []);
return (
<div className="flex gap-4">
<button
onClick={() => {
datablit.track("test_event", { name: "John Doe", value: 42 });
}}
>
Track Event
</button>
<button
onClick={() => {
datablit.identify("user_123", {
name: "John Doe",
email: "john.doe@example.com",
age: 30,
});
}}
>
Identify User
</button>
</div>
);
}
export default DatablitTest;
For more information and examples, visit the Datablit JavaScript SDK documentation.