UNPKG

humanbehavior-js

Version:

SDK for HumanBehavior session and event recording

281 lines (207 loc) • 7.44 kB
# HumanBehavior SDK A simplified session recording and analytics SDK that maintains session continuity across page navigations. šŸ“– **[Full Documentation](https://documentation.humanbehavior.co)** - Complete API reference, examples, and integration guides ## Quick Start ### Auto-Installation (Recommended) The easiest way to get started is using our auto-installation wizard: ```bash # One command installation npx humanbehavior-js auto-install YOUR_API_KEY ``` This will automatically: - šŸ” Detect your project's framework - šŸ“¦ Install the humanbehavior-js package - āœļø Modify your codebase to integrate the SDK - šŸ”§ Create environment files with your API key - šŸš€ Make your app ready to track user behavior ### Single Page Application (Manual Setup) For the best session continuity experience, use the SPA approach: ```html <!DOCTYPE html> <html> <head> <script src="dist/index.min.js"></script> </head> <body> <script> // Initialize once - session persists across all navigation const tracker = HumanBehaviorTracker.init('your-api-key', { logLevel: 'warn', // Reduce console noise redactFields: ['password', 'credit_card'], suppressConsoleErrors: true, // Suppress common rrweb errors (default) recordCanvas: false // Enable canvas recording with protection (default: false) }); // Your SPA navigation logic here function navigateToPage(page) { // Update content without page reload loadPageContent(page); // Track navigation tracker.trackNavigationEvent('spa_navigation', currentPage, page); } </script> </body> </html> ``` ### Traditional Multi-Page Setup For traditional HTML pages, the tracker will automatically restore sessions: ```html <!-- index.html --> <script src="dist/index.min.js"></script> <script> const tracker = HumanBehaviorTracker.init('your-api-key'); </script> <!-- about.html --> <script src="dist/index.min.js"></script> <script> const tracker = HumanBehaviorTracker.init('your-api-key'); // Reuses existing session </script> ``` ## API Reference ### Initialization ```javascript // Main initialization method const tracker = HumanBehaviorTracker.init(apiKey, options); ``` **Options:** - `ingestionUrl`: Custom ingestion server URL - `logLevel`: 'none' | 'error' | 'warn' | 'info' | 'debug' - `redactFields`: Array of CSS selectors to redact - `suppressConsoleErrors`: Boolean to suppress common rrweb errors (default: true) - `recordCanvas`: Boolean to enable canvas recording with PostHog-style protection (default: false) ### Session Management ```javascript // Get current session ID const sessionId = tracker.getSessionId(); // Get current URL const currentUrl = tracker.getCurrentUrl(); // Test connection to ingestion server const result = await tracker.testConnection(); ``` ### Event Tracking ```javascript // Track custom events await tracker.customEvent('button_click', { button: 'submit' }); // Track page views await tracker.trackPageView(); // Track navigation (for SPAs) await tracker.trackNavigationEvent('pushState', '/home', '/about'); ``` ### Data Redaction ```javascript // Redact sensitive fields tracker.setRedactedFields(['input[type="password"]', '#email']); // Check if redaction is active const isActive = tracker.isRedactedFields(); ``` ### Debugging ```javascript // View logs tracker.viewLogs(); // Get connection status const status = tracker.getConnectionStatus(); ``` ### Error Suppression The SDK automatically suppresses common rrweb errors for a clean console: ```javascript // Enable error suppression (default) const tracker = HumanBehaviorTracker.init('your-api-key', { suppressConsoleErrors: true // Suppresses canvas security errors, CORS issues, etc. }); // Disable error suppression for debugging const tracker = HumanBehaviorTracker.init('your-api-key', { suppressConsoleErrors: false // Show all errors for debugging }); ``` **Suppressed Errors:** - Canvas security errors (`SecurityError: Failed to execute 'toDataURL'`) - Cross-origin resource errors - CORS policy violations - Ad blocker interference warnings ### Canvas Recording The SDK supports canvas recording with PostHog-style protection against overwhelming events: ```javascript // Enable canvas recording with protection const tracker = HumanBehaviorTracker.init('your-api-key', { recordCanvas: true // Enables canvas recording with 4 FPS throttle and 40% quality }); ``` **Protection Features:** - **4 FPS Throttling**: Prevents canvas overwhelm (vs 60 FPS default) - **40% Quality**: WebP format with compression - **Opt-in Only**: Disabled by default for safety - **Smart Sampling**: Only captures when canvas changes ## Session Continuity The SDK automatically handles session continuity: 1. **Session Restoration**: Automatically restores sessions within 15 minutes 2. **Activity Tracking**: Updates activity timestamp on user interactions 3. **Cross-Page Persistence**: Session persists across page navigations ## Demo Check out `simple-spa.html` for a complete single-page application demo that shows: - True session continuity across navigation - Interactive event tracking - Real-time status updates - Modern UI with smooth transitions ## Troubleshooting ### Ad Blocker Issues If you see `net::ERR_BLOCKED_BY_CLIENT` errors: 1. Check if ad blockers are active 2. Use `tracker.getConnectionStatus()` to diagnose 3. Consider whitelisting your domain ### Session Issues - Sessions automatically expire after 15 minutes of inactivity - Each page load calls `/init` but reuses existing sessions when possible - Check browser console for session restoration logs ## Development ```bash # Build the SDK npm run build # Watch for changes npm run dev # Run tests npm test # Run auto-installation npm run auto-install ``` ## Auto-Installation Wizard The SDK includes an auto-installation wizard that can detect your project's framework and automatically modify your codebase to integrate the SDK. ### CLI Usage ```bash # Basic usage npx humanbehavior-js auto-install YOUR_API_KEY # With options npx humanbehavior-js auto-install YOUR_API_KEY --yes --project /path/to/project # Help npx humanbehavior-js auto-install --help ``` ### React Component Usage ```jsx import { AutoInstallWizard } from 'humanbehavior-js/react'; function Dashboard() { return ( <AutoInstallWizard apiKey="your-api-key" onComplete={(result) => console.log('Installation completed!', result)} onError={(error) => console.error('Installation failed:', error)} /> ); } ``` ### Supported Frameworks - āœ… React (CRA, Vite, Webpack) - āœ… Next.js (App Router, Pages Router) - āœ… Vue (Vue CLI, Vite) - āœ… Angular - āœ… Svelte (SvelteKit, Vite) - āœ… Vanilla JS/TS - āœ… Node.js (CommonJS & ESM) The wizard will automatically: 1. Detect your project's framework and setup 2. Install the humanbehavior-js package 3. Modify your main app files to integrate the SDK 4. Create environment files with your API key 5. Make your app ready to track user behavior ## Architecture - **Frontend**: TypeScript SDK with session restoration - **Backend**: Node.js ingestion server with Redis storage - **Archiver**: Processes completed sessions to S3 and Prisma - **Session Continuity**: localStorage + cookie-based session management