HumanBehaviorTracker API

The main tracker class for recording user sessions and events.
How to find your Public API Key:
Flow: Project Home → Integrations → Human Behavior SDK → Kebab Menu → Configuration → Public API Key
Where to find your Public API Key

Example screenshot – your actual API key will be different.

Initialization

HumanBehaviorTracker.init(apiKey, options?)

Static method to initialize the tracker with global persistence.
static init(
  apiKey: string, 
  options?: {
    ingestionUrl?: string;
    logLevel?: 'none' | 'error' | 'warn' | 'info' | 'debug';
    redactFields?: string[];
    enableAutomaticTracking?: boolean;
    automaticTrackingOptions?: {
      trackButtons?: boolean;
      trackLinks?: boolean;
      trackForms?: boolean;
      includeText?: boolean;
      includeClasses?: boolean;
    };
  }
): HumanBehaviorTracker
Parameters:
  • apiKey (string): Your HumanBehavior API key
  • options (object, optional): Configuration options
    • ingestionUrl (string, optional): Custom ingestion URL
    • logLevel (string, optional): Logging level
    • redactFields (string[], optional): CSS selectors for fields to redact
    • enableAutomaticTracking (boolean, optional): Enable automatic tracking (default: true)
    • automaticTrackingOptions (object, optional): Automatic tracking configuration
Returns: HumanBehaviorTracker instance Example:
const tracker = HumanBehaviorTracker.init(process.env.HUMANBEHAVIOR_API_KEY, {
  redactFields: ['input[type="password"]', '#email'],
  logLevel: 'debug',
  automaticTrackingOptions: {
    trackButtons: true,
    trackLinks: true,
    trackForms: true
  }
});

Core Methods

start()

Start recording user sessions and events.
async start(): Promise<void>
Example:
await tracker.start();

stop()

Stop recording and cleanup resources.
async stop(): Promise<void>
Example:
await tracker.stop();

customEvent(eventName, properties?)

Track a custom event with optional properties.
async customEvent(eventName: string, properties?: Record<string, any>): Promise<void>
Parameters:
  • eventName (string): Name of the custom event
  • properties (object, optional): Additional event properties
Example:
await tracker.customEvent('button_clicked', {
  buttonLocation: 'header',
  userId: 'user123'
});

addEvent(event)

Add a raw event to the recording queue.
async addEvent(event: any): Promise<void>
Parameters:
  • event (any): Raw event object to record
Example:
await tracker.addEvent({
  type: 'custom',
  data: { action: 'button_click' }
});

User Management

identifyUser({ userProperties })

Identify a user with their properties. This method maintains the current endUserId and merges user properties.
async identifyUser(
  { userProperties }: { 
    userProperties: Record<string, any> 
  }
): Promise<string>
Parameters:
  • userProperties (object): User properties including email, name, image, provider, etc.
Returns: Promise<string> - The current endUserId Example:
await tracker.identifyUser({
  userProperties: {
    email: user.email,
    name: user.name,
    userId: user.id,
    provider: account?.provider
  }
});

getUserAttributes()

Get current user attributes.
getUserAttributes(): Record<string, any>
Returns: Object containing current user properties Example:
const userAttributes = tracker.getUserAttributes();
console.log(userAttributes); // { email: 'user@example.com', name: 'John Doe' }

logout()

Clear user identification and reset to anonymous state.
logout(): void
Example:
tracker.logout();

trackPageView(url?)

Track a page view event.
async trackPageView(url?: string): Promise<void>
Parameters:
  • url (string, optional): URL to track (defaults to current URL)
Example:
await tracker.trackPageView('/dashboard');

trackNavigationEvent(type, fromUrl, toUrl)

Track a navigation event.
async trackNavigationEvent(type: string, fromUrl: string, toUrl: string): Promise<void>
Parameters:
  • type (string): Navigation type (e.g., ‘push’, ‘pop’, ‘replace’)
  • fromUrl (string): Previous URL
  • toUrl (string): New URL
Example:
await tracker.trackNavigationEvent('push', '/home', '/dashboard');

