Documentation
Introduction
Datataki is a powerful JavaScript/TypeScript library for comprehensive user behavior tracking and analytics. It automatically collects user interaction data on web applications, providing insights into sessions, page views, clicks, scroll behavior, and custom events.
Getting Started
Installation
npm install @datataki/sdk
Basic Setup
Basic setup is straightforward:
import { startTracking } from '@datataki/sdk';
startTracking('https://your-analytics-api.com/events');
The library immediately starts tracking page views, scroll behavior, session start/end, and basic clicks. For more control, you can configure additional options:
import { startTracking } from '@datataki/sdk';
startTracking('https://your-analytics-api.com/events', {
debug: true, // Enable console logs for debugging
realTime: false, // Send events immediately or batch them
sessionTimeout: 30000, // Session timeout in milliseconds
excludeRoutes: [/^\/admin/, '/login'], // Routes to exclude from tracking
samplingRate: 0.5, // Track only a percentage of users
globalMetadata: {
appVersion: '1.0.1',
environment: 'production',
},
});
Core Features
1. Session Management
- Automatic session tracking with start and end events
- Session timeout handling
- User inactivity detection
- Unique session and user identification
2. Event Tracking
- Page Views: Automatic tracking of page navigation
- Custom Events: Flexible custom event tracking with metadata support
- Scroll Tracking:
- Scroll depth percentage
- Scroll direction (up/down)
- Debounced scroll events
- Click Tracking:
- Element identification
- Click coordinates
- Custom data attributes support
- Debounced click events
3. UTM Parameter Tracking
- Automatic capture of UTM parameters:
- Campaign
- Source
- Medium
- Term
- Content
4. Device Detection
- Automatic device type detection
- Support for desktop, tablet, and mobile devices
5. Advanced Features
- Event queue management
- Real-time event sending option
- Debug mode for development
- Configurable session timeout
- Automatic handling of page visibility changes
- History state change tracking
Event Types
- SESSION_START
- SESSION_END
- PAGE_VIEW
- SCROLL
- CLICK
- CUSTOM
Configuration Options
interface DatatakiConfig {
debug?: boolean; // Enable debug mode
realTime?: boolean; // Send events in real-time
sessionTimeout?: number; // Custom session timeout
samplingRate?: number; // Allow to track only a percentage of users (default 100%)
excludeRoutes?: Array<string | RegExp>; // List of routes (exact string or RegExp) on which we do NOT want to trace
}
excludeRoutes
only will ignore scroll events and click events without data-taki-* attribute.
Event Tracking Implementation
Custom Events
Track custom events with meaningful names and structured data:
import { sendCustomEvent } from '@datataki/sdk';
sendCustomEvent('button_click', {
buttonId: 'submit-button',
action: 'form_submit',
});
Metadata Restrictions
- Event name: max 120 characters
- Metadata object: max 10KB
- Max 12 metadata keys
- Arrays: max 12 items
- Valid types: string, number, boolean, string[]
Click Tracking
Add data attributes to elements you want to track:
<button data-taki-name="submit_button" data-taki-value="contact_form">Submit</button>
Technical Implementation
Core Components
- Tracking Class: Main class handling all tracking functionality
- Event Queue System: Efficient event batching and sending
- Debounced Event Handlers: Optimized performance for scroll and click events
- Session Management: Comprehensive session lifecycle handling
Detailed Implementation
1. Event Queue System
The library implements a sophisticated event queue system that:
- Batches events to optimize network requests
- Automatically sends queued events at configurable intervals
- Handles offline scenarios by storing events in memory
- Implements a debounce mechanism for high-frequency events (clicks, scrolls)
- Default queue interval: 5 seconds (configurable)
2. Session Management
The session handling system:
- Generates unique session IDs using UUID v4
- Tracks session start and end events
- Implements user inactivity detection:
- Monitors mouse movement, keyboard, scroll, and click events
- Configurable inactivity timeout (default: 30 minutes)
- Automatically ends sessions on page unload
- Handles page visibility changes:
- Pauses tracking when page is hidden
- Resumes tracking when page becomes visible
- Automatically sends queued events before page unload
3. Event Tracking Implementation
Page View Tracking
- Automatically tracks initial page load
- Monitors history API changes (pushState, replaceState)
- Tracks popstate events for browser navigation
- Captures referrer information
- Records page URL and timestamp
Scroll Tracking
- Implements debounced scroll event handling
- Calculates scroll depth as percentage (0-100)
- Tracks scroll direction (up/down)
- Default debounce time: 100ms
- Optimized for performance with passive event listeners
Click Tracking
- Debounced click event handling (default: 300ms)
- Supports nested element tracking
- Implements event delegation for efficiency
- Captures:
- Element information (tag, id, class)
- Click coordinates (x, y)
- Custom data attributes
Custom Events
- Type-safe event validation
- Debug mode validation
- Error handling for invalid events
- Supports metadata with various types:
- String
- Number
- Boolean
- Array of strings
4. Data Collection
UTM Parameters
- Automatic extraction from URL
- Stores parameters for entire session
- Supports all standard UTM parameters:
- utm_campaign
- utm_source
- utm_medium
- utm_term
- utm_content
Device Detection
- Detects device type using user agent
- Stores device information in session
- Categories:
- Desktop
- Tablet
- Mobile
5. Performance Optimizations
- Debounced event handlers for high-frequency events
- Efficient event queue management
- Memory-optimized data structures
- Automatic cleanup of event listeners
- Lazy initialization of tracking features
- Configurable real-time vs. batched event sending
6. Error Handling
- Comprehensive error catching
- Debug mode for development
- Graceful degradation
- Event validation
- Network error handling
- Queue recovery mechanisms
Privacy & Data Collection
Datataki is designed with privacy in mind:
Anonymous by Design
- No collection of personal identifiable information (PII)
- Random session IDs that cannot be linked to individuals
- No IP address tracking
- No cookies used
Data Collection
All collected data is anonymous:
{
type: EventType;
session_id: string; // randomly generated
page_url: string; // without query params containing PII
timestamp: number;
device: DeviceType;
// Event specific anonymous data
}
Best Practices for Custom Events
When sending custom events, ensure no PII is included:
// Good ✅
sendCustomEvent('button_click', {
buttonId: 'submit-form',
category: 'navigation',
isValid: true,
});
// Bad ❌
sendCustomEvent('form_submit', {
email: 'user@email.com', // No PII!
name: 'John Doe', // No PII!
userId: '12345', // No PII!
});
Browser Support
- Modern browsers (Chrome, Firefox, Safari, Edge)
- Mobile browsers
- IE11+ (with polyfills)
Required Browser Features
- localStorage
- Beacon API
- CustomEvent
- matchMedia