unified-tracking
v3.0.1
Published
Unified analytics and error tracking plugin for React + Capacitor Apps
Maintainers
Keywords
Readme
Unified Tracking
A comprehensive Capacitor plugin that provides a unified API for multiple analytics and error tracking providers. Track events, identify users, and monitor errors across all major platforms with a single, consistent interface.
✨ Features
- 🚀 Zero Dependencies - Works out of the box, no required dependencies
- 🎯 Provider-less - No React Context/Providers needed, works in dynamic components
- 📊 Multiple Analytics - Support for Google Analytics, Mixpanel, Segment, PostHog, Amplitude, Firebase
- 🐛 Error Tracking - Integrated Sentry, Bugsnag, Rollbar, DataDog, LogRocket support
- ⚛️ React Ready - Simple hooks that work anywhere, even in dynamically injected components
- 📱 Cross Platform - Web, iOS, Android support via optional Capacitor integration
- 🛡️ Privacy First - Built-in consent management
- 📦 Tree-Shakeable - Only bundle what you use
- 🎯 TypeScript - Full type safety and autocompletion
📦 Installation
For Capacitor Projects
# Install the plugin
npm install unified-tracking
# For iOS
npx cap add ios
npx cap sync ios
# For Android
npx cap add android
npx cap sync androidFor React Web Projects
# Install the plugin
npm install unified-tracking
# Install peer dependencies for React support
npm install react@^19.0.0 @capacitor/core@^7.4.3Manual Setup (CLI Helper)
The plugin includes a setup helper to guide you through configuration:
npx unified-tracking-setup🚀 Quick Start
1. Initialize the Plugin
import { UnifiedTracking } from 'unified-tracking';
// Initialize with your providers
await UnifiedTracking.initialize({
analytics: {
providers: ['google-analytics', 'mixpanel'],
googleAnalytics: {
measurementId: 'G-XXXXXXXXXX',
},
mixpanel: {
token: 'YOUR_MIXPANEL_TOKEN',
},
},
errorTracking: {
providers: ['sentry'],
sentry: {
dsn: 'YOUR_SENTRY_DSN',
},
},
});2. Track Events
// Direct API usage
await UnifiedTracking.trackEvent('purchase_completed', {
product_id: '123',
price: 99.99,
currency: 'USD'
});
// React Hook usage
import { useUnifiedTracking } from 'unified-tracking/react';
function MyComponent() {
const { trackEvent, identify, logError } = useUnifiedTracking();
const handlePurchase = async () => {
await trackEvent('purchase_completed', {
product_id: '123',
price: 99.99
});
};
return <button onClick={handlePurchase}>Buy Now</button>;
}3. Identify Users
await UnifiedTracking.identify('user-123', {
email: '[email protected]',
name: 'John Doe',
plan: 'premium',
});4. Track Errors
try {
// Your code
} catch (error) {
await UnifiedTracking.logError(error, {
context: 'checkout_process',
userId: 'user-123'
});
}
## 📦 Installation Options
### Pure JavaScript/TypeScript
```typescript
import { UnifiedTracking } from 'unified-tracking';React Integration
import { useTrackEvent, useUnifiedTracking } from 'unified-tracking/react';Capacitor Integration (Optional)
import { UnifiedTracking } from 'unified-tracking/capacitor';🔧 Configuration
Minimal Configuration
// Auto-detects available SDKs
await UnifiedTracking.initialize();With Provider Configuration
await UnifiedTracking.initialize({
analytics: {
providers: ['google-analytics', 'mixpanel'],
googleAnalytics: {
measurementId: 'G-XXXXXXXXXX',
},
mixpanel: {
token: 'YOUR_MIXPANEL_TOKEN',
},
},
errorTracking: {
providers: ['sentry'],
sentry: {
dsn: 'YOUR_SENTRY_DSN',
},
},
});🎣 React Hooks (No Providers Required!)
useTrackEvent
const { trackEvent, isTracking, lastError } = useTrackEvent();
await trackEvent('purchase_completed', {
product_id: '123',
price: 99.99,
});useUnifiedTracking
const tracking = useUnifiedTracking();
// All methods available
await tracking.track('event_name', { properties });
await tracking.identify('user123', { email: '[email protected]' });
await tracking.logError(new Error('Something went wrong'));
await tracking.logRevenue({ amount: 99.99, currency: 'USD' });📊 Supported Providers
Analytics
- Google Analytics 4
- Mixpanel
- Segment
- PostHog
- Amplitude
- Firebase Analytics
- Heap
- Matomo
Error Tracking
- Sentry
- Bugsnag
- Rollbar
- LogRocket
- Raygun
- DataDog RUM
- AppCenter
- Firebase Crashlytics
🔌 Dynamic Provider Loading
Providers are loaded dynamically based on availability:
// The package detects which SDKs are available
// and only initializes those providers
// If you have gtag loaded, Google Analytics will work
// If you have mixpanel loaded, Mixpanel will work
// No errors if SDKs are missing - graceful degradation🛡️ Privacy & Consent
Built-in consent management:
await UnifiedTracking.setConsent({
analytics: true,
errorTracking: true,
marketing: false,
personalization: false,
});📱 Platform Support
- ✅ Web (all modern browsers)
- ✅ React 16.8+
- ✅ React Native (via Capacitor)
- ✅ iOS (via Capacitor)
- ✅ Android (via Capacitor)
- ✅ Electron
🤝 Migration
From React Context-based Analytics
// Before (with providers)
<AnalyticsProvider config={config}>
<App />
</AnalyticsProvider>
// After (no providers!)
UnifiedTracking.initialize(config);
// Use hooks anywhere!From Individual SDKs
// Before
gtag('event', 'purchase', { value: 99.99 });
mixpanel.track('purchase', { value: 99.99 });
// After
UnifiedTracking.track('purchase', { value: 99.99 });
// Automatically sent to all configured providers📚 Documentation
- API Reference - Complete API documentation
- React Hooks Guide - All available React hooks
- Provider Configuration - Provider-specific settings
- Migration Guide - Migrate from other solutions
- Examples - Complete examples for various use cases
🏗️ Advanced Usage
Custom Providers
import { ProviderRegistry, BaseAnalyticsProvider } from 'unified-tracking';
@RegisterProvider({
id: 'my-analytics',
name: 'My Analytics',
type: 'analytics',
})
class MyAnalyticsProvider extends BaseAnalyticsProvider {
// Implementation
}Direct SDK Access
// Access underlying provider instances
const providers = await UnifiedTracking.getActiveProviders();📊 Analytics & Metrics
This plugin provides comprehensive analytics tracking:
- Event Tracking: Custom events with properties
- User Identification: Associate events with users
- Revenue Tracking: E-commerce and subscription revenue
- Screen/Page Views: Automatic or manual page tracking
- User Properties: Set custom user attributes
- Session Tracking: Track user sessions across platforms
🚨 Error Tracking
Built-in error handling capabilities:
- Automatic Error Capture: Unhandled exceptions
- Manual Error Logging: Log custom errors with context
- User Context: Associate errors with specific users
- Breadcrumbs: Track user actions leading to errors
- Performance Monitoring: Track performance metrics
- Custom Tags: Add custom metadata to errors
🔒 Privacy & Compliance
- GDPR Compliant: Built-in consent management
- CCPA Support: California Consumer Privacy Act compliance
- Data Minimization: Only collect necessary data
- Anonymization: Option to anonymize sensitive data
- User Control: Users can opt-out of tracking
🛠️ Development
Building from Source
# Clone the repository
git clone https://github.com/aoneahsan/unified-tracking.git
cd unified-tracking
# Install dependencies
yarn install
# Build the plugin
yarn build
# Run tests
yarn test
# Run linting
yarn lintContributing
We welcome contributions! Please see our Contributing Guide for details.
📄 License
MIT © Ahsan Mahmood
🤝 Support
🌟 Show Your Support
Give a ⭐️ if this project helped you!
