ainamika-sdk
v1.2.9
Published
AI-powered analytics SDK with Web Vitals, engagement tracking, error monitoring, and real-time insights for web applications
Downloads
2,576
Maintainers
Readme
AInamika SDK Pro
AInamika SDK Pro is an AI-powered analytics SDK for web applications. It provides intelligent event tracking, Web Vitals performance monitoring, user engagement analytics, error monitoring, user journey analysis, and real-time insights with minimal configuration.
Features
- AI-Powered Auto-Configuration: Automatically analyzes your DOM and generates semantic tracking configurations
- Session Start Tracking: Captures device info, landing page, referrer, and UTM params immediately on load
- Web Vitals & Performance Tracking: Core Web Vitals (LCP, FCP, FID, CLS, TTFB) and page load metrics
- Engagement Analytics: Scroll depth, rage clicks, time on page, active/idle time tracking
- API Response Tracking: Track and analyze API calls with timing and response data
- Error Tracking: Comprehensive error capture with stack traces, screenshots, device info, and DOM snapshots
- Page Context & Query Params: Automatic capture of URL, path, query parameters, referrer with every event
- Extra Config Support: Pass custom data (userId, deviceId, appVersion) that's included in all events
- Smart Event Naming: AI generates semantic event names like
game_launch_cubeforminstead of generic names - Framework Detection: Detects click handlers from React, Vue, Angular, Svelte, and jQuery components
- User Journey Analysis: Track complete user journeys for funnel optimization
- Sampling Support: Server-side sampling to control data volume and costs
- Offline Support: Queue events when offline and sync when back online
- Web Worker Support: Non-blocking event batching for optimal performance
- TypeScript Support: Full TypeScript definitions included
Installation
npm install ainamika-sdkOr via CDN:
<script src="https://unpkg.com/ainamika-sdk@latest/dist/ainamika-sdk.js"></script>Quick Start
1. Get Your Project Key
Sign up at AInamika Dashboard and create a project to get your projectKey.
2. Initialize the SDK
Minimal Configuration (Recommended Start)
The simplest way to get started - just 3 lines:
import AInamikaSDK from 'ainamika-sdk';
const analytics = new AInamikaSDK({
projectKey: 'proj_xxxxxxxxxx', // Get this from your dashboard
autoConfig: true, // AI-powered auto-configuration
clientId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // Your client ID
});That's it! The SDK will automatically track clicks, form submissions, page views, performance metrics, and engagement.
Full Configuration
For more control, you can configure all options:
import AInamikaSDK from 'ainamika-sdk';
const analytics = new AInamikaSDK({
projectKey: 'proj_xxxxxxxxxx', // Get this from your dashboard
autoConfig: true, // AI-powered auto-configuration
clientId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
debug: false, // Set to true for development
// Extra config - custom data included with ALL events
extraConfig: {
appVersion: '2.0.0', // Your app version
environment: 'production', // Environment name
deviceId: 'device_abc123' // Custom device identifier
},
// Enable advanced tracking (enabled by default)
advancedTracking: {
enabled: true,
trackPerformance: true, // Web Vitals tracking
trackEngagement: true, // Engagement metrics
trackScrollDepth: true, // Scroll depth milestones
trackRageClicks: true, // Frustration detection
trackTimeOnPage: true, // Active/idle time
trackAPIResponses: false // Opt-in API tracking
}
});3. Track Events
// Track custom events
analytics.track('button_click', {
buttonId: 'signup-btn',
page: 'landing'
});
// Track purchases
analytics.track('purchase', {
productId: 'SKU123',
price: 99.99,
currency: 'USD'
});Performance Tracking (Web Vitals)
The SDK automatically tracks Core Web Vitals and page performance metrics:
Automatic Metrics
| Metric | Event Name | Description |
|--------|------------|-------------|
| LCP | performance_lcp | Largest Contentful Paint (target: <2.5s) |
| FCP | performance_fcp | First Contentful Paint (target: <1.8s) |
| FID | performance_fid | First Input Delay (target: <100ms) |
| CLS | performance_cls | Cumulative Layout Shift (target: <0.1) |
| TTFB | performance_page_load | Time to First Byte |
| Page Load | performance_page_load | Complete page load timing |
Get Performance Metrics
// Get current performance metrics
const metrics = analytics.getPerformanceMetrics();
console.log(metrics);
// {
// lcp: 1234, // Largest Contentful Paint (ms)
// fcp: 890, // First Contentful Paint (ms)
// fid: 45, // First Input Delay (ms)
// cls: 0.05, // Cumulative Layout Shift
// ttfb: 234, // Time to First Byte (ms)
// domContentLoaded: 1500,
// pageLoad: 2100,
// resourceCount: 45,
// transferSize: 1234567
// }Session Tracking
The SDK automatically sends a session_start event immediately when it loads, before any other processing. This ensures you capture data from the moment a user lands on your app.
Session Start Event Data
// Automatically sent on SDK initialization
{
event: "session_start",
properties: {
// Device Information
userAgent: "Mozilla/5.0...",
language: "en-US",
languages: ["en-US", "en"],
platform: "MacIntel",
screenWidth: 1920,
screenHeight: 1080,
viewportWidth: 1440,
viewportHeight: 900,
devicePixelRatio: 2,
timezone: "America/New_York",
timezoneOffset: -300,
cookieEnabled: true,
onLine: true,
// Session Info
sessionId: "sess_abc123",
userIdentifier: "anon_xyz789",
isNewSession: true,
sdkVersion: "1.2.7",
// Landing Page
landingPage: "/products",
landingUrl: "https://example.com/products?ref=google",
referrer: "https://google.com",
entryTitle: "Products - My Store",
// UTM Parameters (if present)
utmSource: "google",
utmMedium: "cpc",
utmCampaign: "summer_sale"
}
}This gives you complete visibility into:
- Traffic sources: Where users come from (referrer, UTM params)
- Device landscape: Screen sizes, browsers, platforms
- Geographic distribution: Timezone data
- Entry points: Which pages users land on first
Engagement Tracking
Track how users interact with your pages:
Automatic Engagement Events
| Feature | Event Name | Description |
|---------|------------|-------------|
| Scroll Depth | engagement_scroll_depth | Milestones at 25%, 50%, 75%, 90%, 100% |
| Rage Clicks | engagement_rage_click | 3+ rapid clicks (frustration indicator) |
| Page Exit | page_exit | Summary of session engagement |
Get Engagement Metrics
// Get current engagement metrics
const engagement = analytics.getEngagementMetrics();
console.log(engagement);
// {
// timeOnPage: 45000, // Total time (ms)
// scrollDepth: 75, // Max scroll depth (%)
// scrollDepthMilestones: [25, 50, 75],
// rageClicks: 2, // Frustration indicator
// totalClicks: 15,
// activeTime: 38000, // Active engagement (ms)
// idleTime: 7000, // Idle time (ms)
// pageVisibilityChanges: 3 // Tab switches
// }Track Custom Engagement
// Track engagement actions
analytics.trackEngagement('video_watched', {
videoId: 'intro-123',
duration: 120,
completionRate: 0.85
});
analytics.trackEngagement('level_completed', {
level: 5,
score: 1000,
timeSpent: 180
});API Response Tracking
Track API calls with timing and response data:
Enable API Tracking
const analytics = new AInamikaSDK({
projectKey: 'proj_xxx',
advancedTracking: {
trackAPIResponses: true, // Enable automatic fetch interception
apiTrackingPatterns: [ // Optional: filter which APIs to track
'/api/.*',
'https://api.example.com/.*'
]
}
});Manual API Tracking
// Track API responses manually
const response = await fetch('/api/games');
const data = await response.json();
analytics.trackAPI('/api/games', 'GET', data, {
category: 'games',
source: 'homepage'
});
// Track purchase API
const purchaseResult = await processPurchase(item);
analytics.trackAPI('/api/purchase', 'POST', purchaseResult, {
gameId: 'swing-monkey',
amount: 9.99
});Conversion Tracking
Track goals and conversions with value:
// Track purchase conversion
analytics.trackConversion('purchase', 49.99, {
productId: 'game-123',
category: 'premium'
});
// Track signup conversion
analytics.trackConversion('signup', undefined, {
source: 'organic',
plan: 'free'
});
// Track newsletter subscription
analytics.trackConversion('newsletter_subscribe', undefined, {
source: 'blog-footer'
});Configuration Options
const analytics = new AInamikaSDK({
// Required for authentication
projectKey: 'proj_xxxxxxxxxx', // Get from your dashboard
clientId: 'your-client-id', // Your unique client identifier
// Auto-Configuration
autoConfig: true, // Enable AI-powered DOM analysis
// Debugging
debug: false, // Enable console logging
// Batching Configuration
workerConfig: {
batchSize: 50, // Events per batch (default: 10)
batchInterval: 5000 // Batch interval in ms (default: 5000)
},
// Extra Config - Custom data included with ALL events (IMPORTANT!)
extraConfig: {
appVersion: '2.0.0', // Your app version (recommended)
environment: 'production', // Environment: 'development', 'staging', 'production'
deviceId: 'device_abc123', // Custom device identifier
buildNumber: '1234', // Build/release number
// Add any custom fields you need - they'll be included in every event
},
// Advanced Tracking (NEW)
advancedTracking: {
enabled: true, // Master toggle (default: true)
trackPerformance: true, // Web Vitals tracking
trackEngagement: true, // Engagement metrics
trackScrollDepth: true, // Scroll depth milestones
trackRageClicks: true, // Frustration detection
trackTimeOnPage: true, // Active/idle time tracking
trackAPIResponses: false, // API call tracking (opt-in)
scrollDepthThresholds: [25, 50, 75, 90, 100], // Custom thresholds
apiTrackingPatterns: [] // Regex patterns for API filtering
},
// Error Tracking
errorTracking: {
enabled: true, // Enable error tracking
captureScreenshots: false, // Capture screenshots on error (default: false)
captureDomSnapshots: true, // Capture DOM state on error
maxStackTraceDepth: 50, // Stack trace depth limit
maxErrorsPerSession: 100, // Max errors per session
debounceMs: 1000, // Error debounce interval
enableNetworkTracking: true, // Track network errors
enableConsoleCapture: true // Capture console errors
},
// Custom API Endpoint (optional)
apiDetails: {
apiEndPoint: 'https://your-api.com/events',
headers: {
'X-Custom-Header': 'value'
}
}
});Extra Config & Page Context
Every event automatically includes page context (URL, path, query params, referrer) and any extra config you provide.
Page Context (Automatic)
All events include:
{
pageContext: {
url: "https://example.com/products?utm_source=google&campaign=summer",
path: "/products",
queryParams: {
utm_source: "google",
campaign: "summer"
},
referrer: "https://google.com",
title: "Products - My Store",
hash: "#featured" // if present
}
}Extra Config
Pass custom data that will be included with every event. This is useful for tracking app version, environment, device info, and user context across all analytics.
Common fields:
appVersion- Your application version (e.g., '2.0.0')environment- Environment name ('development', 'staging', 'production')deviceId- Custom device identifier for cross-session tracking
// Set during initialization
const analytics = new AInamikaSDK({
projectKey: 'proj_xxxxxxxxxx',
clientId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
autoConfig: true,
extraConfig: {
appVersion: '2.0.0',
environment: 'production',
deviceId: 'device_abc123'
}
});
// Update after user login (merges with existing)
analytics.setExtraConfig({
userId: 'user_12345',
plan: 'premium',
company: 'Acme Inc'
});
// Replace entire extraConfig (pass false to not merge)
analytics.setExtraConfig({ newKey: 'value' }, false);
// Get current extraConfig
const config = analytics.getExtraConfig();Event Data Structure
Every tracked event includes:
{
event: "button_click",
properties: { /* your event data */ },
timestamp: 1704067200000,
userId: "user_12345",
sessionId: "sess_abc123",
project_key: "proj_xxx",
// Automatic page context
pageContext: {
url: "https://example.com/checkout?ref=cart",
path: "/checkout",
queryParams: { ref: "cart" },
referrer: "https://example.com/cart",
title: "Checkout"
},
// Your custom extraConfig
extraConfig: {
appVersion: "2.0.0",
environment: "production",
userId: "user_12345",
plan: "premium"
}
}Smart Event Naming
The SDK uses AI to generate semantic event names from your DOM:
| Generic Name | Smart Name |
|--------------|------------|
| interactive_element_clicked | game_launch_swing_monkey |
| item_clicked | category_selected_arcade |
| element_clicked | profile_icon_clicked |
| button_clicked | button_see_all_clicked |
Events are automatically enriched with data from customdata attributes:
<div customdata='{"name": "Cubeform", "category": "puzzle"}' onclick="...">
<!-- Click generates: game_launch_cubeform with category: puzzle -->
</div>Error Tracking
Automatic Error Capture
When errorTracking.enabled is true, the SDK automatically captures:
- Unhandled exceptions
- Promise rejections
- Network errors
- Console errors
Manual Error Capture
try {
riskyOperation();
} catch (error) {
analytics.captureException(error, {
context: 'checkout-flow',
severity: 'high',
userId: 'user123'
});
}User Identification
// When user logs in
analytics.identifyUser('user_12345', {
email: '[email protected]',
plan: 'premium',
signupDate: '2024-01-15'
});API Reference
Constructor
new AInamikaSDK(config: AnalyticsConfig)Methods
| Method | Description |
|--------|-------------|
| track(eventName, properties) | Track a custom event |
| trackAPI(endpoint, method, response, metadata) | Track an API response |
| trackEngagement(action, properties) | Track engagement event |
| trackConversion(goalName, value?, properties?) | Track conversion/goal |
| getPerformanceMetrics() | Get Web Vitals metrics |
| getEngagementMetrics() | Get engagement metrics |
| identifyUser(userId, properties?) | Identify authenticated user |
| setExtraConfig(config, merge?) | Set/update extra config (included in all events) |
| getExtraConfig() | Get current extra config |
| captureException(error, context?) | Manually capture exception |
| flushStoredErrors() | Flush queued errors |
| getSamplingStatus() | Get sampling decision |
| getProjectInfo() | Get project settings |
| isAuthenticated() | Check authentication |
| logout() | Clear authentication |
Events Tracked Automatically
| Category | Events |
|----------|--------|
| Session | session_start - Fires immediately on SDK load with device info, landing page, referrer, UTM params |
| Performance | performance_lcp, performance_fcp, performance_fid, performance_cls, performance_page_load |
| Engagement | engagement_scroll_depth, engagement_rage_click, page_exit |
| API | api_call (when enabled) |
| DOM | Click, submit, view, focus, change events based on auto-config |
Dashboard Queries
Ask these questions on your AInamika dashboard:
Performance:
- "Show me web vitals"
- "What's my LCP score?"
- "Analyze page performance"
Engagement:
- "Show scroll depth data"
- "How many rage clicks?"
- "Analyze user engagement"
Events:
- "Show top events"
- "Which games are most played?"
- "Show conversion funnel"
Framework Examples
React
import AInamikaSDK from 'ainamika-sdk';
import { useEffect } from 'react';
const analytics = new AInamikaSDK({
projectKey: 'proj_xxxxxxxxxx',
clientId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
autoConfig: true,
extraConfig: {
appVersion: '2.0.0',
environment: 'production',
deviceId: 'device_abc123'
}
});
function App() {
useEffect(() => {
analytics.track('app_loaded');
return () => {
// Log engagement on unmount
const metrics = analytics.getEngagementMetrics();
console.log('Session engagement:', metrics);
};
}, []);
const handlePurchase = async (item) => {
const result = await purchaseAPI(item);
analytics.trackAPI('/api/purchase', 'POST', result);
analytics.trackConversion('purchase', item.price);
};
return <button onClick={handlePurchase}>Buy Now</button>;
}Next.js
// lib/analytics.js
import AInamikaSDK from 'ainamika-sdk';
let analytics = null;
export function getAnalytics() {
if (typeof window !== 'undefined' && !analytics) {
analytics = new AInamikaSDK({
projectKey: 'proj_xxxxxxxxxx',
clientId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
autoConfig: true,
extraConfig: {
appVersion: process.env.NEXT_PUBLIC_APP_VERSION || '1.0.0',
environment: process.env.NODE_ENV,
deviceId: 'device_abc123'
}
});
}
return analytics;
}
// pages/_app.js
import { useEffect } from 'react';
import { useRouter } from 'next/router';
import { getAnalytics } from '../lib/analytics';
function MyApp({ Component, pageProps }) {
const router = useRouter();
useEffect(() => {
const analytics = getAnalytics();
const handleRouteChange = (url) => {
analytics?.track('page_view', { page: url });
};
router.events.on('routeChangeComplete', handleRouteChange);
return () => router.events.off('routeChangeComplete', handleRouteChange);
}, [router.events]);
return <Component {...pageProps} />;
}Vanilla JavaScript (CDN)
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/ainamika-sdk@latest/dist/ainamika-sdk.js"></script>
</head>
<body>
<button id="game-btn" customdata='{"name":"Puzzle Master"}'>Play Game</button>
<script>
// Minimal setup - just 3 required fields
const analytics = new AInamikaSDKPro({
projectKey: 'proj_xxxxxxxxxx',
clientId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
autoConfig: true,
// Optional: Add extra config for better tracking
extraConfig: {
appVersion: '2.0.0',
environment: 'production',
deviceId: 'device_abc123'
},
// Optional: Configure advanced tracking
debug: false,
advancedTracking: {
enabled: true,
trackPerformance: true,
trackEngagement: true,
trackAPIResponses: true
}
});
// Performance metrics available after load
window.addEventListener('load', () => {
setTimeout(() => {
console.log('Performance:', analytics.getPerformanceMetrics());
}, 3000);
});
// Track API calls
fetch('/api/games')
.then(res => res.json())
.then(data => {
analytics.trackAPI('/api/games', 'GET', data);
});
</script>
</body>
</html>Browser Support
- Chrome 60+
- Firefox 55+
- Safari 12+
- Edge 79+
- Opera 47+
Troubleshooting
Performance metrics not showing
- Wait 3-5 seconds after page load for Web Vitals
- Check
advancedTracking.trackPerformance: true - Some metrics (FID) require user interaction
Engagement metrics empty
- Ensure
advancedTracking.trackEngagement: true - Scroll/interact with the page to generate data
- Check
getEngagementMetrics()after interactions
API tracking not working
- Set
advancedTracking.trackAPIResponses: true - Use
trackAPI()for manual tracking - Check
apiTrackingPatternsif using filters
Data Privacy
- All data is transmitted securely over HTTPS
- User identifiers are hashed before transmission
- Sampling can reduce data collection
- No PII is collected automatically
- API response bodies are NOT sent (only metadata)
License
MIT License - see LICENSE for details.
Support
- Documentation: https://ainamika.netlify.app/about.html
- Issues: https://github.com/adarshsingh/ainamika-sdk/issues
- Email: [email protected]
