npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ignitech/modules-facebook-pixel

v1.0.0

Published

Ignitech Modules - Facebook Pixel Integration

Downloads

95

Readme

Facebook Pixel Module - Reusable Library

Version: 1.0.0
Last Updated: 2025-01-20
For: Frontend Development Team (Public Websites)
Feature: Reusable Facebook Pixel Integration Module


📋 Overview

Module Facebook Pixel là một thư viện JavaScript/TypeScript độc lập có thể được nhúng vào bất kỳ website nào trong hệ thống. Module này tự động:

  • ✅ Lấy Pixel ID từ API
  • ✅ Load Facebook Pixel script
  • ✅ Track events tự động
  • ✅ Event deduplication (client-side + server-side)
  • ✅ Gửi events đến backend với event_id
  • ✅ Xử lý enable/disable
  • ✅ Error handling

Lợi ích:

  • Chỉ cần tích hợp 1 lần, dùng cho tất cả websites
  • Dễ maintain và update
  • Consistent tracking across all websites
  • Tự động sync với backend

📦 Installation

NPM Package

npm install @ignitech/modules-facebook-pixel

🚀 Quick Start

import { initFacebookPixel, trackEvent } from '@ignitech/modules-facebook-pixel';

// Initialize
await initFacebookPixel({
  websiteId: '550e8400-e29b-41d4-a716-446655440000',
  apiBaseUrl: 'https://api.example.com',
});

// Track events
trackEvent('PageView');
trackEvent('ViewContent', { content_name: 'Product Name' });

📝 API Reference

initFacebookPixel(config)

Khởi tạo Facebook Pixel module.

Parameters:

interface InitConfig {
  websiteId: string;           // Required: Website ID
  apiBaseUrl: string;          // Required: Backend API base URL
  autoTrackPageView?: boolean;  // Optional: Auto track PageView (default: true)
  debug?: boolean;              // Optional: Enable debug logs (default: false)
}

Example:

await initFacebookPixel({
  websiteId: '550e8400-e29b-41d4-a716-446655440000',
  apiBaseUrl: 'https://api.example.com',
  autoTrackPageView: true,
  debug: false,
});

Returns: Promise<void>


trackEvent(eventName, eventData?, options?)

Track event đến Facebook Pixel và backend.

Parameters:

trackEvent(
  eventName: string,           // Facebook Pixel event name
  eventData?: object,          // Event data
  options?: {
    sendToBackend?: boolean;    // Also send to backend (default: true)
    eventId?: string;           // Custom event ID (auto-generated if not provided)
  }
)

Example:

// Simple event
trackEvent('PageView');

// Event with data
trackEvent('ViewContent', {
  content_name: 'Laptop Dell XPS 15',
  content_ids: ['prod_123'],
  content_type: 'product',
  value: 25000000,
  currency: 'VND',
});

// Event with custom ID
trackEvent('Purchase', {
  value: 50000000,
  currency: 'VND',
}, {
  eventId: 'custom_event_id_123',
});

trackEcommerceEvent(eventType, data)

Helper function để track e-commerce events với format chuẩn.

Parameters:

trackEcommerceEvent(
  eventType: 'ViewContent' | 'AddToCart' | 'InitiateCheckout' | 'Purchase' | ...,
  data: {
    product?: {
      productId: string;
      productName: string;
      productPrice: number;
      quantity?: number;
    };
    products?: Array<{...}>;  // For purchase events
    orderId?: string;
    orderValue?: number;
    currency?: string;
  }
)

Example:

// View Product
trackEcommerceEvent('ViewContent', {
  product: {
    productId: 'prod_123',
    productName: 'Laptop Dell XPS 15',
    productPrice: 25000000,
  },
  currency: 'VND',
});

// Add to Cart
trackEcommerceEvent('AddToCart', {
  product: {
    productId: 'prod_123',
    productName: 'Laptop Dell XPS 15',
    productPrice: 25000000,
    quantity: 1,
  },
  currency: 'VND',
});

// Purchase
trackEcommerceEvent('Purchase', {
  orderId: 'ORD-2025-01-20-0001',
  orderValue: 50000000,
  products: [
    {
      productId: 'prod_123',
      productName: 'Laptop Dell XPS 15',
      productPrice: 25000000,
      quantity: 1,
    },
  ],
  currency: 'VND',
});

isPixelEnabled()

Kiểm tra xem Pixel có được enable không.

