npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

humanbehavior-js

v0.5.70

Published

SDK for HumanBehavior session and event recording

Readme

HumanBehavior JS - Modular SDK

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
│   ├── react/        # React hooks and context provider
│   └── wizard/       # AI-enhanced installation wizard
└── tooling/          # Shared build tools and configs

Core 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() - Initialization helper
  • Framework integrations via subpaths: /react, /core, /wizard

@humanbehavior/core

Core SDK functionality including:

  • Session Recording: High-fidelity session replay using rrweb
  • Event Tracking: Automatic and manual event tracking
  • 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 apps
  • useHumanBehavior() - Hook to access tracker instance
  • useRedaction() - Hook for managing redaction fields
  • useUserTracking() - Hook for user identification
  • 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-js

This 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');
tracker.start();

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');
  tracker.start();
</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 (30-minute window)

📊 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
});

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();

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 sendBeacon on 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"
}

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/user/auth

When: Called when tracker.auth() is invoked

Request Body:

{
  "userId": "string",
  "userAttributes": {
    "email": "string",
    "name": "string",
    ...
  },
  "sessionId": "string",
  "authFields": ["email", "password", ...]
}

Headers:

  • Authorization: Bearer {apiKey}
  • Content-Type: application/json

Response:

{
  "success": true,
  "message": "User authenticated",
  "userId": "string",
  "sessionId": "string"
}

Purpose: Authenticates a user and marks specific fields as authentication-related for enhanced security handling.


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.


Request Flow & Timing

  1. Initialization: SDK creates session ID locally (no server call)
  2. Event Batching: POST /api/ingestion/events is called:
    • Every 3 seconds (automatic flush interval)
    • When event queue reaches maximum size
    • On page unload (via sendBeacon if available)
  3. User Actions: POST /api/ingestion/user or /user/auth when user identification occurs
  4. Custom Events: POST /api/ingestion/customEvent immediately when customEvent() is called
  5. Error Tracking: POST /api/ingestion/logs and /network are called asynchronously when errors occur

Error Handling

  • 429 (Rate Limit): SDK sets monthlyLimitReached flag 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 sendBeacon API
  • 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 build

Testing & Deployment

Testing SDK Changes Locally

Quick workflow for testing SDK changes:

  1. Make your changes in the humanbehavior-js repository

  2. Build and package:

    npm run testing

    This cleans, builds, and creates a .tgz package file (e.g., humanbehavior-js-0.5.61.tgz)

  3. Install in your test project:

    cd /path/to/your/test-project
       
    # Clean install (recommended to ensure fresh package)
    rm -rf node_modules package-lock.json
       
    # Install the new SDK package (use absolute path)
    npm install /absolute/path/to/humanbehavior-js/humanbehavior-js-0.5.61.tgz
  4. Start test ingestion server (in another terminal):

    cd test-ingestion
    npm install
    npm start

    Server runs on http://localhost:5050 by default.

  5. Configure SDK in your test project:

    const tracker = HumanBehaviorTracker.init('your-api-key', {
      ingestionUrl: 'http://localhost:5050'  // Point to test server
    });
  6. Test in incognito mode:

    • ⚠️ Always test in an incognito/private browser window to avoid browser caching old SDK versions
    • Open your test app and verify your changes work correctly
  7. View your test sessions:

    • Session Replay: http://localhost:5050/viewer.html - See all recorded sessions with replay
    • Logs & Network Errors: http://localhost:5050/logs-viewer.html - See console errors and network failures

Benefits of test-ingestion server:

  • ✅ No database or Kafka setup required
  • ✅ Visual session replay viewer
  • ✅ Logs and network errors viewer
  • ✅ Auto-refreshing viewers (updates every 3 seconds)
  • ✅ Perfect for quick SDK testing

Important Notes:

  • Use an absolute path when installing the .tgz file
  • Always test in incognito mode to avoid browser caching
  • Restart your dev server after installing the new package
  • Check package.json to verify the correct SDK version is installed

Publishing Process

To publish a new version to npm:

  1. Commit your changes:

    git add .
    git commit -m "Your commit message"
  2. Bump version and build:

    npm version patch  # or 'minor' or 'major'
    npm run build
  3. Publish to npm:

    npm publish
  4. Push 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';

// Wizard (CLI)
import { AIAutoInstallCLI } from 'humanbehavior-js/wizard';

Architecture Benefits

  1. Simple Start: Install one package and everything works
  2. Progressive Enhancement: Add framework-specific features as needed
  3. Tree-shaking: Only bundle what you use
  4. Framework Optimizations: Each framework package is optimized for its target
  5. Better Maintainability: Clear separation of concerns
  6. Reduced Bundle Size: Smaller packages for specific use cases
  7. 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://documentation.humanbehavior.co
  • Repository: https://github.com/humanbehavior-gh/humanbehavior-js
  • Homepage: https://documentation.humanbehavior.co

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

Built with ❤️ by the HumanBehavior team