@tapbuy-public/pixel-tracker
v1.1.0
Published
Cross-framework pixel tracking for Tapbuy checkout
Readme
@tapbuy-public/pixel-tracker
Cross-framework pixel tracking library for Tapbuy checkout analytics.
Features
- 🚀 Cross-framework support - Works with React, Vue, and vanilla JavaScript
- 🎯 Multiple tracking methods - Image pixels, Fetch API, and Beacon API
- 🍪 Cookie collection - Automatically grab and send cookies with configurable selection
- 🛡️ TypeScript support - Full type definitions included
- ⚡ Lightweight - Minimal bundle size with no dependencies
- 🔧 Configurable - Timeout, error handling, and success callbacks
- 🌐 SSR compatible - Generate pixel HTML for server-side rendering
Installation
npm install @tapbuy-public/pixel-trackeryarn add @tapbuy-public/pixel-trackerQuick Start
Vanilla JavaScript/TypeScript
import { TapbuyPixelTracker } from '@tapbuy-public/pixel-tracker';
const tracker = new TapbuyPixelTracker({
timeout: 5000,
onSuccess: () => console.log('Pixel fired successfully'),
onError: (error) => console.error('Pixel failed:', error),
cookies: {
keys: ['sessionId', 'userId'], // Collect specific cookies
// keys: ['_ga*'], // Or collect cookies matching patterns
// keys: 'all', // Or collect all cookies
// keys: 'none' // Or collect no cookies (default)
}
});
// Fire a pixel - cookies will be automatically appended as query parameters
await tracker.firePixel('https://analytics.tapbuy.com/pixel.gif');
// Get collected cookies as an object
const cookies = tracker.getCookies();
console.log('Collected cookies:', cookies);
// Override cookie options for getCookies
const themeCookie = tracker.getCookies({ keys: ['theme'] });
console.log('Theme cookie:', themeCookie);React Hook
import { useTapbuyPixel } from '@tapbuy-public/pixel-tracker';
function CheckoutPage() {
const { firePixel, getCookies } = useTapbuyPixel({
onSuccess: () => console.log('Conversion tracked!'),
onError: (error) => console.error('Tracking failed:', error),
cookies: {
keys: ['cartId', 'customerId'] // Collect specific cookies
}
});
const handlePurchase = async () => {
// Your checkout logic here...
// Fire conversion pixel with cookies
await firePixel('https://analytics.tapbuy.com/conversion.gif');
// Or override cookie options for this specific call
await firePixel('https://analytics.tapbuy.com/conversion.gif', {
cookies: { keys: 'all' }
});
// Access collected cookies directly
const cookies = getCookies();
console.log('Collected cookies:', cookies);
// Override cookie options for getCookies
const themeCookie = getCookies({ keys: ['theme'] });
console.log('Theme cookie:', themeCookie);
// Example using wildcard pattern
const gaCookies = getCookies({ keys: ['_ga*'] });
console.log('Google Analytics cookies:', gaCookies);
};
return (
<button onClick={handlePurchase}>
Complete Purchase
</button>
);
}Vue Composable
<template>
<button @click="handlePurchase">
Complete Purchase
</button>
</template>
<script setup>
import { useTapbuyPixelVue } from '@tapbuy-public/pixel-tracker';
const { firePixel, getCookies } = useTapbuyPixelVue({
onSuccess: () => console.log('Conversion tracked!'),
onError: (error) => console.error('Tracking failed:', error),
cookies: {
keys: ['cartId', 'customerId']
}
});
const handlePurchase = async () => {
// Your checkout logic here...
// Fire conversion pixel
await firePixel('https://analytics.tapbuy.com/conversion.gif');
// Access collected cookies directly
const cookies = getCookies();
console.log('Collected cookies:', cookies);
// Override cookie options for getCookies
const themeCookie = getCookies({ keys: ['theme'] });
console.log('Theme cookie:', themeCookie);
};
</script>API Reference
TapbuyPixelTracker
The main class for pixel tracking.
Constructor Options
interface TapbuyPixelOptions {
timeout?: number; // Request timeout in ms (default: 5000)
onError?: (error: Error) => void; // Error callback
onSuccess?: () => void; // Success callback
cookies?: CookieOptions; // Cookie collection options
}
interface CookieOptions {
keys?: string[] | 'all' | 'none'; // Cookie keys to collect (supports wildcards like '_ga*')
}Methods
firePixel(pixelUrl: string, options?: FirePixelOptions): Promise<void>
Fire a pixel tracking request.
Parameters:
pixelUrl: Complete pixel URL from your analytics provideroptions.method: Tracking method -'img'(default),'fetch', or'beacon'options.cookies: Cookie collection options (overrides constructor options)
Example:
// Using default image method with default cookies
await tracker.firePixel('https://analytics.example.com/pixel.gif');
// Using fetch API with all cookies
await tracker.firePixel('https://analytics.example.com/pixel.gif', {
method: 'fetch',
cookies: { keys: 'all' }
});
// Using Beacon API with specific cookies
await tracker.firePixel('https://analytics.example.com/pixel.gif', {
method: 'beacon',
cookies: { keys: ['sessionId', 'userId'] }
});
// Using wildcard patterns to collect Google Analytics cookies
await tracker.firePixel('https://analytics.example.com/pixel.gif', {
method: 'img',
cookies: { keys: ['_ga*', '_gid'] }
});getCookies(cookieOptions?: CookieOptions): Record<string, string>
Get cookies as an object, using the default or overridden options.
Example:
const tracker = new TapbuyPixelTracker({
cookies: { keys: ['sessionId', 'userId'] }
});
// Get default cookies
const cookies = tracker.getCookies();
// cookies: { sessionId: 'abc123', userId: 'user456' }
// Override cookie options
const themeCookie = tracker.getCookies({ keys: ['theme'] });
// themeCookie: { theme: 'dark' }
// Use wildcard patterns to collect Google Analytics cookies
const gaCookies = tracker.getCookies({ keys: ['_ga*'] });
// gaCookies: { _ga: 'GA1.1.123.456', _ga_ABC123: 'GS1.1.789.012', _gid: 'GA1.1.334.567' }static generatePixelHtml(pixelUrl: string, cookieOptions?: CookieOptions): string
Generate pixel HTML for server-side rendering.
Example:
// Generate pixel HTML without cookies
const pixelHtml = TapbuyPixelTracker.generatePixelHtml(
'https://analytics.example.com/pixel.gif'
);
// Generate pixel HTML with cookies (client-side only)
const pixelHtmlWithCookies = TapbuyPixelTracker.generatePixelHtml(
'https://analytics.example.com/pixel.gif',
{ keys: ['sessionId', 'userId'] }
);
// Returns: <img src="...?cookie_sessionId=value&cookie_userId=value2" width="1" height="1" style="display:none;..." />React Hook: useTapbuyPixel(options?)
Returns an object with firePixel, generatePixelHtml, and getCookies methods.
Vue Composable: useTapbuyPixelVue(options?)
Returns an object with firePixel, generatePixelHtml, and getCookies methods.
Cookie Collection
The pixel tracker can automatically collect browser cookies and append them to pixel requests as query parameters. This is useful for tracking user sessions, cart data, or other client-side information.
Cookie Options
keys: 'none'(default) - Don't collect any cookieskeys: 'all'- Collect all available cookieskeys: string[]- Collect specific cookies by key names or patterns
Wildcard Pattern Support
Cookie keys support wildcard patterns using the * character:
// Collect all Google Analytics cookies
const tracker = new TapbuyPixelTracker({
cookies: {
keys: ['_ga*'] // Matches _ga, _gid, _ga_ABC123, etc.
}
});
// Collect multiple patterns
const multiPatternTracker = new TapbuyPixelTracker({
cookies: {
keys: ['_ga*', 'utm_*', 'sessionId'] // Mix patterns with exact matches
}
});
// Common patterns:
// '_ga*' - Google Analytics cookies
// 'utm_*' - UTM tracking parameters
// '_fb*' - Facebook pixel cookies
// 'custom_*' - Your custom cookie namespace// Collect specific cookies
const tracker = new TapbuyPixelTracker({
cookies: {
keys: ['sessionId', 'cartId', 'userId']
}
});
// Collect cookies using wildcard patterns
const analyticsTracker = new TapbuyPixelTracker({
cookies: {
keys: ['_ga*', 'utm_*'] // Google Analytics and UTM parameters
}
});
// Collect all cookies
const allCookiesTracker = new TapbuyPixelTracker({
cookies: { keys: 'all' }
});
// Don't collect cookies (default)
const noCookiesTracker = new TapbuyPixelTracker({
cookies: { keys: 'none' }
});Cookie Data Format
Cookies are appended to the pixel URL as query parameters with a cookie_ prefix:
Original URL: https://analytics.example.com/pixel.gif
With cookies: https://analytics.example.com/pixel.gif?cookie_sessionId=abc123&cookie_userId=user456Per-Request Cookie Override
You can override cookie options for individual pixel requests:
const tracker = new TapbuyPixelTracker({
cookies: { keys: ['sessionId'] } // Default: collect sessionId
});
// Use default cookie options
await tracker.firePixel(pixelUrl);
// Override to collect all cookies for this request
await tracker.firePixel(pixelUrl, {
cookies: { keys: 'all' }
});
// Override to collect no cookies for this request
await tracker.firePixel(pixelUrl, {
cookies: { keys: 'none' }
});Security Considerations
- HttpOnly cookies: Cannot be accessed by JavaScript and won't be collected
- Secure cookies: Will be collected on HTTPS pages only
- SameSite cookies: Behavior depends on your site's context
- URL length limits: Be mindful of URL length when collecting many cookies
SSR and Cookie Handling
In server-side rendering environments, cookies are not automatically available. You may need to pass cookie data from the server context:
// Next.js example
export async function getServerSideProps(context) {
const { req } = context;
// In SSR, you'd need to handle cookies differently
// The generatePixelHtml method will only work with cookies in client-side contexts
const pixelHtml = TapbuyPixelTracker.generatePixelHtml(pixelUrl);
return { props: { pixelHtml } };
}Tracking Methods
Image Pixel (Default)
Uses the Image constructor to load a 1x1 pixel. Most compatible across browsers and environments.
await tracker.firePixel(pixelUrl, { method: 'img' });Pros: Universal browser support, works in all environments Cons: Subject to ad blockers, may be cancelled on page unload
Fetch API
Uses the modern Fetch API with no-cors mode for cross-origin requests.
await tracker.firePixel(pixelUrl, { method: 'fetch' });Pros: Modern API, better error handling Cons: Not supported in older browsers, may be cancelled on page unload
Beacon API
Uses navigator.sendBeacon() for reliable tracking, especially during page unload.
await tracker.firePixel(pixelUrl, { method: 'beacon' });Pros: Guaranteed delivery even during page unload Cons: Limited browser support, POST requests only
Server-Side Rendering
For SSR frameworks like Next.js, Nuxt.js, or SvelteKit:
import { TapbuyPixelTracker } from '@tapbuy-public/pixel-tracker';
// Generate pixel HTML on the server
const pixelHtml = TapbuyPixelTracker.generatePixelHtml(
'https://analytics.example.com/pixel.gif'
);
// Include in your HTML response
const html = `
<html>
<head>
${pixelHtml}
</head>
<body>
<!-- Your content -->
</body>
</html>
`;Error Handling
The library provides multiple ways to handle errors:
const tracker = new TapbuyPixelTracker({
onError: (error) => {
// Global error handler
console.error('Pixel tracking failed:', error);
// Send to your error tracking service
errorService.captureError(error);
}
});
// Per-request error handling
try {
await tracker.firePixel(pixelUrl);
} catch (error) {
console.error('This specific pixel failed:', error);
}Browser Support
- Image pixels: All browsers
- Fetch API: Modern browsers (IE not supported)
- Beacon API: Chrome 39+, Firefox 31+, Safari 11.1+
Development
# Install dependencies
yarn install
# Run tests
yarn test
# Build the library
yarn build
# Run linter
yarn lint