Skip to main content

TypeScript Support

MentiQ Analytics SDK is built with TypeScript and provides comprehensive type definitions for all features. This guide covers all the types, interfaces, and type-safe patterns you’ll use.

Core Configuration

AnalyticsConfig

The main configuration interface for initializing the Analytics SDK:
interface AnalyticsConfig {
  // Required
  apiKey: string;                    // Your MentiQ API key
  projectId: string;                 // Your MentiQ project ID

  // Optional - Connection
  endpoint?: string;                 // Default: "https://api.mentiq.io"
  debug?: boolean;                   // Enable console logging (default: false)

  // Optional - User & Session
  userId?: string;                   // Set initial user ID
  sessionTimeout?: number;           // Session timeout in ms (default: 30 min)

  // Optional - Batching & Queuing
  batchSize?: number;                // Events per batch (default: 20)
  flushInterval?: number;            // Auto-flush interval in ms (default: 10s)
  maxQueueSize?: number;             // Max queued events (default: 1000)
  retryAttempts?: number;            // Failed request retries (default: 3)
  retryDelay?: number;               // Retry delay in ms (default: 1000)

  // Optional - Automatic Tracking
  enableAutoPageTracking?: boolean;       // Auto-track page views (default: true)
  enablePerformanceTracking?: boolean;    // Track performance metrics
  enableHeatmapTracking?: boolean;        // Track clicks and hovers
  enableSessionRecording?: boolean;       // Enable session replay
  enableErrorTracking?: boolean;          // Auto-track errors

  // Optional - A/B Testing
  enableABTesting?: boolean;              // Enable A/B testing
  abTestConfig?: ABTestConfig;            // A/B test configuration
}

Usage Example

import { Analytics, AnalyticsConfig } from "mentiq-sdk";

const config: AnalyticsConfig = {
  apiKey: "pk_live_1234567890",
  projectId: "proj_abc123",
  endpoint: "https://analytics.myapp.com",
  debug: process.env.NODE_ENV === "development",
  
  // Batching configuration
  batchSize: 25,
  flushInterval: 5000,
  maxQueueSize: 500,
  
  // Feature flags
  enableAutoPageTracking: true,
  enablePerformanceTracking: true,
  enableErrorTracking: true,
};

const analytics = new Analytics(config);

Event Types

EventProperties

Base type for all event properties:
interface EventProperties {
  [key: string]: string | number | boolean | null | undefined;
}

PageProperties

Properties for page view events:
interface PageProperties {
  title?: string;        // Page title
  url?: string;          // Full URL
  path?: string;         // URL path
  referrer?: string;     // Referrer URL
  search?: string;       // Query string
}
Example:
import { useAnalytics } from "mentiq-sdk";
import type { PageProperties } from "mentiq-sdk";

function MyComponent() {
  const { page } = useAnalytics();

  const trackPage = () => {
    const properties: PageProperties = {
      title: "Product Details",
      url: window.location.href,
      path: "/products/123",
      referrer: document.referrer,
    };
    page(properties);
  };
}

UserProperties

Properties for user identification:
interface UserProperties {
  subscription?: SubscriptionProperties;  // User subscription data
  [key: string]:                         // Any custom properties
    | string
    | number
    | boolean
    | null
    | undefined
    | SubscriptionProperties;
}
Example:
import type { UserProperties } from "mentiq-sdk";

const userTraits: UserProperties = {
  email: "[email protected]",
  name: "John Doe",
  plan: "premium",
  company: "Acme Inc",
  created_at: "2024-01-15",
};

analytics.identify("user_123", userTraits);

Subscription Tracking Types

SubscriptionProperties

Comprehensive subscription data structure:
interface SubscriptionProperties {
  // Status & Plan
  status:
    | "active"
    | "trialing"
    | "past_due"
    | "canceled"
    | "paused"
    | "incomplete"
    | "incomplete_expired"
    | "unpaid";
  plan_id?: string;
  plan_name?: string;
  plan_tier?: string;              // e.g., "free", "starter", "pro"

  // Pricing (in cents)
  mrr?: number;                    // Monthly Recurring Revenue
  arr?: number;                    // Annual Recurring Revenue
  ltv?: number;                    // Lifetime Value
  currency?: string;               // e.g., "usd", "eur"

