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
Maintainers
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-jsYarn
yarn add @insightpro/sdk-jspnpm
pnpm add @insightpro/sdk-jsCDN
<!-- 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
- Initialize Once: Create a single SDK instance and export it for use across your app
- Use Environment Variables: Store endpoint and tenant ID in environment variables
- Enable Debug in Development: Set
debug: truein development for easier debugging - Flush on Navigation: Call
flush()before navigation to ensure events are sent - Reset on Logout: Call
reset()when users log out to clear user data - Batch Wisely: Adjust
batchSizeandbatchIntervalbased on your traffic - Use TypeScript: Leverage TypeScript types for type-safe tracking
- Global Properties: Use global properties for common metadata (app version, etc.)
- Error Handling: Enable auto-error tracking in production
- Privacy First: Respect user privacy with DNT and opt-out support
Troubleshooting
Events Not Sending
- Check network tab for failed requests
- Verify
endpointandtenantIdare correct - Enable
debug: trueto see logs - Check if Do Not Track is enabled
- Verify your API endpoint is reachable
TypeScript Errors
- Ensure you're using TypeScript 4.0+
- Check that types are imported correctly:
import InsightPro, { InsightProConfig } from '@insightpro/sdk-js';
Session Not Persisting
- Check if localStorage is available and enabled
- Verify
enableSessionsis set totrue - Check
sessionTimeoutconfiguration
Events Being Dropped
- Check
maxQueueSize- increase if needed - Verify network connectivity
- Check
maxRetriesconfiguration - 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 JavaScriptexamples/react-app.tsx- React integrationexamples/next-app.tsx- Next.js integrationexamples/vue-app.js- Vue 3 integrationexamples/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
