insightpro-ai-sdk-browser
v1.0.0
Published
InsightPro JavaScript SDK for browser-based event tracking
Maintainers
Readme
@insightpro/browser
Privacy-first JavaScript SDK for InsightPro Analytics
Installation
npm install @insightpro/browserOr via CDN:
<script src="https://cdn.insightpro.com/browser/v1/insightpro.min.js"></script>Quick Start
import InsightPro from '@insightpro/browser';
// Initialize the SDK
InsightPro.init('YOUR_API_KEY', {
cookieless: true, // GDPR-compliant tracking
capturePageViews: true, // Automatic page view tracking
captureClicks: true, // Automatic click tracking
captureFormSubmits: true, // Automatic form tracking
debug: false // Enable debug logging
});
// Track custom events
InsightPro.track('Purchase Completed', {
orderId: '12345',
revenue: 99.99,
currency: 'USD'
});
// Identify users
InsightPro.identify('user-123', {
email: '[email protected]',
name: 'John Doe',
plan: 'premium'
});
// Track page views manually
InsightPro.page('Pricing Page', {
category: 'Marketing'
});
// Associate user with a group (B2B)
InsightPro.group('company-456', {
name: 'Acme Corp',
industry: 'SaaS',
employees: 50
});Features
- Privacy-First: Cookieless tracking by default (GDPR/CCPA compliant)
- Automatic Tracking: Page views, clicks, form submits, errors, performance
- Batching & Retry: Efficient event batching with automatic retry logic
- Session Management: Automatic session tracking with 30-minute timeout
- Cross-Domain: Track users across multiple domains
- Offline Support: Queue events when offline, send when back online
- TypeScript: Full TypeScript support with type definitions
- Lightweight: < 10KB gzipped
Configuration Options
InsightPro.init('YOUR_API_KEY', {
// API Configuration
apiHost: 'https://api.insightpro.com', // API endpoint
// Privacy
cookieless: true, // Use localStorage instead of cookies
// Batching
batchSize: 100, // Events per batch
flushInterval: 10000, // Flush interval in ms (10 seconds)
// Automatic Tracking
capturePageViews: true, // Auto-track page views
captureClicks: false, // Auto-track clicks
captureFormSubmits: false, // Auto-track form submissions
captureErrors: false, // Auto-track JavaScript errors
capturePerformance: false, // Auto-track performance metrics
// Storage
persistence: 'localStorage', // 'localStorage' | 'sessionStorage' | 'cookie' | 'memory'
// Retry Logic
maxRetries: 3, // Maximum retry attempts
retryDelay: 1000, // Base retry delay in ms
// Cross-Domain Tracking
crossDomainTracking: false, // Enable cross-domain tracking
allowedDomains: [], // Allowed domains for cross-domain tracking
// Debugging
debug: false // Enable debug logging
});API Reference
init(apiKey, config)
Initialize the InsightPro SDK.
Parameters:
apiKey(string, required): Your InsightPro API keyconfig(object, optional): Configuration options
track(eventName, properties)
Track a custom event.
Parameters:
eventName(string, required): Name of the eventproperties(object, optional): Event properties
Example:
InsightPro.track('Button Clicked', {
buttonId: 'cta-signup',
page: '/pricing'
});page(name, properties)
Track a page view.
Parameters:
name(string, optional): Page name (defaults to document.title)properties(object, optional): Page properties
Example:
InsightPro.page('Pricing Page', {
category: 'Marketing',
plan: 'premium'
});identify(userId, properties)
Identify a user.
Parameters:
userId(string, required): Unique user identifierproperties(object, optional): User properties
Example:
InsightPro.identify('user-123', {
email: '[email protected]',
name: 'John Doe',
plan: 'premium',
createdAt: '2025-01-15T10:00:00Z'
});group(groupId, properties)
Associate a user with a group (for B2B).
Parameters:
groupId(string, required): Unique group identifierproperties(object, optional): Group properties
Example:
InsightPro.group('company-456', {
name: 'Acme Corp',
industry: 'SaaS',
employees: 50,
plan: 'enterprise'
});reset()
Reset user identity (useful for logout).
Example:
InsightPro.reset();flush()
Manually flush queued events to the server.
Returns: Promise
Example:
await InsightPro.flush();getUserId()
Get the current user ID.
Returns: string | null
getAnonymousId()
Get the anonymous ID.
Returns: string
getSessionId()
Get the current session ID.
Returns: string
onEvent(callback)
Register a callback to be called for every tracked event.
Parameters:
callback(function): Callback function receiving the event object
Example:
InsightPro.onEvent((event) => {
console.log('Event tracked:', event);
});onError(callback)
Register a callback to be called when an error occurs.
Parameters:
callback(function): Callback function receiving error and optional event
Example:
InsightPro.onError((error, event) => {
console.error('SDK error:', error, event);
});Event Context
All events automatically include rich context:
{
event_name: 'Purchase Completed',
user_id: 'user-123',
anonymous_id: 'anon_xxx-xxx-xxx',
session_id: 'sess_xxx-xxx-xxx',
timestamp: 1234567890,
properties: { /* your custom properties */ },
context: {
page: {
url: 'https://example.com/pricing',
path: '/pricing',
title: 'Pricing',
referrer: 'https://google.com',
search: '?utm_source=google',
hash: '#premium'
},
user_agent: 'Mozilla/5.0...',
locale: 'en-US',
timezone: 'America/New_York',
screen: {
width: 1920,
height: 1080,
density: 2
},
library: {
name: '@insightpro/browser',
version: '1.0.0'
},
campaign: {
name: 'summer-sale',
source: 'google',
medium: 'cpc',
term: 'analytics',
content: 'text-ad'
},
referrer: {
url: 'https://google.com',
domain: 'google.com'
}
}
}Session Management
The SDK automatically manages user sessions with the following behavior:
- Session Duration: 30 minutes of inactivity
- Session Renewal: Activity (clicks, scrolls, keypresses, mouse moves) renews the session
- New Session: Created after 30 minutes of inactivity or when the page becomes visible after being hidden for > 30 minutes
Privacy & GDPR Compliance
The SDK is designed with privacy in mind:
- Cookieless by Default: Uses
localStorageinstead of cookies (no cookie banner required in many jurisdictions) - No PII Collection: Only collects what you explicitly send
- Data Minimization: Minimal context data collected by default
- User Control: Easy to implement consent management
Example: Consent Management
// Wait for user consent before initializing
if (userHasConsented()) {
InsightPro.init('YOUR_API_KEY', {
cookieless: true
});
}
// Or disable automatic tracking until consent is given
InsightPro.init('YOUR_API_KEY', {
cookieless: true,
capturePageViews: false,
captureClicks: false
});
// Enable tracking after consent
if (userHasConsented()) {
InsightPro.track('Consent Given');
InsightPro.page(); // Manually track page view
}React Integration
import { useEffect } from 'react';
import InsightPro from '@insightpro/browser';
function App() {
useEffect(() => {
InsightPro.init('YOUR_API_KEY', {
cookieless: true,
capturePageViews: true
});
}, []);
const handlePurchase = () => {
InsightPro.track('Purchase Completed', {
orderId: '12345',
revenue: 99.99
});
};
return <button onClick={handlePurchase}>Purchase</button>;
}Vue Integration
<template>
<button @click="handlePurchase">Purchase</button>
</template>
<script>
import InsightPro from '@insightpro/browser';
export default {
mounted() {
InsightPro.init('YOUR_API_KEY', {
cookieless: true,
capturePageViews: true
});
},
methods: {
handlePurchase() {
InsightPro.track('Purchase Completed', {
orderId: '12345',
revenue: 99.99
});
}
}
};
</script>License
MIT
