UNPKG

prodiax-tracking-sdk

Version:

Production-ready event tracking SDK for product analytics and user behavior insights

466 lines (375 loc) โ€ข 13.2 kB
# Prodiax Tracking SDK v2.0.1 A production-ready event tracking SDK for comprehensive product analytics and user behavior insights. Built to help product managers understand user drop-offs by identifying problems, root causes, and solutions through AI-powered analysis. ## ๐ŸŽฏ What is Prodiax? Prodiax is an AI-powered product analytics platform that helps you understand user pain points by analyzing behavioral signals and event logs. This SDK captures all meaningful user interactions and sends them to the Prodiax platform for AI-powered analysis. **Key Benefits:** - ๐Ÿ” **Identify UX Issues**: Automatically detect rage clicks, form abandonment, and user frustration - ๐Ÿค– **AI-Powered Insights**: Get instant, actionable insights about user problems - ๐Ÿ“Š **Comprehensive Tracking**: Track clicks, scrolls, forms, errors, and performance - ๐Ÿ›ก๏ธ **Privacy Compliant**: GDPR-ready with Do Not Track support - โšก **Production Ready**: Offline support, retry logic, and minimal performance impact ## ๐Ÿš€ Features ### Core Tracking - **Automatic Event Tracking**: Clicks, hovers, scrolls, form interactions - **Session Management**: Cross-page persistence with intelligent session handling - **Performance Monitoring**: Page load times, API response times, interaction delays - **Error Tracking**: JavaScript errors, unhandled rejections, network failures ### Advanced Analytics - **Rage Click Detection**: Identifies user frustration patterns - **Exit Intent Tracking**: Captures when users are about to leave - **Form Analytics**: Tracks form completion rates, field interactions, abandonment - **Scroll Depth Analysis**: Monitors content engagement and reading patterns - **User Journey Mapping**: Comprehensive user flow tracking ### Production Ready - **Offline Support**: Queues events when offline, retries when connection restored - **Privacy Compliant**: GDPR-ready with Do Not Track support and PII masking - **Performance Optimized**: Throttled events, efficient batching, minimal overhead - **Reliable Delivery**: Multiple fallback mechanisms, retry logic, error handling ## ๐Ÿ“ฆ Installation ### Option 1: CDN (Recommended for HTML) ```html <script src="https://unpkg.com/prodiax-tracking-sdk@latest/dist/prodiax-sdk.min.js"></script> ``` ### Option 2: NPM ```bash npm install prodiax-tracking-sdk ``` ### Option 3: jsDelivr CDN ```html <script src="https://unpkg.com/prodiax-tracking-sdk@latest/dist/prodiax-sdk.min.js"></script> ``` ## ๐Ÿš€ Quick Start ### Basic Setup (CDN) ```html <!DOCTYPE html> <html> <head> <title>My App</title> </head> <body> <!-- Your content --> <!-- Add SDK before closing body tag --> <script src="https://unpkg.com/prodiax-tracking-sdk@latest/dist/prodiax-sdk.min.js"></script> <script> window.Prodiax.init({ productId: 'your-product-id' }); </script> </body> </html> ``` ### Basic Setup (NPM) ```javascript import Prodiax from 'prodiax-tracking-sdk'; Prodiax.init({ productId: 'your-product-id' }); ``` ### Advanced Configuration ```javascript Prodiax.init({ productId: 'your-product-id', // Get this from your Prodiax dashboard // Batching & Performance batchSize: 20, // Events per batch batchIntervalMs: 3000, // Send every 3 seconds // Privacy & Compliance respectDoNotTrack: true, // Respect DNT headers anonymizeIp: true, // Anonymize IP addresses maskPii: true, // Mask personally identifiable information // Tracking Features enableScrollTracking: true, // Track scroll depth enableHoverTracking: true, // Track hover interactions enableFormTracking: true, // Track form interactions enableErrorTracking: true, // Track JavaScript errors enableRageClickDetection: true, // Detect user frustration // Debug Mode debugMode: false // Set to true for development }); ``` ## ๐Ÿ“Š API Reference ### Core Methods #### `Prodiax.init(config)` Initializes the tracking SDK with configuration options. **Parameters:** - `config` (Object): Configuration object - `productId` (String, required): Your unique product identifier - `apiEndpoint` (String): API endpoint for sending events - `environment` (String): 'development', 'staging', or 'production' - `debugMode` (Boolean): Enable debug logging #### `Prodiax.track(eventName, properties, options)` Tracks a custom event with properties. ```javascript Prodiax.track('purchase_completed', { product_id: '123', amount: 99.99, currency: 'USD' }); ``` #### `Prodiax.identify(userId, traits)` Identifies a user with traits for better analytics. ```javascript Prodiax.identify('user-123', { email: 'user@example.com', plan: 'premium', signup_date: '2024-01-01' }); ``` #### `Prodiax.setUserProperties(properties)` Updates user properties. ```javascript Prodiax.setUserProperties({ last_login: new Date().toISOString(), preferences: { theme: 'dark' } }); ``` ### Advanced Methods #### `Prodiax.trackError(error, context)` Manually track errors with context. ```javascript try { // Your code } catch (error) { Prodiax.trackError(error, { component: 'checkout-form', user_action: 'submit_payment' }); } ``` #### `Prodiax.trackPerformance(metric, value, context)` Track custom performance metrics. ```javascript Prodiax.trackPerformance('api_response_time', 150, { endpoint: '/api/users', method: 'GET' }); ``` ### Debug Methods #### `Prodiax.getQueue()` Returns the current event queue (debug only). #### `Prodiax.getSession()` Returns current session information (debug only). #### `Prodiax.flush()` Forces immediate sending of queued events. #### `Prodiax.reset()` Resets the SDK state (debug only). ## ๐ŸŽฏ Event Types ### Automatic Events | Event Type | Description | Data Included | |------------|-------------|---------------| | `page_view` | Page load/visit | URL, title, referrer, performance metrics | | `click` | User clicks | Element selector, context, position, modifiers | | `rage_click` | Multiple rapid clicks | Click count, element, time window | | `hover_interaction` | Extended hover | Duration, element selector | | `scroll_depth_reached` | Scroll milestones | Depth percentage, direction, total distance | | `form_interaction` | Form field interactions | Field name, form progress, event type | | `form_submit` | Form submissions | Form duration, fields interacted | | `error` | JavaScript errors | Error message, stack trace, context | | `exit_intent` | User leaving page | Time on page, mouse leave count | | `session_start` | New session | Session ID, timestamp | | `session_end` | Session ended | Duration, total events | ### Custom Events Track any custom event with rich metadata: ```javascript Prodiax.track('feature_used', { feature_name: 'advanced_search', search_terms: ['analytics', 'dashboard'], result_count: 25 }); ``` ## โš™๏ธ Configuration Options ### Core Settings ```javascript { productId: 'your-product-id', // Required apiEndpoint: 'https://api.prodiax.com/track', environment: 'production', // 'development', 'staging', 'production' } ``` ### Performance & Batching ```javascript { batchSize: 20, // Events per batch batchIntervalMs: 3000, // Max wait time for batch maxRetries: 3, // Retry attempts for failed requests retryDelayMs: 1000, // Delay between retries } ``` ### Session Management ```javascript { sessionTimeoutMs: 30 * 60 * 1000, // 30 minutes maxSessionDurationMs: 24 * 60 * 60 * 1000, // 24 hours } ``` ### Privacy & Compliance ```javascript { respectDoNotTrack: true, // Respect DNT header anonymizeIp: true, // Anonymize IP addresses maskPii: true, // Mask personally identifiable info enableCookies: true, // Enable cookie storage } ``` ### Tracking Features ```javascript { enableScrollTracking: true, // Track scroll behavior enableHoverTracking: true, // Track hover interactions enableFormTracking: true, // Track form interactions enableErrorTracking: true, // Track JavaScript errors enableRageClickDetection: true, // Detect user frustration enableExitIntentTracking: true, // Track exit intent enablePerformanceTracking: true, // Track performance metrics } ``` ### Thresholds & Selectors ```javascript { scrollThrottleMs: 200, // Scroll event throttling scrollDepthThresholds: [25, 50, 75, 90], // Scroll depth milestones hoverThresholdMs: 500, // Minimum hover duration rageClickThreshold: { // Rage click detection clicks: 3, timeMs: 2000 }, hoverSelectors: [ // Elements to track hovers 'button', 'a', '[role="button"]' ], ignoreAttribute: 'data-prodiax-ignore', // Attribute to ignore elements } ``` ## ๐Ÿ”’ Privacy & Compliance ### GDPR Compliance The SDK is designed with privacy in mind: - **Do Not Track Support**: Respects browser DNT settings - **PII Masking**: Automatically masks emails, phones, credit cards - **Cookie Consent**: Works with cookie consent management - **Data Minimization**: Only collects necessary data - **Text Input Protection**: Never tracks any user text input, passwords, or form values ### Text Input Protection The SDK automatically excludes tracking for: - **All Input Elements**: `input`, `textarea`, `select` (any type) - **Contenteditable Elements**: Any element with `contenteditable="true"` - **Simple & Reliable**: No complex detection - just excludes all text input fields ### Data Collection The SDK collects: - User interactions (clicks, scrolls, hovers) - Page views and navigation - Form interactions and submissions - Error information - Performance metrics - Device and browser information ### Data NOT Collected - Personal information (unless explicitly provided) - Form field values (only interaction patterns) - Keystrokes or typing patterns - Screenshots or visual data ## ๐Ÿ› ๏ธ Integration Examples ### React Application ```javascript // App.js import { useEffect } from 'react'; function App() { useEffect(() => { Prodiax.init({ productId: 'your-product-id', environment: process.env.NODE_ENV }); }, []); return <YourApp />; } ``` ### Vue.js Application ```javascript // main.js import { createApp } from 'vue'; import App from './App.vue'; const app = createApp(App); // Initialize tracking Prodiax.init({ productId: 'your-product-id' }); app.mount('#app'); ``` ### Angular Application ```javascript // app.component.ts import { Component, OnInit } from '@angular/core'; declare const Prodiax: any; @Component({ selector: 'app-root', template: '<router-outlet></router-outlet>' }) export class AppComponent implements OnInit { ngOnInit() { Prodiax.init({ productId: 'your-product-id' }); } } ``` ### WordPress Plugin ```php // Add to your theme's functions.php or plugin function add_prodiax_tracking() { ?> <script> window.prodiaxSettings = { config: { productId: '<?php echo esc_js(get_option('prodiax_product_id')); ?>', environment: '<?php echo esc_js(wp_get_environment_type()); ?>' } }; </script> <script src="https://cdn.prodiax.com/sdk/v2/prodiax-sdk.min.js"></script> <?php } add_action('wp_head', 'add_prodiax_tracking'); ``` ## ๐Ÿงช Testing ### Unit Tests ```bash npm test ``` ### Integration Tests ```bash npm run test:integration ``` ### Manual Testing Enable debug mode to see events in console: ```javascript Prodiax.init({ productId: 'test-product', debugMode: true, verboseLogging: true }); ``` ## ๐Ÿ“ˆ Analytics Dashboard Track events are automatically sent to your Prodiax dashboard where you can: - View user journeys and drop-off points - Analyze form completion rates - Identify rage click patterns - Monitor performance issues - Generate AI-powered insights ## ๐Ÿค Contributing 1. Fork the repository 2. Create a feature branch (`git checkout -b feature/amazing-feature`) 3. Commit your changes (`git commit -m 'Add amazing feature'`) 4. Push to the branch (`git push origin feature/amazing-feature`) 5. Open a Pull Request ## ๐Ÿ“„ License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. ## ๐Ÿ†˜ Support - **Documentation**: [docs.prodiax.com](https://docs.prodiax.com) - **Issues**: [GitHub Issues](https://github.com/prodiax/tracking-sdk/issues) - **Email**: support@prodiax.com - **Discord**: [Join our community](https://discord.gg/prodiax) ## ๐Ÿ”„ Changelog ### v2.0.0 - Complete rewrite for production readiness - Enhanced error handling and offline support - Advanced form and performance tracking - Privacy compliance improvements - Comprehensive API documentation ### v1.0.0 - Initial release with basic tracking capabilities