humanbehavior-js
v0.8.9
Published
SDK for HumanBehavior session and event recording
Downloads
25,542
Readme
HumanBehavior JS - Modular SDK
Last updated: 2026-08-22
A modular JavaScript SDK for recording user sessions and tracking events with high-fidelity session replay, automatic event tracking, and comprehensive analytics capabilities.
Architecture
This SDK is built as a monorepo using npm workspaces and Turbo, organized into separate packages for optimal tree-shaking, maintainability, and framework-specific optimizations.
Package Structure
humanbehavior-js/
├── packages/
│ ├── browser/ # Main entry point (re-exports from core)
│ ├── core/ # Core SDK functionality
│ ├── loader/ # Auto-updating stub (`humanbehavior-js/auto`)
│ ├── react/ # React hooks and context provider
│ └── wizard/ # Separate npm package `@humanbehavior/wizard` (not a runtime subpath)
└── tooling/ # Shared build tools and configsCore Packages
humanbehavior-js (Main Package)
The primary package that provides everything you need out of the box. Re-exports from @humanbehavior/core and provides UMD builds for direct browser usage.
Exports:
HumanBehaviorTracker- Main tracker class (init()starts recording)- Framework integrations via subpaths:
/react,/core,/auto,/react/auto - The installer is a separate package:
npx @humanbehavior/wizard. There is nohumanbehavior-js/wizardruntime export.
@humanbehavior/core
Core SDK functionality including:
- Session Recording: High-fidelity session replay using rrweb
- Event Tracking: Automatic and manual event tracking
- Error capture: uncaught / rejection / resource / CSP /
captureException - Tracing: page-load + resource spans,
startSpan/startInactiveSpan - API Client: Communication with HumanBehavior ingestion servers
- Redaction Manager: Privacy-first data redaction
- Persistence Layer: Session persistence across page reloads
- Retry Queue: Reliable event delivery with retry logic
- Utilities: Logger, property manager, global tracker
@humanbehavior/react
React-specific integrations:
HumanBehaviorProvider- Context provider for React appsuseHumanBehavior()- Hook to access tracker instanceuseRedaction()- Hook for managing redaction fieldsuseUserTracking()- Hook for user identificationHumanBehaviorErrorBoundary+captureNextError()for render errors- Automatic page view tracking for SPAs
@humanbehavior/wizard
AI-enhanced installation wizard:
- Framework detection and auto-installation
- Code modification suggestions
- CLI tools for setup automation
- Centralized AI service integration
Installation
Quick Start (Recommended)
npm install humanbehavior-jsThis single package includes everything you need:
- Core session recording
- Automatic event tracking
- User identification
- Data redaction
- Session persistence
- Framework integrations
Framework-Specific Packages (Optional)
For better tree-shaking, you can install framework-specific packages:
# React
npm install @humanbehavior/react
# Or use subpath imports
import { useHumanBehavior } from 'humanbehavior-js/react';Quick Start
Vanilla JavaScript
import { HumanBehaviorTracker } from 'humanbehavior-js';
const tracker = HumanBehaviorTracker.init('your-api-key');
// init() starts recording. start() is a no-op if already started.React
import { HumanBehaviorProvider, useHumanBehavior } from 'humanbehavior-js/react';
function App() {
return (
<HumanBehaviorProvider apiKey="your-api-key">
<YourApp />
</HumanBehaviorProvider>
);
}
function MyComponent() {
const tracker = useHumanBehavior();
const handleClick = () => {
tracker.customEvent('button_clicked', { buttonId: 'signup' });
};
return <button onClick={handleClick}>Sign Up</button>;
}UMD Build (Browser)
<script src="https://unpkg.com/humanbehavior-js"></script>
<script>
const tracker = HumanBehaviorTracker.init('your-api-key');
</script>Key Features
🎥 Session Recording
- High-fidelity replay using rrweb
- Captures mouse movements, clicks, scrolls, keyboard input
- Canvas recording support (optional)
- Multi-window tracking
- Session persistence across page reloads (15-minute idle timeout; 24-hour max session)
📊 Event Tracking
- Automatic tracking of buttons, links, and forms
- Custom event tracking
- Console and network error tracking
- Navigation tracking for SPAs
- Rage click and dead click detection
🔒 Privacy & Security
- Privacy-first redaction by default
- Configurable redaction strategies
- Field-level data masking
- Unredaction for specific fields when needed
👤 User Identification
- User property tracking
- Session-to-user association
- Global user identification across sessions
🚀 Performance
- Event batching and queueing
- Automatic retry on failures
- Configurable queue sizes
- Tree-shakeable modules
Configuration Options
const tracker = HumanBehaviorTracker.init('your-api-key', {
ingestionUrl: 'https://your-ingestion-url.com',
redactionStrategy: {
mode: 'privacy-first', // or 'visibility-first'
unredactFields: ['email', 'name'] // Fields to keep visible
},
enableAutomaticTracking: true,
automaticTrackingOptions: {
trackButtons: true,
trackLinks: true,
trackForms: true,
includeText: true,
includeClasses: true
},
recordCanvas: false, // Enable canvas recording
maxQueueSize: 1000, // Maximum events in queue
enableConsoleTracking: true, // Track console errors
enableNetworkTracking: true, // Track network errors
enableErrorTracking: true, // Crash capture (default on)
enableTracing: true, // Page-load / resource / custom spans (default on)
enableWebVitals: true, // FCP/LCP/CLS/INP/TTFB as $web_vitals (default on)
release: '1.2.3' // Stamped on errors; pair with `npx @humanbehavior/wizard upload-sourcemaps`
});API Reference
Core Methods
// Initialize
const tracker = HumanBehaviorTracker.init(apiKey, options);
// Start/Stop recording
tracker.start();
tracker.stop();
// User identification
tracker.identifyUser({ userProperties: { email: '[email protected]' } });
// Custom events
tracker.customEvent('event_name', { property: 'value' });
// Redaction
tracker.setUnredactedFields(['email', 'name']);
tracker.getUnredactedFields();
// Session info
tracker.getSessionId();
tracker.getCurrentUrl();
// Error capture (also automatic for uncaught / rejection / resource / CSP)
tracker.captureException(err);
// Tracing (enabled by default; no-op if enableTracing: false)
tracker.startSpan({ name: 'checkout' }, () => { /* ... */ });API Endpoints
The SDK communicates with HumanBehavior ingestion servers through the following endpoints. All requests include authentication via Authorization: Bearer {apiKey} header.
POST /api/ingestion/events
When: Called automatically when events are batched (every 3 seconds) or when queue reaches maximum size
Request Body:
{
"sessionId": "string",
"events": [
{
"type": "string",
"timestamp": number,
"data": {...},
...
}
],
"endUserId": "string | null",
"windowId": "string (optional)",
"automaticProperties": {...} (optional),
"sdkVersion": "string"
}Headers:
Authorization: Bearer {apiKey}Content-Type: application/json
Response:
{
"success": true,
"appended": number,
"sessionCreated": boolean,
"monthlyLimitReached": boolean (optional)
}Purpose: Sends session replay events (rrweb events) and custom events to the server. Supports chunking for large payloads (max 1MB per chunk). Events are automatically batched and sent every 3 seconds. Sessions are created automatically on the server when the first event is received (PostHog-style, no separate init call needed).
Special Features:
- Automatic chunking for payloads > 1MB
- Retry logic with exponential backoff
- Persistence to localStorage for offline scenarios
- Falls back to
sendBeaconon page unload or CSP violations
POST /api/ingestion/user
When: Called when tracker.identifyUser() is invoked
Request Body:
{
"userId": "string",
"userAttributes": {
"email": "string",
"name": "string",
...
},
"sessionId": "string",
"posthogName": "string | null",
"identityToken": "string (optional; required when the project enforces identity verification)"
}Headers:
Authorization: Bearer {apiKey}Content-Type: application/json
Response:
{
"success": true,
"userId": "string",
"sessionId": "string"
}Purpose: Identifies and associates user properties with a session. Creates or updates user profile on the server.
POST /api/ingestion/customEvent
When: Called when tracker.customEvent() is invoked
Request Body:
{
"sessionId": "string",
"eventName": "string",
"eventProperties": {
"property1": "value1",
...
},
"endUserId": "string | null"
}Headers:
Authorization: Bearer {apiKey}Content-Type: application/json
Response:
{
"success": true,
"eventId": "string"
}Purpose: Sends a single custom event to the server for analytics tracking.
POST /api/ingestion/customEvent/batch
When: Called when multiple custom events need to be sent together
Request Body:
{
"sessionId": "string",
"events": [
{
"eventName": "string",
"eventProperties": {...}
},
...
],
"endUserId": "string | null"
}Headers:
Authorization: Bearer {apiKey}Content-Type: application/json
Response:
{
"success": true,
"eventIds": ["string", ...]
}Purpose: Sends multiple custom events in a single request for better efficiency.
POST /api/ingestion/logs
When: Called automatically when console warnings or errors occur (if enableConsoleTracking is true)
Request Body:
{
"level": "warn" | "error",
"message": "string",
"stack": "string (optional)",
"url": "string",
"timestampMs": number,
"sessionId": "string",
"endUserId": "string | null"
}Headers:
Authorization: Bearer {apiKey}Content-Type: application/json
Response:
{
"success": true
}Purpose: Tracks console warnings and errors for debugging and monitoring. Only sends warn and error level logs, not log or info.
POST /api/ingestion/network
When: Called automatically when network requests fail (4xx, 5xx errors) or encounter network errors (if enableNetworkTracking is true)
Request Body:
{
"requestId": "string",
"url": "string",
"method": "string",
"status": number | null,
"statusText": "string | null",
"duration": number,
"timestampMs": number,
"sessionId": "string",
"endUserId": "string | null",
"errorType": "client_error" | "server_error" | "network_error" | "timeout_error" | "cors_error" | "csp_violation" | "blocked_by_client" | "unknown_error",
"errorMessage": "string | null",
"errorName": "string | null",
"startTimeMs": number (optional),
"spanName": "string (optional)",
"spanStatus": "error" | "success" | "slow" (optional),
"attributes": {
"http.status_code": number,
"http.status_text": "string",
...
}
}Headers:
Authorization: Bearer {apiKey}Content-Type: application/json
Response:
{
"success": true
}Purpose: Tracks network errors and failed HTTP requests for monitoring and debugging. Automatically classifies error types (CORS, timeout, CSP violations, etc.). Note: SDK's own requests to ingestion endpoints are excluded from tracking to avoid recursion.
POST /api/ingestion/errors
When: Uncaught errors, unhandled rejections, resource/CSP failures, React error-boundary reports, and tracker.captureException().
Purpose: Structured ErrorReport (stack frames, mechanism, breadcrumbs, release / environment / commitSha / dist). Routed through the retry queue.
POST /api/ingestion/spans/batch
When: Browser tracing is enabled (default). Page-load and resource spans, plus startSpan / startInactiveSpan.
Purpose: Trace waterfall. sendBeacon on unload.
Request Flow & Timing
- Initialization: SDK creates session ID locally (no server call).
init()also callsstart(). - Event Batching:
POST /api/ingestion/eventsis called:- Every 3 seconds when idle (
IDLE_FLUSH_INTERVAL_MS); 150ms while a live replay is open - When event queue reaches maximum size
- On page unload (via keepalive/
sendBeaconif available)
- Every 3 seconds when idle (
- User Actions:
POST /api/ingestion/userwhen user identification occurs - Custom Events:
POST /api/ingestion/customEvent(short in-process batch, then send) - Crashes:
POST /api/ingestion/errorsfor captured exceptions - Console / network / traces:
POST /api/ingestion/logs,/network, and/spans/batch
Error Handling
- 429 (Rate Limit): SDK sets
monthlyLimitReachedflag and stops sending events - 413 (Payload Too Large): SDK automatically reduces batch size and retries
- Network Errors: Events are persisted to localStorage and retried with exponential backoff
- CSP Violations: SDK automatically falls back to
sendBeaconAPI - Offline: Events are queued and sent when connection is restored
Development
Prerequisites
- Node.js 18+
- npm 10+
Setup
# Install dependencies
npm install
# Build all packages
npm run buildTesting & Deployment
Testing SDK Changes Locally
Quick workflow for testing SDK changes:
Make your changes in the
humanbehavior-jsrepositoryBuild and package:
npm run testingThis cleans, builds, and creates a
.tgz(version comes from rootpackage.json).Install in your test project with an absolute path to that
.tgz. Restart the test app's dev server. Test in an incognito window so the browser does not cache an old UMD bundle.Ingestion: there is no
test-ingestion/folder in this repo. PointingestionUrlat a running HumanBehavior ingestion server (parent monorepo:pnpm dev:server, defaulthttp://localhost:8000). For capture-only local demos:npm run demothen open/tests/e2e/public/demo.html.
Important Notes:
- Use an absolute path when installing the
.tgzfile - Always test in incognito mode to avoid browser caching
- Restart your dev server after installing the new package
- Check
package.jsonto verify the correct SDK version is installed
Publishing Process
To publish a new version to npm:
Commit your changes:
git add . git commit -m "Your commit message"Bump version and build:
npm version patch # or 'minor' or 'major' npm run buildPublish to npm:
npm publishPush to git:
git push git push --tags # Push version tag if needed
Note: The prepublishOnly script automatically runs npm run clean && npm run build before publishing, ensuring the latest build is always published.
Project Structure
- Monorepo: Uses npm workspaces for package management
- Build System: Turbo for fast, cached builds
- Bundling: Rollup for ESM, CJS, and UMD outputs
- TypeScript: Full TypeScript support with type definitions
Package Exports
The main package uses modern package.json exports:
// Main entry
import { HumanBehaviorTracker } from 'humanbehavior-js';
// React integration
import { useHumanBehavior } from 'humanbehavior-js/react';
// Core package (advanced)
import { HumanBehaviorTracker } from 'humanbehavior-js/core';
// Auto-updating stub (optional)
import 'humanbehavior-js/auto';
// Installer is a separate package, not a runtime export:
// npx @humanbehavior/wizardArchitecture Benefits
- Simple Start: Install one package and everything works
- Progressive Enhancement: Add framework-specific features as needed
- Tree-shaking: Only bundle what you use
- Framework Optimizations: Each framework package is optimized for its target
- Better Maintainability: Clear separation of concerns
- Reduced Bundle Size: Smaller packages for specific use cases
- Easier Testing: Isolated packages are easier to test
Browser Support
- Chrome/Edge (latest)
- Firefox (latest)
- Safari (latest)
- Mobile browsers (iOS Safari, Chrome Mobile)
License
ISC
Links
- Documentation: https://docs.humanbehavior.co
- Repository: https://github.com/humanbehavior-gh/humanbehavior-js
- Homepage: https://docs.humanbehavior.co
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
Built with ❤️ by the HumanBehavior team
