A powerful analytics SDK for React and Next.js with heatmap tracking, session monitoring, and performance analytics
npm install mentiq-sdkA powerful, lightweight analytics SDK for React and Next.js applications with advanced features like event queuing, batching, heatmap tracking, session monitoring, and performance analytics.
- ๐ฏ Event tracking with custom properties
- ๐ Page view tracking with auto-tracking
- ๐ค User identification and management
- ๐ Event batching and queuing with retry logic
- ๐ฑ Session management and monitoring
- ๐ฅ Heatmap Tracking: Click, hover, and scroll tracking
- ๐ Session Monitoring: User activity, scroll depth, engagement metrics
- ๐ฅ Session Recording: Replay user sessions with rrweb
- โก Performance Tracking: Core Web Vitals, custom performance metrics
- ๐จ Error Tracking: JavaScript errors, unhandled rejections, React errors
- ๐ฏ Onboarding Tracking: Track user activation funnels and measure completion rates
- ๐ญ React Components: Pre-built tracking components and HOCs
- ๐งช A/B Testing: Experiment management and variant tracking
- ๐ฆ Event queuing with configurable batch sizes
- ๐ Automatic retry with exponential backoff
- ๐ช Local storage for offline support
- ๐ฃ React hooks for easy integration
- ๐ฑ TypeScript support with full type safety
- ๐ Next.js optimized utilities
``bash`
npm install mentiq-sdkor
yarn add mentiq-sdk
`tsx
import React from "react";
import { AnalyticsProvider } from "mentiq-sdk";
function App() {
return (
apiKey: "your-api-key", // Your Mentiq API Key
projectId: "your-project-id", // Your Mentiq Project ID
endpoint: "https://your-endpoint.com/events",
enableHeatmapTracking: true,
enableSessionRecording: true,
enableErrorTracking: true,
batchSize: 10,
flushInterval: 5000,
}}
>
);
}
`
`tsx
import React from "react";
import { useAnalytics, useSessionTracking } from "mentiq-sdk";
function MyComponent() {
const { track, trackError } = useAnalytics();
const { sessionData } = useSessionTracking();
const handleButtonClick = () => {
track("button_clicked", {
button_id: "hero-cta",
user_plan: "premium",
});
};
return (
Session duration: {sessionData?.duration}ms
โ๏ธ Configuration
`tsx
interface AnalyticsConfig {
apiKey: string;
projectId: string;
endpoint?: string;
debug?: boolean;
userId?: string;
sessionTimeout?: number; // Default: 30 minutes
batchSize?: number; // Default: 20 events
flushInterval?: number; // Default: 10 seconds
enableAutoPageTracking?: boolean; // Default: true
enablePerformanceTracking?: boolean;
enableHeatmapTracking?: boolean;
enableSessionRecording?: boolean;
enableErrorTracking?: boolean;
maxQueueSize?: number; // Default: 1000
retryAttempts?: number; // Default: 3
retryDelay?: number; // Default: 1000ms
}
`๐ฃ Core Hooks
$3
Main hook for tracking events and managing users.
`tsx
const {
track, // Track custom events
page, // Track page views
identify, // Identify users
reset, // Reset analytics state
flush, // Force flush events
trackError, // Track custom errors
trackPerformance, // Track performance metrics
getSessionData, // Get current session data
getQueueSize, // Get current queue size
startRecording, // Start session recording
stopRecording, // Stop session recording
pauseRecording, // Pause session recording
resumeRecording, // Resume session recording
isRecordingActive, // Check if recording is active
trackSubscriptionCancellation, // Track subscription cancellations
} = useAnalytics();
`$3
Monitor user session data in real-time.
`tsx
const {
sessionData, // Full session object
sessionId, // Current session ID
isActive, // Is session active
duration, // Session duration in ms
pageViews, // Number of page views
clicks, // Number of clicks
scrollDepth, // Current scroll depth %
} = useSessionTracking();
`$3
Automatic and manual error tracking.
`tsx
const {
trackJavaScriptError, // Track JS errors
trackCustomError, // Track custom errors
} = useErrorTracking();
`$3
Track performance metrics and Core Web Vitals.
`tsx
const {
measureCustomPerformance, // Create custom performance measurements
} = usePerformanceTracking();
`๐งฉ Components
$3
`tsx
event="hero_viewed"
properties={{ section: "homepage" }}
threshold={0.5}
delay={1000}
>
Tracked when 50% visible for 1 second
`$3
`tsx
All interactions tracked for heatmap
`$3
`tsx
`$3
`tsx
}>
`$3
`tsx
`๐ฏ Onboarding Tracking
Track user onboarding flows with the
OnboardingTracker helper. Perfect for measuring funnel completion, identifying dropoff points, and optimizing user activation.$3
The
OnboardingTracker is a helper class that formats and sends events. You must manually call tracker methods when users complete steps.$3
`tsx
import { useOnboardingTracker, useMentiqAnalytics } from "mentiq-sdk";function OnboardingFlow() {
const analytics = useMentiqAnalytics();
// Define your onboarding steps
const config = {
steps: [
{ name: "account_created", index: 0, required: true },
{ name: "profile_completed", index: 1, required: true },
{ name: "preferences_set", index: 2, required: false },
{ name: "first_action", index: 3, required: true },
],
};
const tracker = useOnboardingTracker(analytics, config);
// Start onboarding
useEffect(() => {
tracker?.start({
signup_method: "email",
source: "landing_page",
});
}, []);
// Track step completion
const handleProfileComplete = async () => {
await saveProfile();
tracker?.completeStep("profile_completed", {
fields_filled: ["name", "email", "company"],
});
};
// Skip optional steps
const handleSkip = () => {
tracker?.skipStep("preferences_set", "user_choice");
};
// Get progress
const progress = tracker?.getProgress();
console.log(
${progress?.progressPercent}% complete); return
{/ Your onboarding UI /};
}
`$3
`tsx
// Start onboarding flow
tracker.start(properties?: Record)// Complete a step
tracker.completeStep(stepName: string, properties?: Record)
// Skip optional steps
tracker.skipStep(stepName: string, reason?: string)
// Mark as complete
tracker.complete(properties?: Record)
// Abandon onboarding
tracker.abandon(reason?: string)
// Get current progress
const progress = tracker.getProgress()
// Returns: { currentStep, completedSteps, progressPercent, duration }
`$3
1. You call tracker methods โ Events are sent to backend
2. Events stored in database with metadata (step_index, timing, properties)
3. Backend analyzes events โ Calculates funnel statistics
4. Dashboard displays analytics โ Completion rates, dropoff points, time metrics
$3
The tracker automatically sends these events:
-
onboarding_started - When onboarding begins
- onboarding_step_completed - When each step is completed
- onboarding_step_skipped - When optional steps are skipped
- onboarding_completed - When all required steps are done
- onboarding_abandoned - When user exits early$3
View onboarding metrics in your dashboard:
- Completion Rate: % of users who finish onboarding
- Step-by-Step Breakdown: Completion rate for each step
- Dropoff Points: Steps where users abandon most
- Average Time: Time taken per step and total
- User Journeys: Individual user progress tracking
$3
See
examples/onboarding-tracking.tsx for complete examples:- Basic onboarding flow
- Multi-step form tracking
- Product tour / tutorial
- SaaS onboarding with conditional steps
- Progress monitor component
- Vanilla JavaScript (non-React)
๐ Event Queuing & Batching
The SDK automatically queues events and sends them in batches:
- Batch Size: Configure events per batch
- Flush Interval: Automatic sending frequency
- Retry Logic: Exponential backoff for failed requests
- Offline Support: Queue events when offline
`tsx
const { flush, getQueueSize } = useAnalytics();console.log(
${getQueueSize()} events queued);
await flush(); // Send all events immediately
`๐จ Error Handling
$3
- JavaScript errors
- Unhandled Promise rejections
- React component errors
$3
`tsx
const { trackError } = useAnalytics();try {
// risky operation
} catch (error) {
trackError(error, {
context: "user-action",
user_id: userId,
});
}
`โก Performance Monitoring
$3
Automatically tracks when
enablePerformanceTracking: true:- LCP (Largest Contentful Paint)
- FID (First Input Delay)
- CLS (Cumulative Layout Shift)
- FCP (First Contentful Paint)
$3
`tsx
const { measureCustomPerformance } = usePerformanceTracking();const measurement = measureCustomPerformance("api-call");
measurement.start();
await fetchData();
measurement.end(); // Automatically tracked
`๐ฅ Session Recording
Record and replay user sessions with rrweb integration.
$3
`bash
npm install rrweb
`$3
`tsx
import { AnalyticsProvider } from "mentiq-sdk"; config={{
apiKey: "your-api-key",
projectId: "your-project-id",
enableSessionRecording: true, // Enable automatic recording
}}
>
;
`$3
`tsx
import { useAnalytics } from "mentiq-sdk";function RecordingControls() {
const analytics = useAnalytics();
return (
{analytics.isRecordingActive() && ๐ด Recording Active}
);
}
`$3
`tsx
// Add CSS classes to protect sensitive data
type="password"
className="mentiq-block" // Completely block from recording
/>
Sensitive text content
This section won't be recorded
`$3
`tsx
import { SessionRecorder } from "mentiq-sdk";const recorder = new SessionRecorder(
analytics.config,
analytics.getSessionId(),
{
maxDuration: 10 60 1000, // 10 minutes
blockClass: "sensitive",
maskAllInputs: true,
sampling: {
mousemove: 50, // Sample every 50ms
scroll: 150, // Sample every 150ms
input: "last", // Only record final value
},
}
);
`Note: Recordings are automatically uploaded to
/api/v1/sessions/:session_id/recordings every 10 seconds. See SESSION-RECORDING.md for detailed documentation.๐ฑ Session Management
Rich session tracking includes:
- Session duration and activity
- Page views and navigation
- User interactions (clicks, scrolls)
- Scroll depth and engagement
- Activity/inactivity periods
๐ Next.js Integration
$3
`tsx
// app/layout.tsx
import { AnalyticsProvider } from "mentiq-sdk";export default function RootLayout({ children }) {
return (
{children}
);
}
`$3
`tsx
// pages/_app.tsx
import { AnalyticsProvider } from "mentiq-sdk";export default function App({ Component, pageProps }) {
return (
);
}
`๐ Example Use Cases
$3
`tsx
function ProductPage({ product }) {
const { track } = useAnalytics(); return (
event="product_viewed"
properties={{
product_id: product.id,
category: product.category,
price: product.price,
}}
>
);
}
`$3
`tsx
function BlogPost({ post }) {
return (
{post.title}
{post.content}
);
}
`๐ TypeScript Support
Full TypeScript support with comprehensive types:
`tsx
import type {
AnalyticsConfig,
EventProperties,
SessionData,
PerformanceData,
} from "mentiq-sdk";const config: AnalyticsConfig = {
apiKey: "key",
enableHeatmapTracking: true,
};
`๐ API Reference
$3
`tsx
// Core tracking
analytics.track(event: string, properties?: EventProperties)
analytics.page(properties?: PageProperties)
analytics.identify(userId: string, traits?: UserProperties)// Queue management
analytics.flush(): Promise
analytics.getQueueSize(): number
analytics.clearQueue(): void
// Advanced tracking
analytics.trackCustomError(error: string | Error, properties?: EventProperties)
analytics.trackPerformance(data: PerformanceData)
`โ
Quick Start Checklist
$3
- [ ] Install SDK:
npm install mentiq-sdk
- [ ] Wrap app with
- [ ] Add your API key and project ID
- [ ] Verify events in your dashboard$3
- [ ] Import
OnboardingTracker or useOnboardingTracker
- [ ] Define your onboarding steps configuration
- [ ] Call tracker.start() when onboarding begins
- [ ] Add tracker.completeStep() calls at completion points
- [ ] View funnel analytics in dashboard
- [ ] See examples/onboarding-tracking.tsx for full examples$3
- [ ] Install rrweb:
npm install rrweb
- [ ] Enable enableSessionRecording: true
- [ ] Add privacy CSS classes to sensitive elements
- [ ] Test recording start/stop
- [ ] Verify uploads to backend endpoint$3
- [ ] Add
.mentiq-block to password inputs
- [ ] Add .mentiq-mask to sensitive text
- [ ] Add .mentiq-ignore to private sections
- [ ] Implement user consent if required
- [ ] Review and test privacy settings$3
- [ ] Configure appropriate batch sizes
- [ ] Set reasonable flush intervals
- [ ] Adjust sampling rates for performance
- [ ] Set max session duration
- [ ] Test error handling and retries
See SESSION-RECORDING.md for detailed setup instructions.
๐ Publishing
To publish the SDK:
`bash
npm run build
npm run test
npm publish
``MIT License - Free for personal and commercial use.
- ๐ Documentation
- ๐ Issues
- ๐ฌ Discussions