Skip to main content

Constructor

Creates a new Analytics instance with the provided configuration.
new Analytics(config: AnalyticsConfig)
config
AnalyticsConfig
required
Configuration object for the Analytics instance

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
event
string
required
Name of the event to track
properties
EventProperties
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
properties
PageProperties
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
userId
string
required
Unique identifier for the user
traits
UserProperties
User traits and properties

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
newId
string
required
New user ID
previousId
string
Previous user ID (defaults to current user ID)

Example

analytics.alias('user-123');

reset

Reset the analytics state, clearing user ID and event queue.
analytics.reset(): void

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
return
ChurnRiskMetrics

Funnel Tracking

startFunnel

Start tracking a conversion funnel.
analytics.startFunnel(funnelName: string, properties?: EventProperties): void
funnelName
string
required
Name of the funnel
properties
EventProperties
Additional properties

Example

analytics.startFunnel('checkout');

advanceFunnel

Advance to the next step in a funnel.
analytics.advanceFunnel(
  funnelName: string,
  stepName: string,
  properties?: EventProperties
): void
funnelName
string
required
Name of the funnel
stepName
string
required
Name of the current step
properties
EventProperties
Additional properties

Example

analytics.advanceFunnel('checkout', 'shipping_info');
analytics.advanceFunnel('checkout', 'payment_info');

completeFunnel

Mark a funnel as completed.
analytics.completeFunnel(funnelName: string, properties?: EventProperties): void
funnelName
string
required
Name of the funnel
properties
EventProperties
Additional properties

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
funnelName
string
required
Name of the funnel
reason
string
Reason for abandonment
properties
EventProperties
Additional properties

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
return
object | undefined

Session & Engagement

getSessionData

Get the current session data.
analytics.getSessionData(): SessionData
return
SessionData

getActiveSession

Get detailed session metrics with real-time calculations.
analytics.getActiveSession(): SessionData
return
SessionData
Same as getSessionData but with updated real-time metrics

calculateEngagementScore

Calculate the current engagement score based on user activity.
analytics.calculateEngagementScore(): number
return
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
featureName
string
required
Name of the feature
properties
EventProperties
Additional properties

Example

analytics.trackFeatureUsage('export_data', {
  format: 'csv',
  rows: 1000
});

trackCustomError

Track a custom error.
analytics.trackCustomError(
  error: string | Error,
  properties?: EventProperties
): void
error
string | Error
required
Error message or Error object
properties
EventProperties
Additional properties

Example

try {
  // some code
} catch (error) {
  analytics.trackCustomError(error, {
    context: 'data_processing'
  });
}

trackPerformance

Track custom performance metrics.
analytics.trackPerformance(performanceData: PerformanceData): void
performanceData
PerformanceData
required
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
return
boolean
True if recording is active, false otherwise

User & Session IDs

setUserId

Set the user ID.
analytics.setUserId(userId: string): void
userId
string
required
User ID to set

getUserId

Get the current user ID.
analytics.getUserId(): string | null
return
string | null
Current user ID or null if not set

getAnonymousId

Get the anonymous ID.
analytics.getAnonymousId(): string
return
string
Anonymous ID (generated automatically)

getSessionId

Get the current session ID.
analytics.getSessionId(): string
return
string
Current session ID

Queue Management

flush

Manually flush the event queue to send all pending events.
analytics.flush(): Promise<void>
return
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
return
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

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();

Build docs developers (and LLMs) love