TypeScript SDK for Data Studio
npm install data-studio-sdkA TypeScript SDK for tracking user interactions, sessions, and events in your application. The SDK automatically handles client creation, session management, and event tracking with seamless backend synchronization via AWS SQS.
- Installation
- Quick Start
- API Reference
- Initialization
- Client Management
- Session Management
- Event Tracking
- Event Types
- Type Definitions
- Examples
- Best Practices
- Error Handling
``bash`
npm install data-studio-sdkor
yarn add data-studio-sdk
`typescript
import { DataStudioSDK } from "data-studio-sdk";
// Initialize the SDK with your API key
// Format: "tenantId@apiKey"
const sdk = new DataStudioSDK({
apiKey: "your-tenant-id@your-api-key",
});
// The SDK automatically creates a client on initialization
// Start a session
await sdk.startSession();
// Track events
await sdk.sendRatingEvent({
rating: 1,
max: 5,
raterId: "user-123",
});
// End session when done
await sdk.endSession();
`
#### new DataStudioSDK(config: DataStudioSDKConfig)
Creates a new instance of the Data Studio SDK.
Parameters:
- config.apiKey (string, required): API key in the format "apiKey" (e.g., "123@1234-567-890")
> Note: Your API key is available to copy from the Data Studio console.
Example:
`typescript`
const sdk = new DataStudioSDK({
apiKey: "your-api-key",
});
Note: The SDK automatically:
- Fetches credentials from the API
- Initializes sync services (Client, Session, Event)
- Creates a client on initialization
---
#### createClient(input?: ClientInput): Promise
Creates a new client. This is automatically called during SDK initialization, but you can call it manually if needed.
Parameters:
- input (ClientInput, optional): Manual client configuration. If not provided, the SDK auto-detects browser information in browser environments.
Returns: Promise
Example:
`typescript
// Browser environment - auto-detects info
const client = await sdk.createClient();
// Node.js/server environment - manual input
const client = await sdk.createClient({
clientType: "server",
ip: "192.168.1.1",
region: "us-east-1",
city: "New York",
timezone: "America/New_York",
});
`
#### getClient(): Client | null
Returns the current client instance.
Returns: Client | null
Example:
`typescriptClient ID: ${client.id}
const client = sdk.getClient();
if (client) {
console.log();`
}
#### closeClient(): Promise
Closes the current client. This automatically ends any active session and syncs the updated client to the backend.
Example:
`typescript`
await sdk.closeClient();
---
#### startSession(input?: SessionInput): Promise
Starts a new session. A client must be created before starting a session.
Parameters:
- input (SessionInput, optional): Session configurationuserId?: string
- - Optional user identifiercountry?: string
- - Country codedeviceType?: string
- - Device typereferrer?: string
- - Referrer URL
Returns: Promise
Example:
`typescript`
const session = await sdk.startSession({
userId: "user-123",
country: "US",
deviceType: "desktop",
referrer: "https://example.com",
});
#### endSession(): Promise
Ends the current active session. Calculates session duration and syncs to backend.
Example:
`typescript`
await sdk.endSession();
#### getCurrentSession(): Session | null
Returns the current active session.
Returns: Session | null
Example:
`typescriptSession ID: ${session.id}, Status: ${session.status}
const session = sdk.getCurrentSession();
if (session) {
console.log();`
}
---
The SDK provides methods for tracking various types of events. All event methods require an active session.
#### Feedback & Quality Events
Helpful for experience analytics.
Rating Submitted
##### sendRatingEvent(event: RatingEvent): Promise
Sends a rating submitted event.
Parameters:
- event.rating (number, required): rating valueevent.max
- (number, required): Maximum rating valueevent.source
- (string, optional): Source of the ratingevent.raterId
- (string, optional): ID of the user providing the rating
Example:
`typescript`
await sdk.sendRatingEvent({
rating: 1,
max: 5,
source: "product-page",
raterId: "user-123",
});
Feedback Submitted
##### sendFeedbackEvent(event: FeedbackEvent): Promise
Sends a feedback submitted event.
Parameters:
- event.text (string, required): Feedback textevent.category
- (string, optional): Feedback categoryevent.rating
- (number, optional): Associated rating valueevent.source
- (string, optional): Source of the feedback
Example:
`typescript`
await sdk.sendFeedbackEvent({
text: "Great product! Very satisfied with the quality.",
category: "product-quality",
rating: 5,
source: "feedback-form",
});
Bug Reported
##### sendBugReportEvent(event: BugReportEvent): Promise
Sends a bug reported event.
Parameters:
- event.description (string, required): Bug descriptionevent.severity
- (string, optional): Bug severity level (e.g., "low", "medium", "high", "critical")event.stepsToReproduce
- (string, optional): Steps to reproduce the bugevent.component
- (string, optional): Affected component or area
Example:
`typescript`
await sdk.sendBugReportEvent({
description: "Button not responding on mobile devices",
severity: "high",
stepsToReproduce:
"1. Open app on mobile 2. Click submit button 3. Nothing happens",
component: "checkout-form",
});
Survey Started / Completed
##### sendSurveyEvent(event: SurveyEvent): Promise
Sends a survey started or completed event.
Parameters:
- event.surveyId (string, required): Unique survey identifierevent.status
- ("started" | "completed", required): Survey statusevent.questionCount
- (number, optional): Number of questions in the surveyevent.duration
- (number, optional): Duration in milliseconds
Example:
`typescript
// Survey started
await sdk.sendSurveyEvent({
surveyId: "survey-123",
status: "started",
questionCount: 10,
});
// Survey completed
await sdk.sendSurveyEvent({
surveyId: "survey-123",
status: "completed",
questionCount: 10,
duration: 120000, // 2 minutes in milliseconds
});
`
User Complaint Received
##### sendComplaintEvent(event: ComplaintEvent): Promise
Sends a user complaint received event.
Parameters:
- event.text (string, required): Complaint textevent.category
- (string, optional): Complaint categoryevent.priority
- (string, optional): Priority level (e.g., "low", "medium", "high", "urgent")event.status
- (string, optional): Complaint status (e.g., "new", "in-progress", "resolved")
Example:
`typescript`
await sdk.sendComplaintEvent({
text: "Unable to access my account after password reset",
category: "account-access",
priority: "high",
status: "new",
});
#### Workflow & Business Process Events
Perfect for automation and internal tools.
##### sendWorkflowStartedEvent(event: WorkflowStartedEvent): Promise
Sends a workflow started event.
Parameters:
- event.workflowId (string, required): Unique workflow identifierevent.workflowName
- (string, optional): Name of the workflowevent.workflowType
- (string, optional): Type or category of the workflowevent.initiatorId
- (string, optional): ID of the user or system that initiated the workflow
Example:
`typescript`
await sdk.sendWorkflowStartedEvent({
workflowId: "workflow-123",
workflowName: "Order Processing",
workflowType: "e-commerce",
initiatorId: "user-456",
});
##### sendWorkflowStepCompletedEvent(event: WorkflowStepCompletedEvent): Promise
Sends a workflow step completed event.
Parameters:
- event.workflowId (string, required): Unique workflow identifierevent.stepId
- (string, required): Unique step identifierevent.stepName
- (string, optional): Name of the completed stepevent.duration
- (number, optional): Duration of the step in millisecondsevent.status
- (string, optional): Status of the step completion
Example:
`typescript`
await sdk.sendWorkflowStepCompletedEvent({
workflowId: "workflow-123",
stepId: "step-456",
stepName: "Payment Processing",
duration: 2500,
status: "success",
});
##### sendWorkflowErrorEvent(event: WorkflowErrorEvent): Promise
Sends a workflow error event.
Parameters:
- event.workflowId (string, required): Unique workflow identifierevent.stepId
- (string, optional): Step identifier where the error occurredevent.errorType
- (string, optional): Type or category of the errorevent.errorMessage
- (string, optional): Detailed error messageevent.errorCode
- (string, optional): Error code or identifierevent.severity
- (string, optional): Error severity level (e.g., "low", "medium", "high", "critical")
Example:
`typescript`
await sdk.sendWorkflowErrorEvent({
workflowId: "workflow-123",
stepId: "step-456",
errorType: "validation_error",
errorMessage: "Invalid payment method",
errorCode: "PAYMENT_001",
severity: "high",
});
##### sendWorkflowAbortedEvent(event: WorkflowAbortedEvent): Promise
Sends a workflow aborted event.
Parameters:
- event.workflowId (string, required): Unique workflow identifierevent.reason
- (string, optional): Reason for aborting the workflowevent.abortedBy
- (string, optional): ID of the user or system that aborted the workflow
Example:
`typescript`
await sdk.sendWorkflowAbortedEvent({
workflowId: "workflow-123",
reason: "User cancelled operation",
abortedBy: "user-456",
});
##### sendDocumentCreatedEvent(event: DocumentCreatedEvent): Promise
Sends a document created event.
Parameters:
- event.documentId (string, required): Unique document identifierevent.documentType
- (string, optional): Type of document (e.g., "invoice", "contract", "report")event.documentName
- (string, optional): Name of the documentevent.creatorId
- (string, optional): ID of the user who created the documentevent.templateId
- (string, optional): Template identifier if document was created from a template
Example:
`typescript`
await sdk.sendDocumentCreatedEvent({
documentId: "doc-123",
documentType: "invoice",
documentName: "Invoice #2024-001",
creatorId: "user-456",
templateId: "template-invoice-v2",
});
##### sendDocumentApprovedEvent(event: DocumentApprovedEvent): Promise
Sends a document approved event.
Parameters:
- event.documentId (string, required): Unique document identifierevent.approverId
- (string, optional): ID of the user who approved the documentevent.reason
- (string, optional): Reason for approvalevent.comment
- (string, optional): Additional comments
Example:
`typescript`
await sdk.sendDocumentApprovedEvent({
documentId: "doc-123",
approverId: "user-789",
reason: "All requirements met",
comment: "Approved for production",
});
##### sendDocumentRejectedEvent(event: DocumentRejectedEvent): Promise
Sends a document rejected event.
Parameters:
- event.documentId (string, required): Unique document identifierevent.approverId
- (string, optional): ID of the user who rejected the documentevent.reason
- (string, optional): Reason for rejectionevent.comment
- (string, optional): Additional comments or feedback
Example:
`typescript`
await sdk.sendDocumentRejectedEvent({
documentId: "doc-123",
approverId: "user-789",
reason: "Missing required information",
comment: "Please add customer signature before resubmission",
});
##### sendTaskAssignedEvent(event: TaskAssignedEvent): Promise
Sends a task assigned event.
Parameters:
- event.taskId (string, required): Unique task identifierevent.taskName
- (string, optional): Name of the taskevent.assigneeId
- (string, optional): ID of the user assigned to the taskevent.assignerId
- (string, optional): ID of the user who assigned the taskevent.priority
- (number, optional): Task priority level (higher numbers indicate higher priority)event.dueDate
- (number, optional): Due date timestamp in milliseconds
Example:
`typescript`
await sdk.sendTaskAssignedEvent({
taskId: "task-123",
taskName: "Review quarterly report",
assigneeId: "user-456",
assignerId: "user-789",
priority: 5,
dueDate: Date.now() + 7 24 60 60 1000, // 7 days from now
});
##### sendTaskCompletedEvent(event: TaskCompletedEvent): Promise
Sends a task completed event.
Parameters:
- event.taskId (string, required): Unique task identifierevent.completedBy
- (string, optional): ID of the user who completed the taskevent.duration
- (number, optional): Duration to complete the task in millisecondsevent.status
- (string, optional): Completion status (e.g., "completed", "cancelled", "failed")event.outcome
- (string, optional): Outcome or result of the task
Example:
`typescript`
await sdk.sendTaskCompletedEvent({
taskId: "task-123",
completedBy: "user-456",
duration: 3600000, // 1 hour in milliseconds
status: "completed",
outcome: "All items reviewed and approved",
});
#### E-Commerce Events
Track shopping behavior and order lifecycles.
Product Viewed
##### sendProductViewedEvent(event: ProductViewedEvent): Promise
Sends a product viewed event.
Parameters:
- event.productId (string, required): Unique product identifierevent.name
- (string, required): Product nameevent.category
- (string, optional): Product categoryevent.currency
- (string, optional): Currency code (e.g., "USD")event.variant
- (string, optional): Product variantevent.price
- (number, optional): Product price
Example:
`typescript`
await sdk.sendProductViewedEvent({
productId: "prod-123",
name: "Red T-Shirt",
category: "Apparel",
currency: "USD",
price: 29.99,
});
Order Created
##### sendOrderCreatedEvent(event: OrderCreatedEvent): Promise
Sends an order created event.
Parameters:
- event.orderId (string, required): Unique order identifierevent.currency
- (string, optional): Currency codeevent.couponCode
- (string, optional): Applied coupon codeevent.totalValue
- (number, optional): Total order valueevent.itemCount
- (number, optional): Total number of items
Example:
`typescript`
await sdk.sendOrderCreatedEvent({
orderId: "order-123",
currency: "USD",
totalValue: 150.00,
itemCount: 3,
});
Checkout Started
##### sendCheckoutStartedEvent(event: CheckoutStartedEvent): Promise
Sends a checkout started event.
Parameters:
- event.orderId (string, required): Unique order identifierevent.currency
- (string, optional): Currency codeevent.totalValue
- (number, optional): Total value at start of checkoutevent.itemCount
- (number, optional): Number of items in cart
Example:
`typescript`
await sdk.sendCheckoutStartedEvent({
orderId: "order-123",
currency: "USD",
totalValue: 99.99,
itemCount: 2,
});
#### Custom Events
##### sendCustomEvent(event: Event): Promise
Sends a custom event with full control over the event structure.
Parameters:
- event (Event, required): Custom event object conforming to the Event interface
Example:
`typescript`
await sdk.sendCustomEvent({
id: "custom-event-123",
tenantId: "tenant-123",
sessionId: "session-123",
timestamp: Date.now(),
eventType: "custom",
properties: {
string1: "custom-value",
num1: 42,
bool1: true,
},
});
---
The SDK supports the following event types:
| Event Type | Constant | Description |
| ----------------------- | ------------------------- | -------------------------------------- |
| Rating | RATING | User rating events |CUSTOM
| Custom | | Custom events with flexible properties |FEEDBACK_SUBMITTED
| Feedback Submitted | | User feedback submission |BUG_REPORTED
| Bug Reported | | Bug report events |SURVEY
| Survey | | Survey started/completed events |COMPLAINT_RECEIVED
| Complaint Received | | User complaint events |WORKFLOW_STARTED
| Workflow Started | | Workflow initiation events |WORKFLOW_STEP_COMPLETED
| Workflow Step Completed | | Workflow step completion events |WORKFLOW_ERROR
| Workflow Error | | Workflow error events |WORKFLOW_ABORTED
| Workflow Aborted | | Workflow abortion events |DOCUMENT_CREATED
| Document Created | | Document creation events |DOCUMENT_APPROVED
| Document Approved | | Document approval events |DOCUMENT_REJECTED
| Document Rejected | | Document rejection events |TASK_ASSIGNED
| Task Assigned | | Task assignment events |TASK_COMPLETED
| Task Completed | | Task completion events |PRODUCT_VIEWED
| Product Viewed | | Product view events |CATEGORY_VIEWED
| Category Viewed | | Category view events |PRODUCT_ADDED_TO_CART
| Product Added to Cart | | Add to cart events |PRODUCT_REMOVED_FROM_CART
| Product Removed | | Remove from cart events |CART_CLEARED
| Cart Cleared | | Cart cleared events |CART_VIEWED
| Cart Viewed | | Cart view events |SEARCH_PERFORMED
| Search Performed | | Search events |SEARCH_CLEARED
| Search Cleared | | Search cleared events |FILTER_APPLIED_REMOVED
| Filter Applied/Removed | | Filter interaction events |CHECKOUT_STARTED
| Checkout Started | | Checkout initiation events |CHECKOUT_ABANDONED
| Checkout Abandoned | | Checkout abandonment events |PAYMENT_ATTEMPTED
| Payment Attempted | | Payment attempt events |PAYMENT_FAILED
| Payment Failed | | Payment failure events |PAYMENT_SUCCESS
| Payment Success | | Payment success events |ORDER_CREATED
| Order Created | | Order creation events |ORDER_CONFIRMED
| Order Confirmed | | Order confirmation events |ORDER_PACKED
| Order Packed | | Order packed events |ORDER_SHIPPED
| Order Shipped | | Order shipment events |ORDER_DELIVERED
| Order Delivered | | Order delivery events |ORDER_CANCELLED
| Order Cancelled | | Order cancellation events |ORDER_REFUNDED
| Order Refunded | | Order refund events |ORDER_ITEM_ADDED
| Order Item Added | | Order item addition events |ORDER_ITEM_UPDATED
| Order Item Updated | | Order item update events |ORDER_ITEM_REMOVED
| Order Item Removed | | Order item removal events |ITEM_DELIVERED
| Item Delivered | | Item delivery events |ITEM_DELIVERY_FAILED
| Item Delivery Failed | | Item delivery failure events |DEVICE_ONLINE
| Device Online | | Device online events |DEVICE_OFFLINE
| Device Offline | | Device offline events |DEVICE_REBOOTED
| Device Rebooted | | Device reboot events |FIRMWARE_UPDATED
| Firmware Updated | | Firmware update events |TEMPERATURE_READING
| Temperature Reading | | Temperature sensor reading events |HUMIDITY_READING
| Humidity Reading | | Humidity sensor reading events |VOLTAGE_POWER_LEVEL
| Voltage / Power Level | | Voltage/power level events |MOTION_DETECTED
| Motion Detected | | Motion detection events |GPS_UPDATE
| GPS Update | | GPS location update events |SCREEN_MEDIA_UPDATE
| Screen Media Update | | Screen media update events |QUEUE_UPDATED
| Queue Updated | | Queue update events |FAULT_DETECTED
| Fault Detected | | Device fault detection events |BATTERY_LOW
| Battery Low | | Low battery warning events |OVERHEATING
| Overheating | | Overheating warning events |UNAUTHORIZED_ACCESS
| Unauthorized Access | | Unauthorized access attempt events |COMMAND_SENT
| Command Sent | | Device command sent events |COMMAND_ACKNOWLEDGED
| Command Acknowledged | | Device command acknowledgment events |COMMAND_FAILED
| Command Failed | | Device command failure events |
---
`typescript`
interface ClientInput {
clientType: "browser" | "server";
ip?: string;
region?: string;
city?: string;
timezone?: string;
os?: string;
osVersion?: string;
browser?: string;
browserVersion?: string;
screenResolution?: string;
utmSource?: string;
utmMedium?: string;
utmCampaign?: string;
}
`typescript`
interface SessionInput {
userId?: string;
country?: string;
deviceType?: string;
referrer?: string;
}
`typescript`
interface RatingEvent {
min: number;
max: number;
source?: string;
raterId?: string;
}
`typescript`
interface FeedbackEvent {
text: string;
category?: string;
rating?: number;
source?: string;
}
`typescript`
interface BugReportEvent {
description: string;
severity?: string;
stepsToReproduce?: string;
component?: string;
}
`typescript`
interface SurveyEvent {
surveyId: string;
status: "started" | "completed";
questionCount?: number;
duration?: number;
}
`typescript`
interface ComplaintEvent {
text: string;
category?: string;
priority?: string;
status?: string;
}
`typescript`
interface WorkflowStartedEvent {
workflowId: string;
workflowName?: string;
workflowType?: string;
initiatorId?: string;
}
`typescript`
interface WorkflowStepCompletedEvent {
workflowId: string;
stepId: string;
stepName?: string;
duration?: number;
status?: string;
}
`typescript`
interface WorkflowErrorEvent {
workflowId: string;
stepId?: string;
errorType?: string;
errorMessage?: string;
errorCode?: string;
severity?: string;
}
`typescript`
interface WorkflowAbortedEvent {
workflowId: string;
reason?: string;
abortedBy?: string;
}
`typescript`
interface DocumentCreatedEvent {
documentId: string;
documentType?: string;
documentName?: string;
creatorId?: string;
templateId?: string;
}
`typescript`
interface DocumentApprovedEvent {
documentId: string;
approverId?: string;
reason?: string;
comment?: string;
}
`typescript`
interface DocumentRejectedEvent {
documentId: string;
approverId?: string;
reason?: string;
comment?: string;
}
`typescript`
interface TaskAssignedEvent {
taskId: string;
taskName?: string;
assigneeId?: string;
assignerId?: string;
priority?: number;
dueDate?: number;
}
`typescript`
interface TaskCompletedEvent {
taskId: string;
completedBy?: string;
duration?: number;
status?: string;
outcome?: string;
}
`typescript`
interface ProductViewedEvent {
productId: string;
name: string;
category?: string;
currency?: string;
variant?: string;
price?: number;
}
`typescript`
interface OrderCreatedEvent {
orderId: string;
currency?: string;
couponCode?: string;
totalValue?: number;
itemCount?: number;
}
`typescript`
interface CheckoutStartedEvent {
orderId: string;
currency?: string;
totalValue?: number;
itemCount?: number;
}
`typescript`
interface DeviceOnlineEvent {
deviceId: string;
deviceType?: string;
location?: string;
firmwareVersion?: string;
}
`typescript`
interface DeviceOfflineEvent {
deviceId: string;
reason?: string;
lastSeen?: number;
}
`typescript`
interface DeviceRebootedEvent {
deviceId: string;
reason?: string;
uptimeBeforeReboot?: number;
}
`typescript`
interface FirmwareUpdatedEvent {
deviceId: string;
oldVersion?: string;
newVersion: string;
}
`typescript`
interface TemperatureReadingEvent {
deviceId: string;
sensorId?: string;
temperature: number;
unit?: string;
location?: string;
}
`typescript`
interface HumidityReadingEvent {
deviceId: string;
sensorId?: string;
humidity: number;
unit?: string;
location?: string;
}
`typescript`
interface VoltagePowerLevelEvent {
deviceId: string;
voltage?: number;
powerLevel?: number;
batteryLevel?: number;
}
`typescript`
interface MotionDetectedEvent {
deviceId: string;
sensorId?: string;
location?: string;
motionType?: string;
}
`typescript`
interface GpsUpdateEvent {
deviceId: string;
latitude: number;
longitude: number;
altitude?: number;
accuracy?: number;
}
`typescript`
interface ScreenMediaUpdateEvent {
deviceId: string;
mediaType?: string;
mediaId?: string;
duration?: number;
}
`typescript`
interface QueueUpdatedEvent {
deviceId: string;
queueId?: string;
queueLength: number;
action?: string;
}
`typescript`
interface FaultDetectedEvent {
deviceId: string;
faultType?: string;
faultCode?: string;
severity?: string;
description?: string;
}
`typescript`
interface BatteryLowEvent {
deviceId: string;
batteryLevel: number;
threshold?: number;
}
`typescript`
interface OverheatingEvent {
deviceId: string;
temperature: number;
threshold?: number;
}
`typescript`
interface UnauthorizedAccessEvent {
deviceId: string;
accessType?: string;
source?: string;
attemptCount?: number;
}
`typescript`
interface CommandSentEvent {
deviceId: string;
commandType: string;
commandId?: string;
parameters?: string;
}
`typescript`
interface CommandAcknowledgedEvent {
deviceId: string;
commandId: string;
timestamp?: number;
}
`typescript`
interface CommandFailedEvent {
deviceId: string;
commandId: string;
errorCode?: string;
errorMessage?: string;
}
---
`typescript
import { DataStudioSDK } from "data-studio-sdk";
async function trackUserJourney() {
// Initialize SDK
const sdk = new DataStudioSDK({
apiKey: "your-tenant-id@your-api-key",
});
try {
// Client is automatically created on initialization
// Start a session
await sdk.startSession({
userId: "user-123",
country: "US",
});
// Track various events
await sdk.sendRatingEvent({
rating: 1,
max: 5,
raterId: "user-123",
});
await sdk.sendFeedbackEvent({
text: "Love the new design!",
category: "ui-feedback",
rating: 5,
});
await sdk.sendSurveyEvent({
surveyId: "satisfaction-survey-2024",
status: "started",
questionCount: 5,
});
// ... user completes survey ...
await sdk.sendSurveyEvent({
surveyId: "satisfaction-survey-2024",
status: "completed",
questionCount: 5,
duration: 45000, // 45 seconds
});
// End session
await sdk.endSession();
// Close client
await sdk.closeClient();
} catch (error) {
console.error("Error tracking events:", error);
}
}
`
`typescript
// In your React/Vue/Angular component
import { DataStudioSDK } from "data-studio-sdk";
// Initialize once (e.g., in app initialization)
const sdk = new DataStudioSDK({
apiKey: process.env.REACT_APP_DATA_STUDIO_API_KEY!,
});
// Start session when user lands on page
useEffect(() => {
sdk.startSession({
userId: currentUser?.id,
referrer: document.referrer,
});
return () => {
// End session on component unmount
sdk.endSession();
};
}, []);
// Track events on user interactions
const handleRatingSubmit = async (rating: number) => {
await sdk.sendRatingEvent({
rating: 1,
max: 5,
raterId: currentUser?.id,
});
};
const handleFeedbackSubmit = async (feedback: string) => {
await sdk.sendFeedbackEvent({
text: feedback,
category: "general",
source: "contact-form",
});
};
`
`typescript
import { DataStudioSDK } from "data-studio-sdk";
// Initialize with server-specific configuration
const sdk = new DataStudioSDK({
apiKey: process.env.DATA_STUDIO_API_KEY!,
});
// Create client with server info
await sdk.createClient({
clientType: "server",
ip: req.ip,
region: "us-east-1",
city: "New York",
timezone: "America/New_York",
});
// Start session
await sdk.startSession({
userId: req.user.id,
country: req.headers["cf-ipcountry"] as string,
});
// Track server-side events
await sdk.sendBugReportEvent({
description: "API endpoint returning 500 error",
severity: "critical",
component: "payment-api",
});
`
---
1. Initialize Once: Create a single SDK instance and reuse it throughout your application lifecycle.
2. Session Management:
- Start a session when a user begins their journey
- End the session when they leave or after a period of inactivity
- Don't create multiple concurrent sessions
3. Error Handling: Always wrap SDK calls in try-catch blocks to handle potential errors gracefully.
4. Async/Await: All SDK methods are asynchronous. Always use await or handle promises appropriately.
5. Event Context: The SDK automatically adds context (sessionId, clientId, tenantId, timestamp) to all events. You don't need to provide this manually.
6. Browser vs Server:
- In browser environments, the SDK auto-detects device and browser information
- In server environments, provide client information manually via createClient()
7. Cleanup: Always call endSession() and closeClient()` when appropriate to ensure data is properly synced.
---