aurea-tracking-sdk
v2.0.1
Published
Standalone tracking SDK for Aurea CRM external funnels
Maintainers
Readme
Aurea Tracking SDK
A standalone tracking SDK for Aurea CRM external funnels. Track user behavior, conversions, and analytics events in your web applications.
Installation
npm install aurea-tracking-sdk
# or
yarn add aurea-tracking-sdk
# or
pnpm add aurea-tracking-sdkQuick Start
1. Initialize the SDK
import { initAurea } from 'aurea-tracking-sdk';
initAurea({
apiKey: 'your-api-key',
funnelId: 'your-funnel-id',
apiUrl: 'https://your-aurea-instance.com/api',
debug: true, // Enable debug logging in development
autoTrack: {
pageViews: true,
forms: true,
scrollDepth: true,
clicks: false,
},
});2. Track Custom Events
import { trackEvent } from 'aurea-tracking-sdk';
// Track a custom event
trackEvent('button_clicked', {
buttonName: 'Get Started',
location: 'hero',
});
// Track a conversion
import { trackConversion } from 'aurea-tracking-sdk';
trackConversion({
type: 'purchase',
revenue: 99.00,
currency: 'USD',
orderId: 'order_123',
});3. Identify Users
import { identifyUser } from 'aurea-tracking-sdk';
identifyUser('user_123', {
email: '[email protected]',
name: 'John Doe',
plan: 'premium',
});Features
✅ Auto-Tracking
- Page Views - Automatically tracks page visits and navigation
- Form Submissions - Captures form submit events
- Scroll Depth - Tracks user engagement (25%, 50%, 75%, 100%)
- Clicks - Optional click tracking
- Outbound Links - Track clicks to external domains (v2.0+)
- Hash Changes - Support for hash-based SPA routing (v2.0+)
📊 Analytics
- Custom Events - Track any custom event with properties
- Conversions - Track purchases and revenue
- User Identification - Link events to specific users
- Session Tracking - Automatic session management
- Video Tracking - Track video engagement with milestones (v2.0+)
- Core Web Vitals - Automatic LCP, INP, CLS, FCP, TTFB tracking
🔗 Cross-Domain Tracking (v2.0+)
- Cross-Domain Linker - Maintain visitor identity across your domains
- Auto Link Decoration - Automatically appends linker params to links
- Form Support - Decorates form submissions with linker params
📈 Attribution (v2.0+)
- First-Touch UTM - Track original visit source
- Last-Touch UTM - Track most recent visit source
- Click ID Tracking - Support for 10+ ad platforms (gclid, fbclid, etc.)
🔄 Purchase Detection
- Webhook Integration - Detects purchases from server-side webhooks
- Auto-Redirect - Automatically redirects users to thank-you page after purchase
- Polling System - Checks for purchases every 3 seconds
🛡️ Privacy & Quality (v2.0+)
- Do Not Track - Respects browser DNT settings
- IP Anonymization - Optional IP address anonymization
- Bot Filtering - Automatically filter bot traffic
- Sampling Rate - Control event volume for high-traffic sites
- GDPR Compliant - Built with privacy in mind
🔧 Developer Experience (v2.0+)
- Middleware System - Transform or filter events before sending
- Automatic Retry - Retry failed events when back online
- Event Deduplication - Prevents duplicate events
🎯 Lead Scoring (v2.0+)
- Automatic Lead Scoring - Score visitors 0-100 based on engagement
- Score Categories - Breakdown by engagement, intent, behavior, recency
- Lead Grades - Cold, warm, hot, qualified thresholds
- Score Decay - Configurable decay for inactive leads
🧪 A/B Testing (v2.0+)
- Native A/B Test Support - Track experiments without external tools
- Variant Tracking - Automatic variant assignment in events
- Conversion Attribution - Attribute conversions to test variants
🔍 UX Analytics (v2.0+)
- Rage Click Detection - Detect frustrated rapid clicking
- Dead Click Detection - Find clicks on non-interactive elements
- Element Visibility - Track when key elements are viewed
- Exit Intent - Detect when users are about to leave
📈 Engagement Score (v2.0+)
- Real-time Scoring - 0-100 engagement score
- Factor Breakdown - Time, scroll, interactions, content, return visits
- Engagement Levels - Low, medium, high, very_high
🐛 Error Tracking (v2.0+)
- JavaScript Errors - Capture unhandled errors
- Promise Rejections - Track async failures
- Console Errors - Optional console.error capture
📹 Session Replay (v2.0+)
- Replay Hooks - Integration with external replay tools
- Event Buffer - Click, scroll, input, resize events
- PII Masking - Automatic password field masking
API Reference
initAurea(config)
Initialize the tracking SDK.
Parameters:
interface AureaConfig {
apiKey: string; // Required: Your Aurea API key
funnelId: string; // Required: Your funnel ID
apiUrl?: string; // Optional: API endpoint URL
debug?: boolean; // Optional: Enable debug logging
autoTrack?: { // Optional: Auto-tracking settings
pageViews?: boolean; // Default: true
forms?: boolean; // Default: true
clicks?: boolean; // Default: false
scrollDepth?: boolean; // Default: false
outboundLinks?: boolean; // Default: false (v2.0+)
hashChanges?: boolean; // Default: false (v2.0+)
};
respectDoNotTrack?: boolean; // Optional: Respect DNT header (default: true)
anonymizeIp?: boolean; // Optional: Anonymize IP addresses (default: true)
batchSize?: number; // Optional: Event batch size (default: 10)
batchInterval?: number; // Optional: Batch interval in ms (default: 2000)
// v2.0+ Options
sessionTimeout?: number; // Session timeout in ms (default: 30000)
crossDomainDomains?: string[]; // Domains for cross-domain tracking
crossDomainLinkerParam?: string; // Linker param name (default: '_aurea')
samplingRate?: number; // Event sampling 0.0-1.0 (default: 1.0)
filterBots?: boolean; // Filter bot traffic (default: true)
middleware?: EventMiddleware[]; // Event transformation middleware
}Returns: AureaSDK instance
Example:
const aurea = initAurea({
apiKey: 'ak_1234567890',
funnelId: 'fn_abcdefgh',
apiUrl: 'https://analytics.example.com/api',
debug: process.env.NODE_ENV === 'development',
});trackEvent(name, properties?)
Track a custom event.
Parameters:
name(string): Event nameproperties(object, optional): Event properties
Example:
trackEvent('product_viewed', {
productId: 'prod_123',
productName: 'Premium Plan',
price: 99.00,
category: 'subscription',
});trackPage(name?, properties?)
Track a page view.
Parameters:
name(string, optional): Page nameproperties(object, optional): Page properties
Example:
trackPage('Pricing Page', {
plan: 'premium',
billingCycle: 'monthly',
});trackConversion(data)
Track a conversion event.
Parameters:
interface ConversionData {
type: string; // Conversion type (e.g., 'purchase', 'signup')
revenue: number; // Revenue amount
currency?: string; // Currency code (default: 'USD')
orderId?: string; // Order/transaction ID
properties?: object; // Additional properties
}Example:
trackConversion({
type: 'purchase',
revenue: 149.99,
currency: 'USD',
orderId: 'order_abc123',
properties: {
plan: 'annual',
discount: 'SAVE20',
},
});identifyUser(userId, traits?)
Identify a user.
Parameters:
userId(string): Unique user identifiertraits(object, optional): User traits/properties
Example:
identifyUser('user_123', {
email: '[email protected]',
name: 'John Doe',
plan: 'premium',
signupDate: '2024-01-15',
});getAurea()
Get the current SDK instance.
Returns: AureaSDK | null
Example:
import { getAurea } from 'aurea-tracking-sdk';
const aurea = getAurea();
if (aurea) {
aurea.track('custom_event');
}Framework Integration
Next.js
Create a component to initialize the SDK:
// components/aurea-tracking.tsx
'use client';
import { useEffect } from 'react';
import { initAurea } from 'aurea-tracking-sdk';
export function AureaTracking() {
useEffect(() => {
initAurea({
apiKey: process.env.NEXT_PUBLIC_AUREA_API_KEY!,
funnelId: process.env.NEXT_PUBLIC_AUREA_FUNNEL_ID!,
apiUrl: process.env.NEXT_PUBLIC_AUREA_API_URL,
debug: process.env.NODE_ENV === 'development',
});
}, []);
return null;
}Add to your root layout:
// app/layout.tsx
import { AureaTracking } from '@/components/aurea-tracking';
export default function RootLayout({ children }) {
return (
<html>
<body>
<AureaTracking />
{children}
</body>
</html>
);
}React
import { useEffect } from 'react';
import { initAurea, trackEvent } from 'aurea-tracking-sdk';
function App() {
useEffect(() => {
initAurea({
apiKey: import.meta.env.VITE_AUREA_API_KEY,
funnelId: import.meta.env.VITE_AUREA_FUNNEL_ID,
});
}, []);
return <YourApp />;
}Vanilla JavaScript
<script type="module">
import { initAurea, trackEvent } from 'https://unpkg.com/aurea-tracking-sdk';
initAurea({
apiKey: 'your-api-key',
funnelId: 'your-funnel-id',
});
// Track events
document.querySelector('#cta-button').addEventListener('click', () => {
trackEvent('cta_clicked');
});
</script>v2.0 Features
Cross-Domain Tracking
Maintain visitor identity across multiple domains:
initAurea({
apiKey: 'your-api-key',
funnelId: 'your-funnel-id',
crossDomainDomains: ['checkout.example.com', 'app.example.com'],
crossDomainLinkerParam: '_aurea', // optional, this is the default
});
// Links to configured domains will automatically include the linker param
// <a href="https://checkout.example.com/buy">Buy Now</a>
// becomes: https://checkout.example.com/buy?_aurea=ses_xxx.anon_yyy
// Manual URL generation
const linkedUrl = aurea.getLinkerUrl('https://checkout.example.com/buy');UTM Attribution
Track first-touch and last-touch UTM data:
import { getAurea } from 'aurea-tracking-sdk';
const aurea = getAurea();
// Get original visit UTM data
const firstTouch = aurea?.getFirstTouchUtm();
// { source: 'google', medium: 'cpc', campaign: 'brand', timestamp: 1234567890 }
// Get most recent UTM data
const lastTouch = aurea?.getLastTouchUtm();
// { source: 'facebook', medium: 'social', campaign: 'retargeting', timestamp: 1234567899 }
// Both are automatically included in every event's contextVideo Tracking
Track video engagement with milestones:
import { getAurea } from 'aurea-tracking-sdk';
const aurea = getAurea();
const videoElement = document.querySelector('video');
aurea?.trackVideo(videoElement, {
milestones: [25, 50, 75, 100], // Track at these percentages
trackPlay: true, // Track play events
trackPause: true, // Track pause events
trackComplete: true, // Track when video completes
});
// Events tracked:
// - video_play: When user starts/resumes video
// - video_pause: When user pauses video
// - video_milestone: When user reaches 25%, 50%, 75%, 100%
// - video_complete: When video finishesMiddleware
Transform or filter events before sending:
import { getAurea } from 'aurea-tracking-sdk';
const aurea = getAurea();
// Add enrichment data
aurea?.addMiddleware((event) => ({
...event,
properties: {
...event.properties,
app_version: '2.1.0',
environment: 'production',
},
}));
// Filter out specific events
aurea?.addMiddleware((event) => {
// Return null to drop the event
if (event.eventName === 'internal_debug') {
return null;
}
return event;
});
// PII scrubbing
aurea?.addMiddleware((event) => ({
...event,
properties: {
...event.properties,
email: event.properties?.email?.replace(/(.{2}).*@/, '$1***@'),
},
}));Bot Filtering
Automatically filter bot traffic (enabled by default):
initAurea({
apiKey: 'your-api-key',
funnelId: 'your-funnel-id',
filterBots: true, // Default: true
});
// Filters: headless browsers, webdrivers, crawlers, bots
// Detects: Googlebot, Bingbot, PhantomJS, Puppeteer, etc.Sampling Rate
Control event volume for high-traffic sites:
initAurea({
apiKey: 'your-api-key',
funnelId: 'your-funnel-id',
samplingRate: 0.1, // Only track 10% of events
});Automatic Retry
Events that fail due to network issues are automatically retried:
// Automatic: Failed events are stored in localStorage and retried when online
// Manual retry
import { getAurea } from 'aurea-tracking-sdk';
const aurea = getAurea();
aurea?.retryFailedEvents();Outbound Link Tracking
Track clicks to external domains:
initAurea({
apiKey: 'your-api-key',
funnelId: 'your-funnel-id',
autoTrack: {
outboundLinks: true,
},
});
// Automatically tracks: outbound_link_click
// Properties: { url, text, target }Enterprise Features (v2.0+)
Lead Scoring
Automatically score visitors based on their engagement:
import { initAurea, getAurea } from 'aurea-tracking-sdk';
initAurea({
apiKey: 'your-api-key',
funnelId: 'your-funnel-id',
leadScoring: {
enabled: true,
maxScore: 100,
decayEnabled: true, // Score decays over time
decayRate: 5, // Points lost per day of inactivity
thresholds: {
cold: 30, // 0-30 = cold
warm: 60, // 31-60 = warm
hot: 85, // 61-85 = hot
qualified: 100, // 86-100 = qualified
},
},
});
const aurea = getAurea();
// Add points when user takes high-intent actions
aurea?.addLeadScore(10, 'Viewed pricing page', 'intent');
aurea?.addLeadScore(20, 'Started free trial', 'behavior');
aurea?.addLeadScore(5, 'Watched demo video', 'engagement');
// Get current score
const score = aurea?.getLeadScore();
// {
// score: 35,
// grade: 'warm',
// breakdown: { engagement: 5, intent: 10, behavior: 20, recency: 0 },
// history: [...]
// }
// Reset score (e.g., after conversion)
aurea?.resetLeadScore();A/B Testing
Track experiments and attribute conversions:
initAurea({
apiKey: 'your-api-key',
funnelId: 'your-funnel-id',
abTests: [
{
testId: 'pricing-page-v2',
testName: 'Pricing Page Redesign',
variant: 'B',
variantName: 'New Layout',
},
{
testId: 'cta-color',
testName: 'CTA Button Color',
variant: 'green',
},
],
});
const aurea = getAurea();
// Track when user converts in a test
aurea?.trackABConversion('pricing-page-v2', 'signup', 99.00);
// Get which variant user is in
const variant = aurea?.getTestVariant('pricing-page-v2'); // 'B'
// All events automatically include test contextRage & Dead Click Detection
Detect user frustration and UX issues:
initAurea({
apiKey: 'your-api-key',
funnelId: 'your-funnel-id',
clickAnalysis: {
rageClickThreshold: 3, // 3+ clicks in timeWindow = rage click
rageClickTimeWindow: 1000, // 1 second window
deadClickEnabled: true, // Track clicks on non-interactive elements
},
});
// Events tracked automatically:
// - rage_click: { element, clickCount, x, y }
// - dead_click: { element, x, y }
const aurea = getAurea();
const analysis = aurea?.getClickAnalysis();
// { rageClicks: 2, deadClicks: 5, lastRageClickElement: '.broken-button' }Exit Intent Detection
Detect when users are about to leave:
initAurea({
apiKey: 'your-api-key',
funnelId: 'your-funnel-id',
exitIntent: {
enabled: true,
threshold: 50, // Pixels from top of page
delay: 5000, // Wait 5s before enabling
triggerOnce: true, // Only trigger once per session
onExitIntent: () => {
// Show exit popup, offer discount, etc.
showExitPopup();
},
},
});
// Event tracked: exit_intent
// Properties: { timeOnPage, scrollDepth, currentStage, leadScore }Element Visibility Tracking
Track when key elements come into view:
initAurea({
apiKey: 'your-api-key',
funnelId: 'your-funnel-id',
visibilityTracking: {
enabled: true,
threshold: 0.5, // 50% visible to trigger
elements: [ // CSS selectors to track
'.pricing-section',
'.testimonials',
'#cta-button',
'[data-track="hero"]',
],
trackOnce: true, // Only track each element once
},
});
// Default elements tracked automatically:
// [data-track], [data-aurea-track], .cta, .pricing, .testimonial, .faq, .benefits, .guarantee
// Manually track an element
const aurea = getAurea();
aurea?.trackElement('.custom-section');
// Event tracked: element_visible
// Properties: { elementId, selector, visibilityRatio, timeOnPage }Engagement Score
Get real-time engagement scoring:
const aurea = getAurea();
const engagement = aurea?.getEngagementScore();
// {
// score: 72,
// level: 'high',
// factors: {
// timeOnPage: 20, // Up to 25 points
// scrollDepth: 18, // Up to 25 points
// interactions: 15, // Up to 25 points
// contentViewed: 12, // Up to 25 points
// returnVisits: 7, // Bonus points
// }
// }
// Use for personalization
if (engagement.level === 'very_high') {
showPremiumOffer();
}Error Tracking
Capture JavaScript errors automatically:
initAurea({
apiKey: 'your-api-key',
funnelId: 'your-funnel-id',
errorTracking: {
enabled: true,
captureUnhandled: true, // window.onerror
capturePromiseRejections: true, // unhandledrejection
captureConsoleErrors: false, // console.error (noisy)
maxErrorsPerSession: 50, // Limit to prevent spam
},
});
// Manual error tracking
const aurea = getAurea();
aurea?.trackError(new Error('Checkout failed'), {
step: 'payment',
paymentMethod: 'stripe',
});
// Events tracked:
// - js_error: { message, filename, lineno, stack }
// - unhandled_rejection: { reason }
// - custom_error: { message, stack, ...context }Session Replay Hooks
Integrate with external session replay tools:
initAurea({
apiKey: 'your-api-key',
funnelId: 'your-funnel-id',
sessionReplay: {
enabled: true,
captureClicks: true,
captureScrolls: true,
captureInputs: true, // Auto-masks passwords
captureResize: true,
onEvent: (event) => {
// Send to external replay service (LogRocket, FullStory, etc.)
replayService.send(event);
},
},
});
// Get replay buffer for custom processing
const aurea = getAurea();
const events = aurea?.getReplayBuffer();
// [{ type: 'click', timestamp: 123, data: { x, y, target } }, ...]
aurea?.clearReplayBuffer();Multi-Page Funnel Tracking
Track progress through multi-page funnels:
const aurea = getAurea();
// On each funnel page
aurea?.startFunnelStep('step-1', 'Landing Page');
// When user advances
aurea?.completeFunnelStep();
aurea?.startFunnelStep('step-2', 'Product Selection');
// Get progress
const progress = aurea?.getFunnelProgress();
// {
// steps: [
// { stepId: 'step-1', stepName: 'Landing Page', completed: true, duration: 45000 },
// { stepId: 'step-2', stepName: 'Product Selection', completed: false }
// ],
// currentStep: { stepId: 'step-2', ... },
// completedCount: 1
// }Custom Dimensions
Add custom attributes to all events:
const aurea = getAurea();
// Single dimension
aurea?.setCustomDimension('plan', 'enterprise');
aurea?.setCustomDimension('team_size', 50);
// Multiple dimensions
aurea?.setCustomDimensions({
cohort: 'january-2024',
segment: 'high-value',
industry: 'saas',
});
// All events now include these dimensions in context
// Clear when needed
aurea?.clearCustomDimensions();Time-to-Conversion Metrics
Get detailed conversion timing:
const aurea = getAurea();
const timing = aurea?.getTimeToConversion();
// {
// sessionDuration: 180, // Total seconds on site
// timeToFirstInteraction: 5, // Seconds until first click/scroll
// timeToCheckout: 120, // Seconds until checkout started
// timeToConversion: undefined, // Only set after purchase
// engagementDuration: 145, // Active (not idle) seconds
// }Full Enterprise Configuration
initAurea({
// Core
apiKey: process.env.AUREA_API_KEY!,
funnelId: process.env.AUREA_FUNNEL_ID!,
apiUrl: 'https://analytics.yourdomain.com/api',
debug: false,
// Auto-tracking
autoTrack: {
pageViews: true,
forms: true,
scrollDepth: true,
clicks: false,
outboundLinks: true,
hashChanges: false,
},
// Privacy
respectDoNotTrack: true,
anonymizeIp: true,
filterBots: true,
samplingRate: 1.0,
// Cross-domain
crossDomainDomains: ['checkout.yourdomain.com', 'app.yourdomain.com'],
// Lead Scoring
leadScoring: {
enabled: true,
maxScore: 100,
decayEnabled: true,
decayRate: 5,
},
// A/B Testing
abTests: [
{ testId: 'homepage-v2', testName: 'Homepage Redesign', variant: 'B' },
],
// UX Analytics
clickAnalysis: {
rageClickThreshold: 3,
rageClickTimeWindow: 1000,
deadClickEnabled: true,
},
exitIntent: {
enabled: true,
threshold: 50,
delay: 5000,
triggerOnce: true,
},
visibilityTracking: {
enabled: true,
threshold: 0.5,
elements: ['.pricing', '.testimonials', '.cta'],
},
// Error Tracking
errorTracking: {
enabled: true,
captureUnhandled: true,
capturePromiseRejections: true,
},
// Session Replay
sessionReplay: {
enabled: true,
captureClicks: true,
captureScrolls: true,
captureInputs: true,
},
// GDPR
gdprConsent: {
required: true,
consentVersion: '1.0',
},
});Advanced Usage
Custom Session Management
import { getAurea } from 'aurea-tracking-sdk';
const aurea = getAurea();
// Get current session ID
console.log(aurea?.sessionId);
// Get current anonymous ID
console.log(aurea?.anonymousId);Event Batching
Events are automatically batched and sent in groups for better performance:
initAurea({
apiKey: 'your-api-key',
funnelId: 'your-funnel-id',
batchSize: 20, // Send after 20 events
batchInterval: 5000, // Or after 5 seconds
});Error Handling
import { trackEvent } from 'aurea-tracking-sdk';
try {
trackEvent('risky_operation', { value: 123 });
} catch (error) {
console.error('Failed to track event:', error);
}Configuration Examples
Development
initAurea({
apiKey: 'ak_dev_1234567890',
funnelId: 'fn_dev_abcdefgh',
apiUrl: 'http://localhost:3000/api',
debug: true,
respectDoNotTrack: false, // Track in dev
});Production
initAurea({
apiKey: process.env.AUREA_API_KEY!,
funnelId: process.env.AUREA_FUNNEL_ID!,
apiUrl: 'https://analytics.yourdomain.com/api',
debug: false,
respectDoNotTrack: true,
anonymizeIp: true,
batchSize: 10,
batchInterval: 2000,
// v2.0+ recommended settings
filterBots: true,
crossDomainDomains: ['checkout.yourdomain.com'],
autoTrack: {
pageViews: true,
forms: true,
scrollDepth: true,
outboundLinks: true,
},
});Browser Support
- Chrome/Edge (last 2 versions)
- Firefox (last 2 versions)
- Safari (last 2 versions)
- Mobile browsers (iOS Safari, Chrome Mobile)
TypeScript
This package is written in TypeScript and includes type definitions out of the box.
import type { AureaConfig, ConversionData } from 'aurea-tracking-sdk';License
MIT
Support
For issues and questions:
- GitHub: https://github.com/yourusername/aurea-tracking-sdk/issues
- Documentation: https://docs.aureacrm.com
- Email: [email protected]
