npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

insightpro-ai-sdk-js

v1.0.0

Published

Official JavaScript/TypeScript SDK for InsightPro Analytics Platform - Track user behavior, analytics events, conversions, and revenue with powerful auto-capture capabilities

Readme

InsightPro JavaScript SDK

The official JavaScript/TypeScript SDK for InsightPro Analytics Platform. Track user behavior, analytics events, conversions, and revenue across web applications with powerful auto-capture capabilities.

Features

  • Full API Coverage: All analytics methods (track, page, identify, alias, group, revenue, conversions)
  • Auto-Capture: Automatic tracking of page views, clicks, form submissions, scroll depth, and time on page
  • Session Management: Automatic session tracking with configurable timeout
  • Event Batching: Efficient batching with configurable size and interval (default: 10 events or 30 seconds)
  • Retry Logic: Automatic retry on network failures with exponential backoff
  • Offline Queue: Queue events when offline, automatically send when connection restored
  • Privacy First: Respect Do Not Track, GDPR compliant, opt-out support
  • TypeScript Support: Full TypeScript types and interfaces included
  • Lightweight: < 10KB gzipped, zero dependencies
  • Framework Agnostic: Works with React, Vue, Angular, Next.js, or vanilla JavaScript
  • Tree-Shakeable: Import only what you need
  • Source Maps: Included for easier debugging

Installation

NPM

npm install @insightpro/sdk-js

Yarn

yarn add @insightpro/sdk-js

pnpm

pnpm add @insightpro/sdk-js

CDN

<!-- Latest version -->
<script src="https://cdn.jsdelivr.net/npm/@insightpro/sdk-js/dist/insightpro.umd.js"></script>

<!-- Specific version -->
<script src="https://cdn.jsdelivr.net/npm/@insightpro/[email protected]/dist/insightpro.umd.js"></script>

Quick Start

Initialize SDK

import InsightPro from '@insightpro/sdk-js';

const analytics = new InsightPro({
  endpoint: 'https://api.insightpro.com',
  tenantId: 'your-tenant-id',
  apiKey: 'your-api-key', // Optional
  debug: true, // Enable debug logging in development
});

Track Events

// Track a custom event
analytics.track('user_action', {
  action: 'button_click',
  buttonName: 'Subscribe',
  location: 'header',
});

API Reference

Initialization

new InsightPro(config: InsightProConfig)

Configuration Options

| Option | Type | Default | Description | |--------|------|---------|-------------| | endpoint | string | required | API endpoint URL | | tenantId | string | required | Your tenant identifier | | apiKey | string | undefined | API key for authentication | | debug | boolean | false | Enable debug logging | | batchSize | number | 10 | Number of events to batch before sending | | batchInterval | number | 30000 | Time in ms to wait before sending batch | | autoTrackPageViews | boolean | true | Automatically track page views | | autoTrackClicks | boolean | false | Automatically track clicks on links/buttons | | autoTrackErrors | boolean | true | Automatically track JavaScript errors | | autoTrackForms | boolean | false | Automatically track form submissions | | autoTrackScrollDepth | boolean | false | Track scroll depth (25%, 50%, 75%, 100%) | | autoTrackTimeOnPage | boolean | false | Track time spent on page | | enableSessions | boolean | true | Enable automatic session tracking | | sessionTimeout | number | 1800000 | Session timeout in ms (default: 30 min) | | globalProperties | object | {} | Properties to include with every event | | retryFailedRequests | boolean | true | Retry failed network requests | | maxRetries | number | 3 | Maximum number of retry attempts | | respectDNT | boolean | true | Respect Do Not Track browser setting | | offlineQueue | boolean | true | Queue events when offline | | maxQueueSize | number | 100 | Maximum number of queued events |

Core Methods

track(eventName, properties, context?)

Track a custom event with properties.

analytics.track('button_click', {
  buttonName: 'Get Started',
  location: 'hero',
  variant: 'primary',
});

identify(userId, traits?)

Identify a user and associate them with traits.

analytics.identify('user-123', {
  email: '[email protected]',
  name: 'John Doe',
  plan: 'premium',
  company: 'Acme Inc',
  createdAt: '2025-01-01T00:00:00Z',
});

page(pageName?, properties?)

Track a page view with optional category and properties.

analytics.page('Home', {
  category: 'Marketing',
  path: '/',
  title: 'Welcome to InsightPro',
});

