@ignitech/modules-facebook-pixel
v1.0.0
Published
Ignitech Modules - Facebook Pixel Integration
Downloads
95
Maintainers
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:
- Generate Event ID: Tự động tạo unique event ID cho mỗi event
- Send to Pixel: Gửi event đến Facebook Pixel với
eventID - 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=falseRuntime 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
websiteIdvàapiBaseUrl - [ ] Test với một event (PageView)
- [ ] Verify events trong Facebook Events Manager
- [ ] Test event deduplication
🆘 Troubleshooting
Pixel không load
- Kiểm tra
websiteIdđúng chưa - Kiểm tra
apiBaseUrlcó thể access được không - Kiểm tra Pixel có được enable trong admin panel không
- Enable debug mode để xem logs
Events không xuất hiện
- Kiểm tra Network tab xem API calls có thành công không
- Kiểm tra Facebook Events Manager > Test Events
- Kiểm tra Pixel ID đúng chưa
- Kiểm tra console logs (nếu debug mode)
Duplicate events
- Đảm bảo chỉ init module 1 lần
- Kiểm tra event_id được generate đúng
- 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