  // Billing Cycle
  billing_interval?: "day" | "week" | "month" | "year";
  billing_cycle_anchor?: string;   // ISO date
  current_period_start?: string;   // ISO date
  current_period_end?: string;     // ISO date

  // Trial
  trial_start?: string;            // ISO date
  trial_end?: string;              // ISO date
  is_trial?: boolean;

  // Payment (PCI-safe)
  payment_method_type?: string;    // e.g., "card", "bank_account"
  payment_method_last4?: string;   // Last 4 digits only
  payment_method_brand?: string;   // e.g., "visa", "mastercard"

  // Cancellation
  cancel_at_period_end?: boolean;
  canceled_at?: string;            // ISO date
  cancellation_reason?: string;

  // Provider Info
  provider?: "stripe" | "paddle" | "chargebee" | "manual" | string;
  provider_customer_id?: string;
  provider_subscription_id?: string;

  // Metadata
  created_at?: string;             // ISO date
  updated_at?: string;             // ISO date

  // Custom fields
  [key: string]: string | number | boolean | null | undefined;
}
Example:
import type { SubscriptionProperties } from "mentiq-sdk";

const subscription: SubscriptionProperties = {
  status: "active",
  plan_id: "price_premium_monthly",
  plan_name: "Premium Plan",
  plan_tier: "premium",
  mrr: 2900,  // $29.00 in cents
  currency: "usd",
  billing_interval: "month",
  current_period_start: "2024-01-01T00:00:00Z",
  current_period_end: "2024-02-01T00:00:00Z",
  provider: "stripe",
  provider_subscription_id: "sub_1234567890",
  payment_method_type: "card",
  payment_method_last4: "4242",
  payment_method_brand: "visa",
};

analytics.identify("user_123", { subscription });

PaymentEventProperties

Properties for payment events:
interface PaymentEventProperties extends EventProperties {
  amount?: number;                              // Payment amount
  currency?: string;                            // Currency code
  payment_status?: "succeeded" | "failed" | "pending" | "refunded";
  failure_reason?: string;                      // Reason for failure
  invoice_id?: string;                          // Invoice identifier
  charge_id?: string;                           // Charge identifier
}
Example:
import type { PaymentEventProperties } from "mentiq-sdk";

const paymentEvent: PaymentEventProperties = {
  amount: 2900,
  currency: "usd",
  payment_status: "succeeded",
  invoice_id: "inv_123",
  charge_id: "ch_456",
};

analytics.trackPaymentSucceeded(paymentEvent);

ChurnRiskMetrics

Churn risk analysis result:
interface ChurnRiskMetrics {
  risk_score: number;                          // 0-100
  risk_category: "low" | "medium" | "high" | "critical";
  factors: {
    engagement_score?: number;
    days_since_last_active?: number;
    feature_adoption_rate?: number;
    support_tickets?: number;
    negative_feedback_count?: number;
    payment_failures?: number;
  };
  predicted_churn_date?: string;               // ISO date
  intervention_recommended?: boolean;
}
Example:
const churnRisk = analytics.calculateChurnRisk();

if (churnRisk.risk_category === "high" || churnRisk.risk_category === "critical") {
  // Trigger intervention campaign
  triggerRetentionCampaign(churnRisk);
}

Session Types

SessionData

Real-time session tracking data:
interface SessionData {
  sessionId?: string;              // Session identifier
  startTime: number;               // Session start timestamp
  endTime?: number;                // Session end timestamp
  duration?: number;               // Duration in milliseconds
  pageViews: number;               // Number of page views
  clicks: number;                  // Number of clicks
  scrollDepth: number;             // Current scroll depth %
  maxScrollDepth: number;          // Maximum scroll depth %
  isActive: boolean;               // Is session currently active
  events: string[];                // List of event names
  scrollEvents?: number;           // Number of scroll events
  clickEvents?: number;            // Number of click events
  pageChanges?: number;            // Number of page changes
  engagementScore?: number;        // Engagement score (0-100)
  bounceLikelihood?: number;       // Bounce likelihood % (0-100)
  channel?: string;                // Traffic source channel
}
Example:
import { useSessionTracking } from "mentiq-sdk";
import type { SessionData } from "mentiq-sdk";