Returns: Promise<boolean>

Example:

const enabled = await isPixelEnabled();
if (enabled) {
  trackEvent('CustomEvent');
}

getPixelId()

Lấy Pixel ID hiện tại.

Returns: Promise<string | null>


🎯 Implementation Example

Full Integration Example

// app.ts or main.ts
import { 
  initFacebookPixel, 
  trackEcommerceEvent,
  trackEvent 
} from '@ignitech/modules-facebook-pixel';

// Initialize on app start
async function init() {
  try {
    await initFacebookPixel({
      websiteId: '550e8400-e29b-41d4-a716-446655440000',
      apiBaseUrl: process.env.API_BASE_URL || 'https://api.example.com',
      autoTrackPageView: true,
      debug: process.env.NODE_ENV === 'development',
    });
    
    console.log('Facebook Pixel initialized');
  } catch (error) {
    console.error('Failed to initialize Facebook Pixel:', error);
  }
}

// Track product view
function onProductView(product: any) {
  trackEcommerceEvent('ViewContent', {
    product: {
      productId: product.id,
      productName: product.name,
      productPrice: product.price,
    },
    currency: 'VND',
  });
}

// Track add to cart
function onAddToCart(product: any, quantity: number = 1) {
  trackEcommerceEvent('AddToCart', {
    product: {
      productId: product.id,
      productName: product.name,
      productPrice: product.price,
      quantity,
    },
    currency: 'VND',
  });
}

// Track purchase
function onPurchase(order: any) {
  trackEcommerceEvent('Purchase', {
    orderId: order.id,
    orderValue: order.total,
    products: order.items.map((item: any) => ({
      productId: item.productId,
      productName: item.productName,
      productPrice: item.price,
      quantity: item.quantity,
    })),
    currency: 'VND',
  });
}

// Initialize
init();

🔄 Event Deduplication

Module tự động xử lý event deduplication:

  1. Generate Event ID: Tự động tạo unique event ID cho mỗi event
  2. Send to Pixel: Gửi event đến Facebook Pixel với eventID
  3. Send to Backend: Gửi cùng event đến backend với facebookEventId

Facebook sẽ tự động deduplicate events có cùng event_id.

Example:

// Module tự động:
// 1. Generate: eventId = "fbp_1705747200000_abc123"
// 2. fbq('track', 'AddToCart', data, { eventID: eventId })
// 3. POST /analytics/track/ecommerce { ..., facebookEventId: eventId }

⚙️ Configuration

Environment Variables

# .env
REACT_APP_API_BASE_URL=https://api.example.com
REACT_APP_WEBSITE_ID=550e8400-e29b-41d4-a716-446655440000
REACT_APP_PIXEL_DEBUG=false

Runtime Configuration

// config.ts
export const pixelConfig = {
  websiteId: process.env.REACT_APP_WEBSITE_ID!,
  apiBaseUrl: process.env.REACT_APP_API_BASE_URL!,
  autoTrackPageView: true,
  debug: process.env.REACT_APP_PIXEL_DEBUG === 'true',
};

🎨 React Integration

React Hook

// hooks/useFacebookPixel.ts
import { useEffect } from 'react';
import { initFacebookPixel, trackEvent } from '@ignitech/modules-facebook-pixel';

export function useFacebookPixel(websiteId: string) {
  useEffect(() => {
    initFacebookPixel({
      websiteId,
      apiBaseUrl: process.env.REACT_APP_API_BASE_URL!,
    });
  }, [websiteId]);

  return {
    trackEvent,
  };
}

// Usage
function ProductPage({ product }) {
  const { trackEvent } = useFacebookPixel(websiteId);

  useEffect(() => {
    trackEvent('ViewContent', {
      content_name: product.name,
      content_ids: [product.id],
      value: product.price,
      currency: 'VND',
    });
  }, [product]);

  return <div>...</div>;
}

React Component Wrapper

// components/FacebookPixelProvider.tsx
import React, { useEffect, createContext, useContext } from 'react';
import { initFacebookPixel, trackEvent } from '@ignitech/modules-facebook-pixel';

const FacebookPixelContext = createContext<{
  trackEvent: typeof trackEvent;
} | null>(null);