alias(userId, previousId?)

Associate one user ID with another (e.g., merge anonymous and identified users).

// When user signs up, merge anonymous session with new user ID
analytics.alias('user-123'); // previousId defaults to current anonymousId

// Or explicitly specify previous ID
analytics.alias('user-123', 'anonymous-456');

group(groupId, traits?)

Associate the current user with a group (e.g., company, organization).

analytics.group('company-456', {
  name: 'Acme Corporation',
  plan: 'enterprise',
  industry: 'Technology',
  employees: 500,
});

trackRevenue(amount, currency, properties?)

Track revenue events.

analytics.trackRevenue(99.99, 'USD', {
  productId: 'prod-123',
  productName: 'Premium Plan',
  category: 'Subscription',
  paymentMethod: 'credit_card',
});

trackConversion(conversionType, value, properties?)

Track conversion events (signups, trials, purchases, etc.).

analytics.trackConversion('trial_signup', 1, {
  currency: 'USD',
  source: 'landing_page',
  campaign: 'summer_2025',
});

E-commerce Methods

trackEcommerce(properties)

Track e-commerce events (view, add_to_cart, purchase, etc.).

// Product view
analytics.trackEcommerce({
  action: 'view_item',
  productId: 'prod-123',
  productName: 'Awesome Product',
  productSku: 'SKU-123',
  price: 99.99,
  currency: 'USD',
  productCategory: 'Electronics',
});

// Add to cart
analytics.trackEcommerce({
  action: 'add_to_cart',
  productId: 'prod-123',
  productName: 'Awesome Product',
  quantity: 2,
  price: 99.99,
  currency: 'USD',
});

// Purchase
analytics.trackEcommerce({
  action: 'purchase',
  orderId: 'order-789',
  revenue: 199.98,
  currency: 'USD',
  productId: 'prod-123',
  quantity: 2,
});

User Actions

trackAction(action, properties?)

Track user actions (clicks, form submissions, etc.).

analytics.trackAction('video_played', {
  videoId: 'video-123',
  videoTitle: 'Product Demo',
  duration: 180,
  percentageWatched: 75,
});

trackError(message, properties?)

Manually track errors.

try {
  // Your code
} catch (error) {
  analytics.trackError(error.message, {
    stack: error.stack,
    level: 'error',
    context: { userId: '123', action: 'checkout' },
  });
}

Utility Methods

flush()

Manually flush all pending events (useful before navigation).

// Flush before navigation
window.addEventListener('beforeunload', () => {
  analytics.flush();
});

reset()

Reset the SDK (clear user ID, reset session). Call on logout.

analytics.reset();

destroy()

Destroy the SDK instance and clean up event listeners.

analytics.destroy();

Auto-Capture Features

Page Views

Automatically tracks page views including SPA navigation (pushState, replaceState, popstate).

const analytics = new InsightPro({
  endpoint: 'https://api.insightpro.com',
  tenantId: 'your-tenant-id',
  autoTrackPageViews: true, // default: true
});

Clicks

Automatically tracks clicks on links and buttons.

const analytics = new InsightPro({
  endpoint: 'https://api.insightpro.com',
  tenantId: 'your-tenant-id',
  autoTrackClicks: true, // default: false
});

Form Submissions

Automatically tracks form submissions.

const analytics = new InsightPro({
  endpoint: 'https://api.insightpro.com',
  tenantId: 'your-tenant-id',
  autoTrackForms: true, // default: false
});

Scroll Depth

Tracks when users scroll to 25%, 50%, 75%, and 100% of page.

const analytics = new InsightPro({
  endpoint: 'https://api.insightpro.com',
  tenantId: 'your-tenant-id',
  autoTrackScrollDepth: true, // default: false
});

Time on Page

Tracks time spent on each page.

const analytics = new InsightPro({
  endpoint: 'https://api.insightpro.com',
  tenantId: 'your-tenant-id',
  autoTrackTimeOnPage: true, // default: false
});

JavaScript Errors

Automatically captures JavaScript errors and unhandled promise rejections.

const analytics = new InsightPro({
  endpoint: 'https://api.insightpro.com',
  tenantId: 'your-tenant-id',
  autoTrackErrors: true, // default: true
});

Framework Integration

React

// lib/analytics.js
import InsightPro from '@insightpro/sdk-js';