function SessionMonitor() {
  const { sessionData } = useSessionTracking();

  const renderEngagement = (data: SessionData) => {
    const score = data.engagementScore || 0;
    return (
      <div>
        <p>Engagement: {score.toFixed(0)}%</p>
        <p>Page Views: {data.pageViews}</p>
        <p>Scroll Depth: {data.maxScrollDepth}%</p>
      </div>
    );
  };

  return sessionData ? renderEngagement(sessionData) : null;
}

Performance Types

PerformanceData

Core Web Vitals and performance metrics:
interface PerformanceData {
  loadTime?: number;                    // Total page load time
  domReady?: number;                    // DOM ready time
  firstPaint?: number;                  // First Paint (FP)
  firstContentfulPaint?: number;        // First Contentful Paint (FCP)
  largestContentfulPaint?: number;      // Largest Contentful Paint (LCP)
  firstInputDelay?: number;             // First Input Delay (FID)
  cumulativeLayoutShift?: number;       // Cumulative Layout Shift (CLS)
  timeToInteractive?: number;           // Time to Interactive (TTI)
}
Example:
import type { PerformanceData } from "mentiq-sdk";

const perfData: PerformanceData = {
  loadTime: 1250,
  firstContentfulPaint: 800,
  largestContentfulPaint: 1200,
  firstInputDelay: 50,
  cumulativeLayoutShift: 0.05,
};

analytics.trackPerformance(perfData);

Error Tracking Types

ErrorData

Error information structure:
interface ErrorData {
  message: string;                     // Error message
  stack?: string;                      // Stack trace
  filename?: string;                   // File where error occurred
  lineno?: number;                     // Line number
  colno?: number;                      // Column number
  type: "javascript"                   // Error type
      | "unhandledrejection"
      | "network"
      | "custom";
}
Example:
import { useAnalytics } from "mentiq-sdk";
import type { ErrorData } from "mentiq-sdk";

function MyComponent() {
  const { trackCustomError } = useAnalytics();

  const handleError = (error: Error) => {
    trackCustomError(error, {
      component: "MyComponent",
      action: "data_fetch",
      severity: "high",
    });
  };
}

Heatmap Types

HeatmapData

User interaction data for heatmaps:
interface HeatmapData {
  x: number;                          // X coordinate
  y: number;                          // Y coordinate
  element?: string;                   // Element tag name
  selector?: string;                  // CSS selector
  action: "click" | "move" | "scroll"; // Interaction type
  viewport: {
    width: number;                    // Viewport width
    height: number;                   // Viewport height
  };
}

Analytics Instance Type

AnalyticsInstance

Complete interface for the Analytics class:
interface AnalyticsInstance {
  // Core tracking
  track: (event: string, properties?: EventProperties) => void;
  page: (properties?: PageProperties) => void;
  identify: (
    userId: string,
    traits?: UserProperties & { email?: string; subscription?: SubscriptionProperties }
  ) => void;
  alias: (newId: string, previousId?: string) => void;
  reset: () => void;
  flush: () => Promise<void>;

  // User & Session
  setUserId: (userId: string) => void;
  getUserId: () => string | null;
  getAnonymousId: () => string;
  getSessionId: () => string;
  getSessionData: () => SessionData;
  getActiveSession: () => SessionData;
  calculateEngagementScore: () => number;

  // Queue management
  getQueueSize: () => number;
  clearQueue: () => void;

  // Error tracking
  trackCustomError: (error: string | Error, properties?: EventProperties) => void;

  // Performance
  trackPerformance: (performanceData: PerformanceData) => void;

  // Feature tracking
  trackFeatureUsage: (featureName: string, properties?: EventProperties) => void;

  // Funnel tracking
  trackFunnelStep: (
    funnelName: string,
    stepName: string,
    stepIndex: number,
    properties?: EventProperties
  ) => void;
  completeFunnel: (funnelName: string, properties?: EventProperties) => void;
  startFunnel: (funnelName: string, properties?: EventProperties) => void;
  advanceFunnel: (
    funnelName: string,
    stepName: string,
    properties?: EventProperties
  ) => void;
  abandonFunnel: (
    funnelName: string,
    reason?: string,
    properties?: EventProperties
  ) => void;
  getFunnelState: (funnelName: string) => FunnelState | undefined;