export function FacebookPixelProvider({
  websiteId,
  children,
}: {
  websiteId: string;
  children: React.ReactNode;
}) {
  useEffect(() => {
    initFacebookPixel({
      websiteId,
      apiBaseUrl: process.env.REACT_APP_API_BASE_URL!,
    });
  }, [websiteId]);

  return (
    <FacebookPixelContext.Provider value={{ trackEvent }}>
      {children}
    </FacebookPixelContext.Provider>
  );
}

export function useFacebookPixel() {
  const context = useContext(FacebookPixelContext);
  if (!context) {
    throw new Error('useFacebookPixel must be used within FacebookPixelProvider');
  }
  return context;
}

// Usage in App.tsx
function App() {
  return (
    <FacebookPixelProvider websiteId={websiteId}>
      <YourApp />
    </FacebookPixelProvider>
  );
}

🛠️ Vue.js Integration

// plugins/facebook-pixel.ts
import { initFacebookPixel, trackEvent } from '@ignitech/modules-facebook-pixel';

export default {
  install(app: any, options: { websiteId: string; apiBaseUrl: string }) {
    initFacebookPixel({
      websiteId: options.websiteId,
      apiBaseUrl: options.apiBaseUrl,
    });

    app.config.globalProperties.$trackEvent = trackEvent;
  },
};

// main.ts
import FacebookPixel from './plugins/facebook-pixel';

app.use(FacebookPixel, {
  websiteId: '550e8400-e29b-41d4-a716-446655440000',
  apiBaseUrl: 'https://api.example.com',
});

// Usage in component
this.$trackEvent('ViewContent', { ... });

📊 Supported Events

Module hỗ trợ tất cả Facebook Pixel Standard Events:

| Event | Description | Usage | |-------|-------------|-------| | PageView | Page view | Auto-tracked | | ViewContent | View product/content | trackEcommerceEvent('ViewContent', {...}) | | AddToCart | Add item to cart | trackEcommerceEvent('AddToCart', {...}) | | InitiateCheckout | Begin checkout | trackEcommerceEvent('InitiateCheckout', {...}) | | AddPaymentInfo | Add payment info | trackEcommerceEvent('AddPaymentInfo', {...}) | | Purchase | Complete purchase | trackEcommerceEvent('Purchase', {...}) | | Lead | Form submission | trackEvent('Lead', {...}) | | Search | Search query | trackEvent('Search', {...}) | | ViewCategory | View category | trackEvent('ViewCategory', {...}) | | AddToWishlist | Add to wishlist | trackEvent('AddToWishlist', {...}) |


🐛 Error Handling

Module tự động xử lý errors:

  • ✅ Pixel không được cấu hình → Silent fail
  • ✅ Pixel bị disable → Silent fail
  • ✅ API error → Log warning, không break app
  • ✅ Network error → Retry logic

Debug Mode:

initFacebookPixel({
  websiteId: '...',
  apiBaseUrl: '...',
  debug: true,  // Enable console logs
});

📦 Build & Distribution

Build Module

# Install dependencies
npm install

# Build
npm run build

# Output:
# - dist/index.js (CommonJS)
# - dist/index.mjs (ES Module)
# - dist/index.d.ts (TypeScript definitions)

Publish to NPM

npm publish --access public

✅ Integration Checklist

Cho mỗi website mới:

  • [ ] Install module: npm install @ignitech/modules-facebook-pixel
  • [ ] Import và init trong app entry point
  • [ ] Pass websiteIdapiBaseUrl
  • [ ] Test với một event (PageView)
  • [ ] Verify events trong Facebook Events Manager
  • [ ] Test event deduplication

🆘 Troubleshooting

Pixel không load

  1. Kiểm tra websiteId đúng chưa
  2. Kiểm tra apiBaseUrl có thể access được không
  3. Kiểm tra Pixel có được enable trong admin panel không
  4. Enable debug mode để xem logs

Events không xuất hiện

  1. Kiểm tra Network tab xem API calls có thành công không
  2. Kiểm tra Facebook Events Manager > Test Events
  3. Kiểm tra Pixel ID đúng chưa
  4. Kiểm tra console logs (nếu debug mode)

Duplicate events

  1. Đảm bảo chỉ init module 1 lần
  2. Kiểm tra event_id được generate đúng
  3. Verify backend nhận được facebookEventId

📚 References


🔄 Version History

  • v1.0.0 (2025-01-20): Initial release
    • Basic tracking functionality
    • Event deduplication
    • Auto initialization
    • React/Vue support

Version: 1.0.0
Last Updated: 2025-01-20