Standalone tracking SDK for Aurea CRM external funnels
npm install aurea-tracking-sdkA standalone tracking SDK for Aurea CRM external funnels. Track user behavior, conversions, and analytics events in your web applications.
``bash`
npm install aurea-tracking-sdkor
yarn add aurea-tracking-sdkor
pnpm add aurea-tracking-sdk
`typescript
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,
},
});
`
`typescript
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',
});
`
`typescript
import { identifyUser } from 'aurea-tracking-sdk';
identifyUser('user_123', {
email: 'user@example.com',
name: 'John Doe',
plan: 'premium',
});
`
- 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+)
- 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 Linker - Maintain visitor identity across your domains
- Auto Link Decoration - Automatically appends linker params to links
- Form Support - Decorates form submissions with linker params
- 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.)
- 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
- 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
- Middleware System - Transform or filter events before sending
- Automatic Retry - Retry failed events when back online
- Event Deduplication - Prevents duplicate events
- 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
- Native A/B Test Support - Track experiments without external tools
- Variant Tracking - Automatic variant assignment in events
- Conversion Attribution - Attribute conversions to test variants
- 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
- Real-time Scoring - 0-100 engagement score
- Factor Breakdown - Time, scroll, interactions, content, return visits
- Engagement Levels - Low, medium, high, very_high
- JavaScript Errors - Capture unhandled errors
- Promise Rejections - Track async failures
- Console Errors - Optional console.error capture
- Replay Hooks - Integration with external replay tools
- Event Buffer - Click, scroll, input, resize events
- PII Masking - Automatic password field masking
Initialize the tracking SDK.
Parameters:
`typescript`
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:
`typescript`
const aurea = initAurea({
apiKey: 'ak_1234567890',
funnelId: 'fn_abcdefgh',
apiUrl: 'https://analytics.example.com/api',
debug: process.env.NODE_ENV === 'development',
});
---
Track a custom event.
Parameters:
- name (string): Event nameproperties
- (object, optional): Event properties
Example:
`typescript`
trackEvent('product_viewed', {
productId: 'prod_123',
productName: 'Premium Plan',
price: 99.00,
category: 'subscription',
});
---
Track a page view.
Parameters:
- name (string, optional): Page nameproperties
- (object, optional): Page properties
Example:
`typescript`
trackPage('Pricing Page', {
plan: 'premium',
billingCycle: 'monthly',
});
---
Track a conversion event.
Parameters:
`typescript`
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:
`typescript`
trackConversion({
type: 'purchase',
revenue: 149.99,
currency: 'USD',
orderId: 'order_abc123',
properties: {
plan: 'annual',
discount: 'SAVE20',
},
});
---
Identify a user.
Parameters:
- userId (string): Unique user identifiertraits
- (object, optional): User traits/properties
Example:
`typescript`
identifyUser('user_123', {
email: 'john@example.com',
name: 'John Doe',
plan: 'premium',
signupDate: '2024-01-15',
});
---
Get the current SDK instance.
Returns: AureaSDK | null
Example:
`typescript
import { getAurea } from 'aurea-tracking-sdk';
const aurea = getAurea();
if (aurea) {
aurea.track('custom_event');
}
`
Create a component to initialize the SDK:
`tsx
// 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:
`tsx
// app/layout.tsx
import { AureaTracking } from '@/components/aurea-tracking';
export default function RootLayout({ children }) {
return (
$3
`tsx
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 ;
}
`$3
`html
`v2.0 Features
$3
Maintain visitor identity across multiple domains:
`typescript
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
// Buy Now
// becomes: https://checkout.example.com/buy?_aurea=ses_xxx.anon_yyy
// Manual URL generation
const linkedUrl = aurea.getLinkerUrl('https://checkout.example.com/buy');
`$3
Track first-touch and last-touch UTM data:
`typescript
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 context
`$3
Track video engagement with milestones:
`typescript
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 finishes
`$3
Transform or filter events before sending:
`typescript
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**@'),
},
}));
`$3
Automatically filter bot traffic (enabled by default):
`typescript
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.
`$3
Control event volume for high-traffic sites:
`typescript
initAurea({
apiKey: 'your-api-key',
funnelId: 'your-funnel-id',
samplingRate: 0.1, // Only track 10% of events
});
`$3
Events that fail due to network issues are automatically retried:
`typescript
// Automatic: Failed events are stored in localStorage and retried when online// Manual retry
import { getAurea } from 'aurea-tracking-sdk';
const aurea = getAurea();
aurea?.retryFailedEvents();
`$3
Track clicks to external domains:
`typescript
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+)
$3
Automatically score visitors based on their engagement:
`typescript
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();
`$3
Track experiments and attribute conversions:
`typescript
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 context
`$3
Detect user frustration and UX issues:
`typescript
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' }
`$3
Detect when users are about to leave:
`typescript
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 }
`$3
Track when key elements come into view:
`typescript
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 }
`$3
Get real-time engagement scoring:
`typescript
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();
}
`$3
Capture JavaScript errors automatically:
`typescript
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 }
`$3
Integrate with external session replay tools:
`typescript
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();
`$3
Track progress through multi-page funnels:
`typescript
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
// }
`$3
Add custom attributes to all events:
`typescript
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();
`$3
Get detailed conversion timing:
`typescript
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
`typescript
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
$3
`typescript
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);
`$3
Events are automatically batched and sent in groups for better performance:
`typescript
initAurea({
apiKey: 'your-api-key',
funnelId: 'your-funnel-id',
batchSize: 20, // Send after 20 events
batchInterval: 5000, // Or after 5 seconds
});
`$3
`typescript
import { trackEvent } from 'aurea-tracking-sdk';try {
trackEvent('risky_operation', { value: 123 });
} catch (error) {
console.error('Failed to track event:', error);
}
`Configuration Examples
$3
`typescript
initAurea({
apiKey: 'ak_dev_1234567890',
funnelId: 'fn_dev_abcdefgh',
apiUrl: 'http://localhost:3000/api',
debug: true,
respectDoNotTrack: false, // Track in dev
});
`$3
`typescript
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.
`typescript
import type { AureaConfig, ConversionData } from 'aurea-tracking-sdk';
``MIT
For issues and questions:
- GitHub: https://github.com/yourusername/aurea-tracking-sdk/issues
- Documentation: https://docs.aureacrm.com
- Email: support@aureacrm.com