export const analytics = new InsightPro({
  endpoint: process.env.REACT_APP_ANALYTICS_ENDPOINT,
  tenantId: process.env.REACT_APP_TENANT_ID,
  debug: process.env.NODE_ENV === 'development',
});

// App.jsx
import { useEffect } from 'react';
import { analytics } from './lib/analytics';

function App() {
  useEffect(() => {
    analytics.identify('user-123', {
      email: '[email protected]',
      name: 'John Doe',
    });
  }, []);

  const handlePurchase = () => {
    analytics.trackRevenue(99.99, 'USD', {
      productId: 'prod-123',
      productName: 'Premium Plan',
    });
  };

  return <div>...</div>;
}

Next.js

// lib/analytics.ts
import InsightPro from '@insightpro/sdk-js';

export const analytics = new InsightPro({
  endpoint: process.env.NEXT_PUBLIC_ANALYTICS_ENDPOINT!,
  tenantId: process.env.NEXT_PUBLIC_TENANT_ID!,
  debug: process.env.NODE_ENV === 'development',
});

// app/layout.tsx
'use client';

import { useEffect } from 'react';
import { usePathname } from 'next/navigation';
import { analytics } from '@/lib/analytics';

export default function RootLayout({ children }) {
  const pathname = usePathname();

  useEffect(() => {
    analytics.page(pathname);
  }, [pathname]);

  return (
    <html>
      <body>{children}</body>
    </html>
  );
}

Vue 3

<!-- composables/useAnalytics.js -->
<script>
import InsightPro from '@insightpro/sdk-js';
import { onMounted, onBeforeUnmount } from 'vue';

const analytics = new InsightPro({
  endpoint: import.meta.env.VITE_ANALYTICS_ENDPOINT,
  tenantId: import.meta.env.VITE_TENANT_ID,
  debug: import.meta.env.DEV,
});

export function useAnalytics() {
  onMounted(() => {
    analytics.page();
  });

  onBeforeUnmount(() => {
    analytics.flush();
  });

  return {
    analytics,
    track: (event, props) => analytics.track(event, props),
    identify: (userId, traits) => analytics.identify(userId, traits),
  };
}
</script>

<!-- App.vue -->
<script setup>
import { useAnalytics } from './composables/useAnalytics';

const { track } = useAnalytics();

const handleClick = () => {
  track('button_click', { buttonName: 'CTA' });
};
</script>

TypeScript

import InsightPro, {
  InsightProConfig,
  UserTraits,
  GroupTraits,
  EcommerceEvent,
} from '@insightpro/sdk-js';

const config: InsightProConfig = {
  endpoint: 'https://api.insightpro.com',
  tenantId: 'your-tenant-id',
  debug: true,
  batchSize: 10,
  batchInterval: 30000,
};

const analytics = new InsightPro(config);

// Type-safe user traits
const userTraits: UserTraits = {
  email: '[email protected]',
  name: 'John Doe',
  plan: 'premium',
};

analytics.identify('user-123', userTraits);

// Type-safe ecommerce events
const purchaseEvent: EcommerceEvent['properties'] = {
  action: 'purchase',
  orderId: 'order-123',
  revenue: 99.99,
  currency: 'USD',
};

analytics.trackEcommerce(purchaseEvent);

Advanced Usage

Global Properties

Add properties to every event:

const analytics = new InsightPro({
  endpoint: 'https://api.insightpro.com',
  tenantId: 'your-tenant-id',
  globalProperties: {
    appVersion: '1.2.3',
    environment: 'production',
    buildNumber: '456',
  },
});

Custom Endpoints

Use different endpoints for different event types:

const analytics = new InsightPro({
  endpoint: 'https://api.insightpro.com',
  tenantId: 'your-tenant-id',
  customEndpoints: {
    track: 'https://custom-api.com/track',
    page: 'https://custom-api.com/page',
    identify: 'https://custom-api.com/identify',
  },
});

Event Batching

Control batching behavior:

const analytics = new InsightPro({
  endpoint: 'https://api.insightpro.com',
  tenantId: 'your-tenant-id',
  batchSize: 20, // Send after 20 events
  batchInterval: 60000, // Or after 60 seconds
});

Offline Queue

Events are automatically queued when offline and sent when connection is restored:

const analytics = new InsightPro({
  endpoint: 'https://api.insightpro.com',
  tenantId: 'your-tenant-id',
  offlineQueue: true, // default: true
  maxQueueSize: 200, // Maximum queued events
});

