multi-platform-tracking-sdk
TypeScript icon, indicating that this package has built-in type declarations

2.4.3Β β€’Β PublicΒ β€’Β Published

πŸš€ Multi-Platform Tracking SDK | Facebook Meta Pixel | Instagram Analytics | Google Tag Manager

npm version npm downloads License: MIT TypeScript Tests Build Created by A. Z. M. Arif Code Encover

🎯 Professional-grade Multi-Platform Tracking SDK for Facebook/Meta Pixel, Instagram Analytics, and Google Tag Manager

Created by A. Z. M. Arif | Code Encover
Follow on Social Media: GitHub β€’ LinkedIn β€’ YouTube β€’ Twitter/X β€’ Telegram

npm version npm downloads License: MIT TypeScript Tests Build

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

# 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

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

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

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

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

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

// 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

// 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

// 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

// 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

const tracker = new MetaPixelTracker({
    pixelId: 'YOUR_PIXEL_ID',
    debug: true, // Enables detailed console logging
});

Test Events

const tracker = new MetaConversionTracker({
    accessToken: 'YOUR_ACCESS_TOKEN',
    pixelId: 'YOUR_PIXEL_ID',
    testEventCode: 'TEST12345', // From Facebook Events Manager
});

Connection Validation

// 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

// 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

// 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

// 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

// 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

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

# 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:

import type {
    MetaPixelConfig,
    ConversionAPIConfig,
    ServerEventData,
    UserData,
    CustomData,
    EventResponse,
} from 'multi-platform-tracking-sdk';

πŸš€ Migration Guide

From Facebook Pixel

// 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

// 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.

Development Setup

# 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

πŸ†˜ Support

πŸ‘¨β€πŸ’» 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:

🏒 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:

Ready to transform your business with technology? Let's build something amazing together.

πŸ“Š Changelog

See CHANGELOG.md for detailed release history.


πŸš€ Built with ❀️ by A. Z. M. Arif | Code Encover

Follow @azmarifdev on all platforms for updates and more projects!

⭐ Star on GitHub β€’ πŸ“¦ View on NPM β€’ πŸ“– Read the Docs β€’ 🌐 Visit Portfolio

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

Package Sidebar

Install

npm i multi-platform-tracking-sdk

Weekly Downloads

142

Version

2.4.3

License

MIT

Unpacked Size

149 kB

Total Files

13

Last publish

Collaborators

  • azmarifdev