Skip to main content

Overview

The MentiQ Analytics SDK automatically manages user sessions, tracking engagement, duration, and activity. Sessions provide crucial context for understanding user behavior and calculating engagement metrics.

Session Lifecycle

Automatic Session Creation

Sessions are automatically created when the Analytics instance is initialized:
import { Analytics } from 'mentiq-sdk';

const analytics = new Analytics({
  apiKey: 'your-api-key',
  projectId: 'your-project-id',
  sessionTimeout: 30 * 60 * 1000, // 30 minutes (default)
});

// Session is automatically started

Session Timeout

Sessions automatically end after a period of inactivity (default: 30 minutes). A new session begins when the user becomes active again.
const analytics = new Analytics({
  apiKey: 'your-api-key',
  projectId: 'your-project-id',
  sessionTimeout: 20 * 60 * 1000, // 20 minutes
});
sessionTimeout
number
default:"1800000"
Duration of inactivity (in milliseconds) before a session expires. Default is 30 minutes (1800000ms).

Session Data

The SDK tracks comprehensive session data:

SessionData Interface

interface SessionData {
  sessionId?: string;           // Unique session identifier
  startTime: number;            // Session start timestamp
  endTime?: number;             // Session end timestamp (if ended)
  duration?: number;            // Session duration in ms
  pageViews: number;            // Number of page views
  clicks: number;               // Number of clicks
  scrollDepth: number;          // Current scroll depth (0-100)
  maxScrollDepth: number;       // Maximum scroll depth reached
  isActive: boolean;            // Whether session is currently active
  events: string[];             // Array of event names tracked
  scrollEvents?: number;        // Number of scroll events
  clickEvents?: number;         // Number of click events
  pageChanges?: number;         // Number of page changes
  engagementScore?: number;     // Calculated engagement score (0-100)
  bounceLikelihood?: number;    // Probability of bounce (0-100)
  channel?: string;             // Acquisition channel
}

Retrieving Session Information

Get Session ID

Retrieve the current session identifier:
const sessionId = analytics.getSessionId();
console.log('Current session:', sessionId);

Get Session Data

Retrieve basic session data:
const sessionData = analytics.getSessionData();
console.log('Page views:', sessionData.pageViews);
console.log('Clicks:', sessionData.clicks);
console.log('Max scroll depth:', sessionData.maxScrollDepth);

Get Active Session

Retrieve detailed session metrics with calculated scores:
const activeSession = analytics.getActiveSession();
console.log('Engagement score:', activeSession.engagementScore);
console.log('Bounce likelihood:', activeSession.bounceLikelihood);
console.log('Duration:', activeSession.duration, 'ms');

Session Metrics

Engagement Score

The SDK automatically calculates an engagement score (0-100) based on:
  • Click Engagement (up to 25 points): Number of clicks × 2
  • Scroll Engagement (up to 20 points): Maximum scroll depth
  • Time Engagement (up to 30 points): Session duration (diminishing returns after 10 minutes)
  • Page View Engagement (up to 20 points): Number of page views × 4
  • Scroll Event Engagement (up to 5 points): Number of scroll events × 0.5
const score = analytics.calculateEngagementScore();
console.log('Current engagement score:', score);

// Engagement score is automatically included in session data
const session = analytics.getActiveSession();
if (session.engagementScore > 70) {
  console.log('Highly engaged user!');
}

Bounce Likelihood

The SDK calculates bounce likelihood (0-100) where higher values indicate greater chance of bouncing:
const session = analytics.getActiveSession();

if (session.bounceLikelihood > 80) {
  // User is likely to bounce - consider intervention
  showSpecialOffer();
}
Bounce likelihood decreases based on:
  • Multiple page views (-30 points)
  • Multiple clicks (-20 points)
  • Active scrolling (-15 points)
  • Scrolling past 50% (-15 points)
  • Time on site > 30 seconds (-10 points)
  • Time on site > 2 minutes (-10 points)

Session Activity Tracking

The SDK automatically tracks user activity to maintain session state:

Tracked Activities

  • Mouse movements
  • Keyboard inputs
  • Clicks
  • Scrolling
  • Touch events