Redaction Management

setRedactedFields(fields)

Set fields to be redacted from recordings.
setRedactedFields(fields: string[]): void
Parameters:
  • fields (string[]): Array of CSS selectors for fields to redact
Example:
tracker.setRedactedFields([
  'input[type="password"]',
  '#email',
  '.sensitive-data'
]);

isRedactionActive()

Check if redaction is currently active.
isRedactionActive(): boolean
Returns: boolean - Whether redaction is active Example:
const isActive = tracker.isRedactionActive();

getRedactedFields()

Get current redacted fields.
getRedactedFields(): string[]
Returns: string[] - Array of current redacted field selectors Example:
const fields = tracker.getRedactedFields();

unredactFields(fields)

Remove specific fields from redaction.
unredactFields(fields: string[]): void
Parameters:
  • fields (string[]): Array of CSS selectors for fields to unredact
Example:
tracker.unredactFields([
  '#public-comment',
  '.non-sensitive-input'
]);

clearRedactedFields()

Clear all redacted fields (disable redaction completely).
clearRedactedFields(): void
Example:
tracker.clearRedactedFields();

redact(options?)

Apply redaction to current session.
async redact(options?: RedactionOptions): Promise<void>
Parameters:
  • options (object, optional): Redaction options
Example:
await tracker.redact();

Session Information

getSessionId()

Get the current session ID.
getSessionId(): string
Returns: string - Current session ID Example:
const sessionId = tracker.getSessionId();

getCurrentUrl()

Get the current URL.
getCurrentUrl(): string
Returns: string - Current URL Example:
const currentUrl = tracker.getCurrentUrl();

getUserInfo()

Get comprehensive user information.
getUserInfo(): {
  endUserId: string | null;
  sessionId: string;
  isPreexistingUser: boolean;
  initialized: boolean;
}
Returns: Object containing user information Example:
const userInfo = tracker.getUserInfo();
console.log(userInfo.endUserId); // Current endUserId
console.log(userInfo.sessionId); // Current sessionId

isPreexistingUser()

Check if the current user is preexisting.
isPreexistingUser(): boolean
Returns: boolean - Whether user is preexisting Example:
const isPreexisting = tracker.isPreexistingUser();

Connection Management

testConnection()

Test connection to the HumanBehavior server.
async testConnection(): Promise<{ success: boolean; error?: string }>
Returns: Object with connection status Example:
const result = await tracker.testConnection();
if (result.success) {
  console.log('Connection successful');
} else {
  console.log('Connection failed:', result.error);
}

getConnectionStatus()

Get detailed connection status and recommendations.
getConnectionStatus(): {
  blocked: boolean;
  recommendations: string[];
}
Returns: Object with connection status and recommendations Example:
const status = tracker.getConnectionStatus();
if (status.blocked) {
  console.log('Connection blocked. Recommendations:', status.recommendations);
}

Logging and Debugging

viewLogs()

View stored logs (if available).
viewLogs(): void
Example:
tracker.viewLogs();

configureLogging(config)

Configure logging options.
static configureLogging(config: {
  level?: 'none' | 'error' | 'warn' | 'info' | 'debug';
  enableConsole?: boolean;
  enableStorage?: boolean;
}): void
Parameters:
  • config (object): Logging configuration
    • level (string, optional): Log level
    • enableConsole (boolean, optional): Enable console logging
    • enableStorage (boolean, optional): Enable storage logging
Example:
HumanBehaviorTracker.configureLogging({
  level: 'debug',
  enableConsole: true,
  enableStorage: false
});

Snapshot Information

getSnapshotFrequencyInfo()

Get information about snapshot frequency and timing.
getSnapshotFrequencyInfo(): {
  sessionDuration: number;
  currentInterval: number;
  currentThreshold: number;
  phase: string;
}
Returns: Object with snapshot frequency information Example:
const info = tracker.getSnapshotFrequencyInfo();
console.log('Session duration:', info.sessionDuration);
console.log('Current phase:', info.phase);