# 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 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()` starts recording)
- Framework integrations via subpaths: `/react`, `/core`, `/auto`, `/react/auto`
- The installer is a separate package: `npx @humanbehavior/wizard`. There is no `humanbehavior-js/wizard` runtime 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 apps
- `useHumanBehavior()` - Hook to access tracker instance
- `useRedaction()` - Hook for managing redaction fields
- `useUserTracking()` - Hook for user identification
- `HumanBehaviorErrorBoundary` + `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)

```bash
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:

```bash
# React
npm install @humanbehavior/react

# Or use subpath imports
import { useHumanBehavior } from 'humanbehavior-js/react';
```

## Quick Start

### Vanilla JavaScript

```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

```jsx
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)

```html
<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

```javascript
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

```javascript
// Initialize
const tracker = HumanBehaviorTracker.init(apiKey, options);

// Start/Stop recording
tracker.start();
tracker.stop();

// User identification
tracker.identifyUser({ userProperties: { email: 'user@example.com' } });

// 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:**
```json
{
  "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:**
```json
{
  "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:**
```json
{
  "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:**
```json
{
  "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:**
```json
{
  "sessionId": "string",
  "eventName": "string",
  "eventProperties": {
    "property1": "value1",
    ...
  },
  "endUserId": "string | null"
}
```

**Headers:**
- `Authorization: Bearer {apiKey}`
- `Content-Type: application/json`

**Response:**
```json
{
  "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:**
```json
{
  "sessionId": "string",
  "events": [
    {
      "eventName": "string",
      "eventProperties": {...}
    },
    ...
  ],
  "endUserId": "string | null"
}
```

**Headers:**
- `Authorization: Bearer {apiKey}`
- `Content-Type: application/json`

**Response:**
```json
{
  "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:**
```json
{
  "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:**
```json
{
  "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:**
```json
{
  "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:**
```json
{
  "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

1. **Initialization**: SDK creates session ID locally (no server call). `init()` also calls `start()`.
2. **Event Batching**: `POST /api/ingestion/events` is 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/`sendBeacon` if available)
3. **User Actions**: `POST /api/ingestion/user` when user identification occurs
4. **Custom Events**: `POST /api/ingestion/customEvent` (short in-process batch, then send)
5. **Crashes**: `POST /api/ingestion/errors` for captured exceptions
6. **Console / network / traces**: `POST /api/ingestion/logs`, `/network`, and `/spans/batch`

## 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

```bash
# 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:**
   ```bash
   npm run testing
   ```
   This cleans, builds, and creates a `.tgz` (version comes from root `package.json`).

3. **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.

4. **Ingestion:** there is no `test-ingestion/` folder in this repo. Point `ingestionUrl` at a running HumanBehavior ingestion server (parent monorepo: `pnpm dev:server`, default `http://localhost:8000`). For capture-only local demos: `npm run demo` then open `/tests/e2e/public/demo.html`.

**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:**
   ```bash
   git add .
   git commit -m "Your commit message"
   ```

2. **Bump version and build:**
   ```bash
   npm version patch  # or 'minor' or 'major'
   npm run build
   ```

3. **Publish to npm:**
   ```bash
   npm publish
   ```

4. **Push to git:**
   ```bash
   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:

```javascript
// 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/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://docs.humanbehavior.co
- **Repository**: https://github.com/humanbehavior-gh/humanbehavior-js
- **Homepage**: https://docs.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