  // Session recording
  startRecording: () => void;
  stopRecording: () => void;
  pauseRecording: () => void;
  resumeRecording: () => void;
  isRecordingActive: () => boolean;

  // Subscription tracking
  trackSubscription: (
    eventName: string,
    properties?: SubscriptionProperties & EventProperties
  ) => void;
  trackSubscriptionStarted: (properties: SubscriptionProperties) => void;
  trackSubscriptionUpgraded: (
    properties: SubscriptionProperties & { previous_plan?: string }
  ) => void;
  trackSubscriptionDowngraded: (
    properties: SubscriptionProperties & { previous_plan?: string }
  ) => void;
  trackSubscriptionCanceled: (
    properties: SubscriptionProperties & { cancellation_reason?: string }
  ) => void;
  trackSubscriptionPaused: (properties: SubscriptionProperties) => void;
  trackSubscriptionReactivated: (properties: SubscriptionProperties) => void;
  trackTrialStarted: (properties: SubscriptionProperties) => void;
  trackTrialConverted: (properties: SubscriptionProperties) => void;
  trackTrialExpired: (properties: SubscriptionProperties) => void;
  trackPaymentFailed: (properties: PaymentEventProperties) => void;
  trackPaymentSucceeded: (properties: PaymentEventProperties) => void;

  // Churn analysis
  calculateChurnRisk: () => ChurnRiskMetrics;
  getSubscriptionData: () => SubscriptionProperties | null;

  // Configuration
  config: AnalyticsConfig;
}

A/B Testing Types

Experiment

interface Experiment {
  id: string;
  name: string;
  description?: string;
  key: string;
  status: "DRAFT" | "RUNNING" | "PAUSED" | "COMPLETED" | "ARCHIVED";
  trafficSplit: number;
  startDate?: string;
  endDate?: string;
  createdAt: string;
  updatedAt: string;
  variants: Variant[];
}

Variant

interface Variant {
  id: string;
  name: string;
  key: string;
  description?: string;
  isControl: boolean;
  trafficSplit: number;
  createdAt: string;
  updatedAt: string;
}

ExperimentAssignment

interface ExperimentAssignment {
  experimentId: string;
  variantId: string;
  variantKey: string;
  variantName: string;
  isControl: boolean;
  assignedAt: string;
  experiment?: Experiment;
}

Type Guards

Create type-safe helpers for runtime type checking:
import type { SubscriptionProperties, PaymentEventProperties } from "mentiq-sdk";

function isActiveSubscription(
  sub: SubscriptionProperties
): sub is SubscriptionProperties & { status: "active" } {
  return sub.status === "active";
}

function isPaymentSuccess(
  payment: PaymentEventProperties
): payment is PaymentEventProperties & { payment_status: "succeeded" } {
  return payment.payment_status === "succeeded";
}

// Usage
const subscription = analytics.getSubscriptionData();
if (subscription && isActiveSubscription(subscription)) {
  // TypeScript knows status is "active" here
  console.log("User has active subscription");
}

Generic Event Typing

Create strongly-typed custom events:
import type { EventProperties } from "mentiq-sdk";

interface ProductViewEvent extends EventProperties {
  product_id: string;
  product_name: string;
  category: string;
  price: number;
  currency: string;
}

interface AddToCartEvent extends EventProperties {
  product_id: string;
  quantity: number;
  price: number;
}

// Type-safe tracking
function trackProductView(event: ProductViewEvent) {
  analytics.track("product_viewed", event);
}

trackProductView({
  product_id: "prod_123",
  product_name: "Premium Widget",
  category: "widgets",
  price: 29.99,
  currency: "usd",
});

Utility Types

Useful type utilities for common patterns:
import type { EventProperties, AnalyticsConfig } from "mentiq-sdk";

// Partial config for updates
type PartialConfig = Partial<AnalyticsConfig>;

// Required event properties
type RequiredEventProps<T extends EventProperties> = {
  [K in keyof T]-?: T[K];
};

// Event with metadata
type EventWithMetadata<T extends EventProperties = EventProperties> = T & {
  _timestamp: number;
  _userId?: string;
  _sessionId: string;
};

Next Steps

Next.js Integration

Integrate with Next.js App and Pages Router

Event Batching

Learn about the queuing and batching system

Build docs developers (and LLMs) love