Each activity resets the session timeout timer.

Session Events

Session start and end events are automatically tracked:
// Session start (automatic on initialization)
// Event: "session_start"

// Session end (automatic on timeout or manual end)
// Event: "session_end" with full session data

Manual Session Management

Reset Session

Reset user data and start a fresh session:
analytics.reset();
// Clears user ID, event queue, and creates new session
Calling reset() clears all user identification and queued events. Use this when a user logs out.

Flush Session Data

Manually send all queued events including session data:
await analytics.flush();

Session Storage

Session Persistence

Session IDs are stored in sessionStorage and persist across page reloads within the same browser tab:
// Session ID is automatically stored as:
// sessionStorage.getItem('mentiq_session_id')

// Last activity timestamp is stored as:
// localStorage.getItem('mentiq_last_activity')

Cross-Tab Behavior

Each browser tab maintains its own session. Opening your app in a new tab creates a new session with a unique session ID.

Channel Attribution

Sessions automatically track acquisition channel based on:
  1. UTM Parameters (highest priority)
    • utm_source
    • utm_medium
    • utm_campaign
  2. Custom Tracking Parameters
    • ref or referral query params
  3. Referrer Analysis
    • Social media platforms
    • Search engines
    • Other websites
  4. Direct Traffic (no referrer)
const session = analytics.getSessionData();
console.log('Acquisition channel:', session.channel);
// Examples: "paid_social_facebook", "organic_search_google", "direct"

Advanced Session Tracking

Session Recording

Enable session recording to capture user interactions:
const analytics = new Analytics({
  apiKey: 'your-api-key',
  projectId: 'your-project-id',
  enableSessionRecording: true,
});

// Control recording
analytics.startRecording();
analytics.pauseRecording();
analytics.resumeRecording();
analytics.stopRecording();

// Check recording status
if (analytics.isRecordingActive()) {
  console.log('Session is being recorded');
}
Session recording can generate significant data and may impact performance. Use selectively for specific user segments or pages.

Heatmap Tracking

Track click and scroll heatmaps during sessions:
const analytics = new Analytics({
  apiKey: 'your-api-key',
  projectId: 'your-project-id',
  enableHeatmapTracking: true,
});
This tracks:
  • Click positions
  • Mouse movement patterns
  • Scroll depth and positions
  • Element interactions

Session-Based Analysis

Use session data for behavioral analysis:
const session = analytics.getActiveSession();

// High-value session detection
if (session.engagementScore > 75 && session.pageViews > 5) {
  // User is highly engaged - show premium content
  unlockPremiumFeature();
}

// Bounce prevention
if (session.bounceLikelihood > 70 && session.duration < 30000) {
  // Show exit-intent popup
  showRetentionOffer();
}

// Channel-specific behavior
if (session.channel?.includes('paid')) {
  // Track paid campaign performance
  evaluateCampaignROI();
}

Best Practices

Set session timeout based on your application type:
  • Content sites: 30 minutes (default)
  • E-commerce: 60 minutes
  • SaaS applications: 4-8 hours
  • Banking/Security: 5-15 minutes
Use engagement score to segment users:
  • High engagement (greater than 70): Power users, feature adopters
  • Medium engagement (40-70): Regular users
  • Low engagement (less than 40): At-risk users, need intervention
Session data is automatically included with all events, providing rich context for analysis.

Common Use Cases

Detect Inactive Users

const session = analytics.getActiveSession();
const sessionDuration = session.duration || 0;

if (sessionDuration > 5 * 60 * 1000 && session.engagementScore < 30) {
  // User has been on site for 5+ minutes but low engagement
  showHelpPrompt();
}

Track Session Quality

const session = analytics.getActiveSession();

if (session.maxScrollDepth < 25 && session.pageViews === 1) {
  // Single page, minimal scroll - potential quality issue
  analytics.track('low_quality_session', {
    scroll_depth: session.maxScrollDepth,
    duration: session.duration,
  });
}

Monitor Real-Time Engagement

setInterval(() => {
  const score = analytics.calculateEngagementScore();
  updateEngagementDashboard(score);
}, 30000); // Every 30 seconds

Build docs developers (and LLMs) love