Privacy & GDPR

Do Not Track

By default, the SDK respects the Do Not Track browser setting:

const analytics = new InsightPro({
  endpoint: 'https://api.insightpro.com',
  tenantId: 'your-tenant-id',
  respectDNT: true, // default: true
});

Opt-Out

Implement user opt-out:

// Check if user has opted out
const hasOptedOut = localStorage.getItem('analytics_opt_out') === 'true';

if (!hasOptedOut) {
  const analytics = new InsightPro({
    endpoint: 'https://api.insightpro.com',
    tenantId: 'your-tenant-id',
  });
}

// Opt-out function
function optOut() {
  localStorage.setItem('analytics_opt_out', 'true');
  analytics.destroy();
}

// Opt-in function
function optIn() {
  localStorage.removeItem('analytics_opt_out');
  // Reinitialize SDK
}

Best Practices

  1. Initialize Once: Create a single SDK instance and export it for use across your app
  2. Use Environment Variables: Store endpoint and tenant ID in environment variables
  3. Enable Debug in Development: Set debug: true in development for easier debugging
  4. Flush on Navigation: Call flush() before navigation to ensure events are sent
  5. Reset on Logout: Call reset() when users log out to clear user data
  6. Batch Wisely: Adjust batchSize and batchInterval based on your traffic
  7. Use TypeScript: Leverage TypeScript types for type-safe tracking
  8. Global Properties: Use global properties for common metadata (app version, etc.)
  9. Error Handling: Enable auto-error tracking in production
  10. Privacy First: Respect user privacy with DNT and opt-out support

Troubleshooting

Events Not Sending

  1. Check network tab for failed requests
  2. Verify endpoint and tenantId are correct
  3. Enable debug: true to see logs
  4. Check if Do Not Track is enabled
  5. Verify your API endpoint is reachable

TypeScript Errors

  1. Ensure you're using TypeScript 4.0+
  2. Check that types are imported correctly:
    import InsightPro, { InsightProConfig } from '@insightpro/sdk-js';

Session Not Persisting

  1. Check if localStorage is available and enabled
  2. Verify enableSessions is set to true
  3. Check sessionTimeout configuration

Events Being Dropped

  1. Check maxQueueSize - increase if needed
  2. Verify network connectivity
  3. Check maxRetries configuration
  4. Enable debug mode to see error messages

Migration Guides

From Google Analytics

// Google Analytics
gtag('event', 'page_view', { page_title: 'Home' });

// InsightPro
analytics.page('Home');

From Segment

// Segment
analytics.track('Button Clicked', { buttonName: 'CTA' });

// InsightPro (same API!)
analytics.track('Button Clicked', { buttonName: 'CTA' });

From Mixpanel

// Mixpanel
mixpanel.track('Video Played', { videoId: '123' });

// InsightPro
analytics.track('Video Played', { videoId: '123' });

Browser Support

  • Chrome (latest)
  • Firefox (latest)
  • Safari (latest)
  • Edge (latest)
  • Opera (latest)
  • iOS Safari 12+
  • Android Chrome 80+

TypeScript Types

Full TypeScript definitions are included:

import type {
  InsightProConfig,
  Event,
  PageViewEvent,
  EcommerceEvent,
  UserActionEvent,
  ErrorEvent,
  IdentifyEvent,
  PageEvent,
  AliasEvent,
  GroupEvent,
  RevenueEvent,
  ConversionEvent,
  UserTraits,
  GroupTraits,
  Context,
  SessionData,
} from '@insightpro/sdk-js';

Examples

See the examples/ directory for complete examples:

  • examples/vanilla-js.html - Vanilla JavaScript
  • examples/react-app.tsx - React integration
  • examples/next-app.tsx - Next.js integration
  • examples/vue-app.js - Vue 3 integration
  • examples/typescript-app.ts - TypeScript usage

License

MIT

Support

  • Documentation: https://docs.insightpro.com
  • GitHub Issues: https://github.com/insightpro/sdk-js/issues
  • Email: [email protected]

Changelog

1.0.0 (2025-01-15)

  • Initial release
  • Core tracking methods (track, page, identify, alias, group)
  • Revenue and conversion tracking
  • Auto-capture features (page views, clicks, forms, scroll, time)
  • Event batching and offline queue
  • Session management
  • Privacy features (DNT, opt-out)
  • TypeScript support
  • Framework examples