mentiq-sdk v1.0.6

Mentiq SDK Documentation

A comprehensive analytics SDK for React and Next.js with event tracking, session monitoring, heatmaps, and session recording.

Installation

Install the Mentiq SDK using npm or yarn:

Terminal
$ npm install mentiq-sdk

# or with yarn
$ yarn add mentiq-sdk

Note: The SDK requires React 16.8+ and rrweb 2.0+ as peer dependencies for session recording.

Quick Start

Wrap your app with the AnalyticsProvider and start tracking in minutes:

app/layout.tsx
import { AnalyticsProvider } from "mentiq-sdk";

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <AnalyticsProvider
          config={{
            projectId: "your-project-id",
            apiKey: "mentiq_live_your_api_key",
            endpoint: "https://api.trymentiq.com",
          }}
        >
          {children}
        </AnalyticsProvider>
      </body>
    </html>
  );
}

💡 Tip: Find your API key in the Projects page of your dashboard. An API key is automatically created when you create a project.

Provider Setup

The AnalyticsProvider must wrap your application to enable tracking. It initializes the SDK and provides the analytics context to all child components.

React App
import { AnalyticsProvider } from "mentiq-sdk";

// Basic setup
<AnalyticsProvider
  config={{
    projectId: "my-project",
    apiKey: "mentiq_live_abc123",
    endpoint: "https://api.trymentiq.com",
  }}
>
  <App />
</AnalyticsProvider>

// With all options
<AnalyticsProvider
  config={{
    projectId: "my-project",
    apiKey: "mentiq_live_abc123",
    endpoint: "https://api.trymentiq.com",
    debug: true,                       // Enable console logs
    batchSize: 10,                     // Events per batch
    flushInterval: 10000,              // Auto-flush every 10s
    enableHeatmapTracking: true,       // Enable heatmap tracking
    enableSessionRecording: true,      // Enable session recording
    enableAutoPageTracking: true,      // Auto-track page views
    enablePerformanceTracking: true,   // Track Core Web Vitals
    enableErrorTracking: true,         // Track JS errors
    sessionTimeout: 1800000,           // 30 min session timeout
  }}
>
  <App />
</AnalyticsProvider>

Tracking Events

Use the useAnalytics hook to track custom events:

Component.tsx
import { useAnalytics } from "mentiq-sdk";

function SignupButton() {
  const { track } = useAnalytics();

  const handleClick = () => {
    track("button_clicked", {
      button_name: "signup_cta",
      page: "homepage",
      position: "hero",
    });
  };

  return <button onClick={handleClick}>Sign Up</button>;
}

// Track feature usage
function ExportButton() {
  const { track } = useAnalytics();

  const handleExport = () => {
    track("feature_used", {
      feature_name: "export_report",
      export_format: "pdf",
      record_count: 150,
    });
    // ... actual export logic
  };

  return <button onClick={handleExport}>Export PDF</button>;
}

// Track subscription changes
function UpgradeHandler() {
  const { track } = useAnalytics();

  const handleUpgrade = (newPlan) => {
    track("subscription_upgraded", {
      from_plan: "starter",
      to_plan: newPlan,
      mrr_increase: 50,
    });
  };
}

How Event Batching Works

Events are automatically batched for optimal performance:

  • By size: When queue reaches batchSize (default: 10 events)
  • By time: Every flushInterval (default: 10 seconds)
  • On unload: Before user leaves the page
  • Manual: When you call flush()

User Identification

Identify users to track behavior across sessions and devices:

auth.tsx
import { useAnalytics } from "mentiq-sdk";

function LoginHandler() {
  const { identify, setUserProperties } = useAnalytics();

  const handleLogin = async (user) => {
    // Identify the user after login
    identify(user.id, {
      email: user.email,
      name: user.name,
      plan: user.subscription.plan,
      created_at: user.createdAt,
      company: user.company,
    });
  };

  const handleProfileUpdate = () => {
    // Update user properties anytime
    setUserProperties({
      last_login: new Date().toISOString(),
      feature_flags: ["beta_dashboard", "new_reports"],
    });
  };
}

// Reset identity on logout
function LogoutHandler() {
  const { reset } = useAnalytics();

  const handleLogout = () => {
    reset(); // Clears user data and starts fresh
  };
}

Page Tracking

Automatically track page views using the usePageTracking hook:

page.tsx
"use client";

import { usePageTracking, useAnalytics } from "mentiq-sdk";

export default function DashboardPage() {
  // Automatic page view tracking
  usePageTracking();

  return <div>Dashboard Content</div>;
}

// Manual page view tracking
function CustomPage() {
  const { trackPageView } = useAnalytics();

  useEffect(() => {
    trackPageView({
      path: "/custom-page",
      title: "Custom Page | My App",
      referrer: document.referrer,
    });
  }, []);
}

Heatmap Tracking

Enable heatmap tracking to visualize user interactions:

layout.tsx
<AnalyticsProvider
  config={{
    projectId: "my-project",
    apiKey: "mentiq_live_abc123",
    endpoint: "https://api.trymentiq.com",
    enableHeatmapTracking: true,  // Enable heatmap tracking
  }}
>
  <App />
</AnalyticsProvider>

When enabled, the SDK tracks:

  • Clicks: X/Y coordinates relative to viewport
  • Scrolls: Scroll depth percentage
  • Mouse movements: Sampled movement coordinates
  • Element interactions: Which elements users engage with

Session Recording

The SDK integrates with rrweb for session recording, enabling full session replay in the dashboard:

Enable Session Recording
import { AnalyticsProvider } from "mentiq-sdk";

// Enable session recording with rrweb integration
<AnalyticsProvider
  config={{
    projectId: "my-project",
    apiKey: "mentiq_live_abc123",
    endpoint: "https://api.trymentiq.com",
    enableSessionRecording: true,  // Enable session recording
  }}
>
  <App />
</AnalyticsProvider>

// View recordings in the Session Replay page of your dashboard

Configuration Options

Complete list of configuration options:

OptionTypeDefaultDescription
projectIdstringrequiredYour project ID
apiKeystringrequiredYour API key
endpointstring-Backend API URL
debugbooleanfalseEnable console logs
batchSizenumber20Events per batch
flushIntervalnumber10000Auto-flush interval (ms)
maxQueueSizenumber1000Max queue size
sessionTimeoutnumber1800000Session timeout (30 min)
enableAutoPageTrackingbooleantrueAuto-track page views
enableHeatmapTrackingbooleanfalseEnable heatmap tracking
enableSessionRecordingbooleanfalseEnable session recording
enablePerformanceTrackingbooleanfalseTrack Core Web Vitals
enableErrorTrackingbooleanfalseTrack JavaScript errors
enableABTestingbooleanfalseEnable A/B testing features

API Reference

The useAnalytics hook provides these methods:

track(eventName, properties?)

Track a custom event with optional properties

identify(userId, traits?)

Identify a user with unique ID and traits

setUserProperties(properties)

Update properties for the current user

trackPageView(details?)

Manually track a page view

getSessionId()

Get the current session ID

flush()

Manually flush the event queue

reset()

Reset all user data and start fresh

usePageTracking Hook

Usage
import { usePageTracking } from "mentiq-sdk";

// Simply call in any page component to auto-track page views
export default function Page() {
  usePageTracking();
  return <div>Page content</div>;
}

Need Help?

Check out the full SDK source on GitHub or contact our support team.