Constructor
Creates a new Analytics instance with the provided configuration.
new Analytics(config: AnalyticsConfig)
Configuration object for the Analytics instance
endpoint
string
default:"https://api.mentiq.io"
API endpoint URL
Session timeout in milliseconds (default: 30 minutes)
Number of events to batch before auto-flushing
Auto-flush interval in milliseconds (default: 10 seconds)
Automatically track page views
enablePerformanceTracking
Track page performance metrics
Maximum number of events to queue
Number of retry attempts for failed events
Delay between retries in milliseconds
Example
import { Analytics } from 'mentiq-sdk';
const analytics = new Analytics({
apiKey: 'your-api-key',
projectId: 'your-project-id',
debug: true,
enableAutoPageTracking: true,
enableSessionRecording: true
});
Core Tracking Methods
track
Track a custom event with optional properties.
analytics.track(event: string, properties?: EventProperties): void
Name of the event to track
Additional properties to attach to the event
Example
analytics.track('button_clicked', {
button_id: 'signup',
page: 'home'
});
page
Track a page view with optional properties.
analytics.page(properties?: PageProperties): void
Additional properties to attach to the page view
Example
analytics.page({
name: 'Product Details',
category: 'ecommerce',
product_id: '12345'
});
identify
Identify a user with traits and optional subscription data.
analytics.identify(userId: string, traits?: UserProperties & {
email?: string;
subscription?: SubscriptionProperties;
}): void
Unique identifier for the user
User traits and properties
User subscription information
Example
analytics.identify('user-123', {
email: '[email protected]',
name: 'John Doe',
plan: 'premium',
subscription: {
plan_name: 'Pro',
status: 'active',
mrr: 99
}
});
alias
Alias a user ID to another ID (e.g., anonymous to authenticated).
analytics.alias(newId: string, previousId?: string): void
Previous user ID (defaults to current user ID)
Example
analytics.alias('user-123');
reset
Reset the analytics state, clearing user ID and event queue.
Example
// On user logout
analytics.reset();
Subscription Tracking
trackSubscriptionStarted
Track when a subscription starts.
analytics.trackSubscriptionStarted(properties: SubscriptionProperties): void
properties
SubscriptionProperties
required
Subscription properties
Example
analytics.trackSubscriptionStarted({
plan_name: 'Pro',
plan_tier: 'premium',
status: 'active',
mrr: 99,
billing_interval: 'month',
provider: 'stripe'
});
trackSubscriptionUpgraded
Track when a subscription is upgraded.
analytics.trackSubscriptionUpgraded(
properties: SubscriptionProperties & { previous_plan?: string }
): void
trackSubscriptionDowngraded
Track when a subscription is downgraded.
analytics.trackSubscriptionDowngraded(
properties: SubscriptionProperties & { previous_plan?: string }
): void
trackSubscriptionCanceled
Track when a subscription is canceled.
analytics.trackSubscriptionCanceled(
properties: SubscriptionProperties & { cancellation_reason?: string }
): void
trackSubscriptionPaused
Track when a subscription is paused.
analytics.trackSubscriptionPaused(properties: SubscriptionProperties): void
trackSubscriptionReactivated
Track when a subscription is reactivated.
analytics.trackSubscriptionReactivated(properties: SubscriptionProperties): void
trackTrialStarted
Track when a trial starts.
analytics.trackTrialStarted(properties: SubscriptionProperties): void
trackTrialConverted
Track when a trial converts to a paid subscription.
analytics.trackTrialConverted(properties: SubscriptionProperties): void
trackTrialExpired
Track when a trial expires.
analytics.trackTrialExpired(properties: SubscriptionProperties): void
trackPaymentFailed
Track when a payment fails.
analytics.trackPaymentFailed(properties: PaymentEventProperties): void
trackPaymentSucceeded
Track when a payment succeeds.
analytics.trackPaymentSucceeded(properties: PaymentEventProperties): void
getSubscriptionData
Get stored subscription data from localStorage.
analytics.getSubscriptionData(): SubscriptionProperties | null
return
SubscriptionProperties | null
Subscription data if available, null otherwise
calculateChurnRisk
Calculate churn risk based on user engagement and behavior.
analytics.calculateChurnRisk(): ChurnRiskMetrics
risk_category
'low' | 'medium' | 'high' | 'critical'
Risk category
Contributing factors to the risk score
ISO date string of predicted churn (if high risk)
Whether intervention is recommended
Funnel Tracking
startFunnel
Start tracking a conversion funnel.
analytics.startFunnel(funnelName: string, properties?: EventProperties): void
Example
analytics.startFunnel('checkout');
advanceFunnel
Advance to the next step in a funnel.
analytics.advanceFunnel(
funnelName: string,
stepName: string,
properties?: EventProperties
): void
Example
analytics.advanceFunnel('checkout', 'shipping_info');
analytics.advanceFunnel('checkout', 'payment_info');
completeFunnel
Mark a funnel as completed.
analytics.completeFunnel(funnelName: string, properties?: EventProperties): void
Example
analytics.completeFunnel('checkout', {
order_id: '12345',
total: 99.99
});
abandonFunnel
Mark a funnel as abandoned.
analytics.abandonFunnel(
funnelName: string,
reason?: string,
properties?: EventProperties
): void
Example
analytics.abandonFunnel('checkout', 'payment_failed');
trackFunnelStep
Track a specific funnel step.
analytics.trackFunnelStep(
funnelName: string,
stepName: string,
stepIndex: number,
properties?: EventProperties
): void
getFunnelState
Get the current state of a funnel.
analytics.getFunnelState(funnelName: string): any
Timestamp when funnel started
Array of completed step names
Whether funnel is currently active
Time spent in funnel (milliseconds)
Session & Engagement
getSessionData
Get the current session data.
analytics.getSessionData(): SessionData
Session duration in milliseconds
Current scroll depth percentage
Maximum scroll depth reached
Whether session is active
Calculated engagement score (0-100)
Bounce likelihood percentage (0-100)
Traffic channel (direct, organic, paid, etc.)
getActiveSession
Get detailed session metrics with real-time calculations.
analytics.getActiveSession(): SessionData
Same as getSessionData but with updated real-time metrics
calculateEngagementScore
Calculate the current engagement score based on user activity.
analytics.calculateEngagementScore(): number
Engagement score from 0-100
Example
const score = analytics.calculateEngagementScore();
if (score < 30) {
// Show engagement prompt
}
Feature & Error Tracking
trackFeatureUsage
Track usage of a specific feature.
analytics.trackFeatureUsage(featureName: string, properties?: EventProperties): void
Example
analytics.trackFeatureUsage('export_data', {
format: 'csv',
rows: 1000
});
trackCustomError
Track a custom error.
analytics.trackCustomError(
error: string | Error,
properties?: EventProperties
): void
Error message or Error object
Example
try {
// some code
} catch (error) {
analytics.trackCustomError(error, {
context: 'data_processing'
});
}
Track custom performance metrics.
analytics.trackPerformance(performanceData: PerformanceData): void
Performance metrics object
Session Recording
startRecording
Start session recording.
analytics.startRecording(): void
Example
analytics.startRecording();
stopRecording
Stop session recording.
analytics.stopRecording(): void
pauseRecording
Pause session recording.
analytics.pauseRecording(): void
resumeRecording
Resume session recording.
analytics.resumeRecording(): void
isRecordingActive
Check if recording is currently active.
analytics.isRecordingActive(): boolean
True if recording is active, false otherwise
User & Session IDs
setUserId
Set the user ID.
analytics.setUserId(userId: string): void
getUserId
Get the current user ID.
analytics.getUserId(): string | null
Current user ID or null if not set
getAnonymousId
Get the anonymous ID.
analytics.getAnonymousId(): string
Anonymous ID (generated automatically)
getSessionId
Get the current session ID.
analytics.getSessionId(): string
Queue Management
flush
Manually flush the event queue to send all pending events.
analytics.flush(): Promise<void>
Promise that resolves when flush is complete
Example
// Before page unload
await analytics.flush();
getQueueSize
Get the current number of events in the queue.
analytics.getQueueSize(): number
Number of events in queue
clearQueue
Clear all events from the queue.
analytics.clearQueue(): void
Provider Management
addProvider
Add a custom analytics provider.
analytics.addProvider(provider: AnalyticsProvider): void
provider
AnalyticsProvider
required
Track function that receives events
Example
analytics.addProvider({
name: 'custom',
track: (event) => {
console.log('Custom tracking:', event);
}
});
Lifecycle
destroy
Clean up and destroy the analytics instance.
analytics.destroy(): void
Example
// On app unmount
analytics.destroy();