UNPKG

multi-platform-tracking-sdk

Version:

๐Ÿš€ Professional Multi-Platform Tracking SDK for Facebook/Meta Pixel, Instagram Analytics & Google Tag Manager | Zero Dependencies | TypeScript Ready | Privacy Compliant GDPR/CCPA | Created by A. Z. M. Arif | Code Encover

586 lines (458 loc) โ€ข 17.2 kB
# ๐Ÿš€ Multi-Platform Tracking SDK | Facebook Meta Pixel | Instagram Analytics | Google Tag Manager [![npm version](https://img.shields.io/npm/v/multi-platform-tracking-sdk.svg)](https://www.npmjs.com/package/multi-platform-tracking-sdk) [![npm downloads](https://img.shields.io/npm/dm/multi-platform-tracking-sdk.svg)](https://www.npmjs.com/package/multi-platform-tracking-sdk) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/) [![Tests](https://img.shields.io/badge/Tests-44%20Passing-green.svg)](#testing) [![Build](https://github.com/azmarifdev/multi-platform-tracking-sdk/workflows/Tests/badge.svg)](https://github.com/azmarifdev/multi-platform-tracking-sdk/actions) [![Created by A. Z. M. Arif](https://img.shields.io/badge/Created%20by-A.%20Z.%20M.%20Arif-blue)](https://azmarif.dev) [![Code Encover](https://img.shields.io/badge/Company-Code%20Encover-green)](https://codeencover.com) > **๐ŸŽฏ Professional-grade Multi-Platform Tracking SDK for Facebook/Meta Pixel, > Instagram Analytics, and Google Tag Manager** > > **Created by [A. Z. M. Arif](https://azmarif.dev) | > [Code Encover](https://codeencover.com)** > **Follow on Social Media**: [GitHub](https://github.com/azmarifdev) โ€ข > [LinkedIn](https://linkedin.com/in/azmarifdev) โ€ข > [YouTube](https://youtube.com/@azmarifdev) โ€ข > [Twitter/X](https://twitter.com/azmarifdev) โ€ข > [Telegram](https://t.me/azmarifdev) [![npm version](https://img.shields.io/npm/v/multi-platform-tracking-sdk.svg)](https://www.npmjs.com/package/multi-platform-tracking-sdk) [![npm downloads](https://img.shields.io/npm/dm/multi-platform-tracking-sdk.svg)](https://www.npmjs.com/package/multi-platform-tracking-sdk) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/) [![Tests](https://img.shields.io/badge/Tests-44%20Passing-green.svg)](#testing) [![Build](https://github.com/azmarifdev/multi-platform-tracking-sdk/workflows/Tests/badge.svg)](https://github.com/azmarifdev/multi-platform-tracking-sdk/actions) > **Professional-grade tracking SDK for Facebook/Meta Pixel, Instagram, and > Google Tag Manager** > Zero dependencies โ€ข TypeScript ready โ€ข Framework agnostic โ€ข Privacy compliant ## โœจ Why Choose This SDK? - ๐ŸŽฏ **Complete Multi-Platform Support** - Facebook/Meta, Instagram, Google GTM - ๐Ÿ”’ **Privacy-First Design** - GDPR/CCPA compliant with automatic data hashing - ๐Ÿš€ **Zero Dependencies** - Self-contained, optimized implementation - ๐Ÿ“ฆ **Framework Agnostic** - Works with React, Vue, Angular, Node.js, vanilla JS - ๐Ÿ›ก๏ธ **Enterprise Ready** - TypeScript support, comprehensive error handling - โšก **Performance Optimized** - Tree-shakable, minimal bundle size (~15KB) ## ๐Ÿ“ฆ Installation ```bash # Choose your preferred package manager npm install multi-platform-tracking-sdk yarn add multi-platform-tracking-sdk pnpm add multi-platform-tracking-sdk bun add multi-platform-tracking-sdk ``` ## ๐Ÿš€ Quick Start ### 30 Second Setup ```typescript import { MetaPixelTracker } from 'multi-platform-tracking-sdk'; // 1. Initialize (client-side) const tracker = new MetaPixelTracker({ pixelId: 'YOUR_PIXEL_ID', debug: true, // Enable for development }); // 2. Track events await tracker.trackPageView(); await tracker.trackPurchase({ value: 99.99, currency: 'USD', content_ids: ['product-123'], }); // Done! ๐ŸŽ‰ Your tracking is now active ``` ### Server-Side Tracking ```typescript import { MetaConversionTracker } from 'multi-platform-tracking-sdk'; const tracker = new MetaConversionTracker({ accessToken: 'YOUR_ACCESS_TOKEN', pixelId: 'YOUR_PIXEL_ID', }); await tracker.trackPurchase({ eventSourceUrl: 'https://yoursite.com/checkout', userData: { email: 'customer@example.com', clientIpAddress: req.ip, clientUserAgent: req.headers['user-agent'], }, customData: { value: 99.99, currency: 'USD', contents: [{ id: 'product-123', quantity: 1 }], }, }); ``` ## ๐ŸŽฏ Core Features ### ๐Ÿ–ฅ๏ธ Client-Side Tracking Perfect for websites and web applications ```typescript const pixelTracker = new MetaPixelTracker({ pixelId: 'YOUR_PIXEL_ID' }); // Essential e-commerce events await pixelTracker.trackPageView(); await pixelTracker.trackViewContent({ content_ids: ['product-123'] }); await pixelTracker.trackAddToCart({ value: 29.99, currency: 'USD' }); await pixelTracker.trackPurchase({ value: 299.99, currency: 'USD' }); ``` ### ๐Ÿ”ง Server-Side Conversion API Enhanced data quality and iOS 14.5+ compliance ```typescript const conversionTracker = new MetaConversionTracker({ accessToken: 'YOUR_ACCESS_TOKEN', pixelId: 'YOUR_PIXEL_ID', }); await conversionTracker.trackPurchase({ eventSourceUrl: 'https://yoursite.com/checkout/success', userData: { email: 'customer@example.com', // Automatically hashed phone: '+1234567890', // Automatically hashed clientIpAddress: '192.168.1.1', clientUserAgent: 'Mozilla/5.0...', }, customData: { value: 299.99, currency: 'USD', contents: [{ id: 'product-1', quantity: 2, itemPrice: 149.99 }], }, }); ``` ### ๐Ÿ”„ Hybrid Tracking (Recommended) Best of both worlds with automatic deduplication ```typescript const hybridTracker = new HybridTracker({ pixelId: 'YOUR_PIXEL_ID', serverEndpoint: '/api/track', }); // Tracks on both client and server with deduplication await hybridTracker.trackPurchase({ value: 199.99, currency: 'USD', eventId: 'unique-purchase-123', // Prevents duplicate counting }); ``` ## ๐Ÿ“š Framework Integration ### โš›๏ธ React/Next.js ```typescript // hooks/useTracking.ts import { MetaPixelTracker } from 'multi-platform-tracking-sdk'; const tracker = new MetaPixelTracker({ pixelId: process.env.NEXT_PUBLIC_META_PIXEL_ID! }); export const useTracking = () => { const trackPurchase = (orderData: any) => { return tracker.trackPurchase({ value: orderData.total, currency: orderData.currency, content_ids: orderData.items.map((item: any) => item.id) }); }; return { trackPurchase }; }; // components/CheckoutButton.tsx import { useTracking } from '../hooks/useTracking'; export default function CheckoutButton({ orderData }: any) { const { trackPurchase } = useTracking(); const handleCheckout = async () => { await trackPurchase(orderData); // Process checkout... }; return <button onClick={handleCheckout}>Complete Purchase</button>; } ``` ### ๐ŸŸข Node.js/Express ```typescript // middleware/tracking.ts import { MetaConversionTracker } from 'multi-platform-tracking-sdk'; const tracker = new MetaConversionTracker({ accessToken: process.env.META_ACCESS_TOKEN!, pixelId: process.env.META_PIXEL_ID!, }); export const trackingMiddleware = (req: any, res: any, next: any) => { req.tracking = tracker; next(); }; // routes/orders.ts app.post('/orders', trackingMiddleware, async (req, res) => { const order = await createOrder(req.body); // Track the purchase await req.tracking.trackPurchase({ eventSourceUrl: `${req.protocol}://${req.get('host')}/orders`, userData: { email: req.body.customerEmail, clientIpAddress: req.ip, clientUserAgent: req.headers['user-agent'], }, customData: { value: order.total, currency: order.currency, contents: order.items.map((item) => ({ id: item.productId, quantity: item.quantity, itemPrice: item.price, })), }, }); res.json(order); }); ``` ## ๐Ÿ” Privacy & Compliance ### GDPR/CCPA Ready ```typescript // Automatic PII hashing - no manual setup required const userData = { email: 'user@example.com', // Automatically SHA-256 hashed phone: '+1234567890', // Automatically SHA-256 hashed firstName: 'John', // Automatically hashed lastName: 'Doe', // Automatically hashed }; // California compliance await tracker.trackPurchase({ // ... event data dataProcessingOptions: ['LDU'], dataProcessingOptionsCountry: 1, dataProcessingOptionsState: 1000, }); ``` ### Consent Management ```typescript // Check user consent before tracking if (userConsent.analytics) { await tracker.trackPageView(); } // Opt-out specific users await tracker.trackEvent({ // ... event data optOut: true, // Excludes from ad optimization }); ``` ## ๐Ÿงช Testing & Development ### Debug Mode ```typescript const tracker = new MetaPixelTracker({ pixelId: 'YOUR_PIXEL_ID', debug: true, // Enables detailed console logging }); ``` ### Test Events ```typescript const tracker = new MetaConversionTracker({ accessToken: 'YOUR_ACCESS_TOKEN', pixelId: 'YOUR_PIXEL_ID', testEventCode: 'TEST12345', // From Facebook Events Manager }); ``` ### Connection Validation ```typescript // Test your API connection const testResult = await tracker.testConnection(); if (testResult.success) { console.log('โœ… API connection successful'); } else { console.error('โŒ Connection failed:', testResult.error); } ``` ## ๐Ÿ“Š Event Reference ### E-commerce Events ```typescript // Page view await tracker.trackPageView(); // Product view await tracker.trackViewContent({ content_ids: ['product-123'], content_type: 'product', value: 29.99, currency: 'USD', }); // Add to cart await tracker.trackAddToCart({ content_ids: ['product-123'], value: 29.99, currency: 'USD', }); // Purchase completed await tracker.trackPurchase({ value: 299.99, currency: 'USD', content_ids: ['product-123', 'product-456'], content_type: 'product', }); ``` ### Lead Generation Events ```typescript // Lead form submission await tracker.trackLead({ value: 100, currency: 'USD', content_name: 'Newsletter Signup', }); // User registration await tracker.trackCompleteRegistration({ content_name: 'Account Creation', }); // Custom events await tracker.trackCustomEvent('custom_event_name', { custom_parameter: 'value', value: 50, currency: 'USD', }); ``` ## โšก Performance Features ### Bundle Size Optimization ```typescript // Tree-shaking friendly - only import what you need import { MetaPixelTracker } from 'multi-platform-tracking-sdk/pixel'; import { MetaConversionTracker } from 'multi-platform-tracking-sdk/conversion'; // Total bundle impact: ~15KB gzipped ``` ### Batch Processing ```typescript // Send multiple events efficiently const events = [ { eventName: 'PageView', eventSourceUrl: 'https://example.com/page1' }, { eventName: 'ViewContent', eventSourceUrl: 'https://example.com/product' }, { eventName: 'AddToCart', eventSourceUrl: 'https://example.com/cart' }, ]; const response = await tracker.sendBatchEvents(events); console.log(`โœ… Processed ${response.eventsReceived} events`); ``` ### Error Handling ```typescript try { await tracker.trackPurchase(purchaseData); } catch (error) { if (error.code === 'VALIDATION_ERROR') { console.error('Data validation failed:', error.message); } else if (error.code === 'API_ERROR') { console.error('Facebook API error:', error.message); console.error('Trace ID:', error.fbtrace_id); } else if (error.code === 'NETWORK_ERROR') { console.error('Network error:', error.message); // Implement retry logic } } ``` ## ๐ŸŒ Environment Setup ### Environment Variables ```env # Client-side (use NEXT_PUBLIC_ prefix for Next.js) NEXT_PUBLIC_META_PIXEL_ID=your_pixel_id NEXT_PUBLIC_META_DEBUG=false # Server-side META_ACCESS_TOKEN=your_access_token META_PIXEL_ID=your_pixel_id META_APP_SECRET=your_app_secret META_DEBUG=false META_TEST_EVENT_CODE=TEST12345 ``` ### TypeScript Support Full TypeScript definitions included: ```typescript import type { MetaPixelConfig, ConversionAPIConfig, ServerEventData, UserData, CustomData, EventResponse, } from 'multi-platform-tracking-sdk'; ``` ## ๐Ÿš€ Migration Guide ### From Facebook Pixel ```typescript // Before (Facebook Pixel) fbq('track', 'Purchase', { value: 29.99, currency: 'USD', }); // After (Multi-Platform SDK) await tracker.trackPurchase({ value: 29.99, currency: 'USD', }); ``` ### From facebook-nodejs-business-sdk ```typescript // Before (facebook-nodejs-business-sdk) const { ServerEvent, EventRequest, UserData, } = require('facebook-nodejs-business-sdk'); // ... complex setup with many lines // After (Multi-Platform SDK) await tracker.trackPurchase({ eventSourceUrl: 'https://example.com', userData: { email: 'user@example.com' }, customData: { value: 29.99, currency: 'USD' }, }); ``` ## ๐Ÿค Contributing We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md). ### Development Setup ```bash # Clone the repository git clone https://github.com/azmarifdev/multi-platform-tracking-sdk.git # Install dependencies npm install # Run tests npm test # Build the project npm run build ``` ## ๐Ÿ“„ License MIT ยฉ [A. Z. M. Arif](https://github.com/azmarifdev) ## ๐Ÿ†˜ Support - ๐Ÿ“– **Documentation**: [GitHub Wiki](https://github.com/azmarifdev/multi-platform-tracking-sdk/wiki) - ๐Ÿ› **Bug Reports**: [GitHub Issues](https://github.com/azmarifdev/multi-platform-tracking-sdk/issues) - ๐Ÿ’ฌ **Discussions**: [GitHub Discussions](https://github.com/azmarifdev/multi-platform-tracking-sdk/discussions) - ๐Ÿ“ง **Email**: hello@azmarif.dev - ๐ŸŒ **Portfolio**: [azmarif.dev](https://azmarif.dev) ## ๐Ÿ‘จโ€๐Ÿ’ป About the Author **A. Z. M. Arif** is a Full-Stack Software Engineer and the founder of **Code Encover**, specializing in enterprise-grade web applications, analytics solutions, and developer tools. ### ๏ฟฝ Connect with A. Z. M. Arif: - ๐ŸŒ **Portfolio**: [azmarif.dev](https://azmarif.dev) - ๐Ÿ’ผ **LinkedIn**: [linkedin.com/in/azmarifdev](https://linkedin.com/in/azmarifdev) - ๐Ÿ™ **GitHub**: [github.com/azmarifdev](https://github.com/azmarifdev) - ๐Ÿ“บ **YouTube**: [youtube.com/@azmarifdev](https://youtube.com/@azmarifdev) - ๐Ÿฆ **Twitter/X**: [twitter.com/azmarifdev](https://twitter.com/azmarifdev) - ๐Ÿ“ฑ **Telegram**: [t.me/azmarifdev](https://t.me/azmarifdev) ### ๐Ÿข About Code Encover **Code Encover** is a leading software development company founded and led by **A. Z. M. Arif**, dedicated to delivering innovative, scalable, and enterprise-grade solutions for businesses worldwide. Our mission is to empower organizations with cutting-edge technology and robust digital solutions. #### ๐ŸŽฏ Our Expertise: - **๐Ÿ”ง Custom Software Development** - Tailored solutions for unique business needs - **๐Ÿ“Š Analytics & Tracking Solutions** - Advanced data insights and conversion optimization - **๐Ÿš€ Enterprise Web Applications** - Scalable, secure, and performance-optimized platforms - **๐Ÿ“ฑ Mobile Application Development** - Cross-platform mobile solutions for iOS and Android - **โ˜๏ธ Cloud Solutions & DevOps** - Modern infrastructure and deployment strategies - **๐Ÿ›ก๏ธ Security & Compliance** - GDPR, CCPA, and enterprise-grade security implementations #### ๐ŸŒŸ Why Choose Code Encover: - **Proven Track Record** - Successfully delivered 50+ projects across various industries - **Expert Team** - Led by experienced engineers with deep technical expertise - **Quality First** - Rigorous testing, code reviews, and best practices - **Client-Centric** - Transparent communication and collaborative development approach - **Innovation Focus** - Staying ahead with latest technologies and methodologies #### ๐ŸŒ Learn More: - **Website**: [codeencover.com](https://codeencover.com) - **Get in Touch**: hello@codeencover.com - **Follow**: [@codeencover](https://github.com/orgs/codeencover) on GitHub *Ready to transform your business with technology? Let's build something amazing together.* ## ๐Ÿ“Š Changelog See [CHANGELOG.md](CHANGELOG.md) for detailed release history. --- <div align="center"> **๐Ÿš€ Built with โค๏ธ by [A. Z. M. Arif](https://azmarif.dev) | [Code Encover](https://codeencover.com)** **Follow @azmarifdev on all platforms for updates and more projects!** [โญ Star on GitHub](https://github.com/azmarifdev/multi-platform-tracking-sdk) โ€ข [๐Ÿ“ฆ View on NPM](https://www.npmjs.com/package/multi-platform-tracking-sdk) โ€ข [๐Ÿ“– Read the Docs](https://github.com/azmarifdev/multi-platform-tracking-sdk/wiki) โ€ข [๐ŸŒ Visit Portfolio](https://azmarif.dev) **SEO Keywords**: Facebook Pixel, Meta Pixel, Instagram Analytics, Google Tag Manager, GTM, Conversion API, Tracking SDK, A. Z. M. Arif, azmarifdev, Code Encover, TypeScript, JavaScript, React, Vue, Angular, Node.js, GDPR, CCPA, Privacy Compliant, Zero Dependencies, Multi-Platform Analytics </div>