Cross-framework pixel tracking for Tapbuy checkout
npm install @tapbuy-public/pixel-trackerCross-framework pixel tracking library for Tapbuy checkout analytics.
- 🚀 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
``bash`
npm install @tapbuy-public/pixel-tracker
`bash`
yarn add @tapbuy-public/pixel-tracker
`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);
`
`tsx
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 (
);
}
`
`vue
`
The main class for pixel tracking.
#### Constructor Options
`typescript
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
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:
`typescript
// 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
Get cookies as an object, using the default or overridden options.
Example:
`typescript
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:
`typescript
// 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:
`
Returns an object with firePixel, generatePixelHtml, and getCookies methods.
Returns an object with firePixel, generatePixelHtml, and getCookies methods.
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.
- keys: 'none' (default) - Don't collect any cookieskeys: 'all'
- - Collect all available cookies keys: string[]
- - Collect specific cookies by key names or patterns
#### Wildcard Pattern Support
Cookie keys support wildcard patterns using the * character:
`typescript
// 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
`
`typescript
// 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' }
});
`
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=user456
You can override cookie options for individual pixel requests:
`typescript
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' }
});
`
- 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
In server-side rendering environments, cookies are not automatically available. You may need to pass cookie data from the server context:
`typescript`
// 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 } };
}
Uses the Image constructor to load a 1x1 pixel. Most compatible across browsers and environments.
`typescript`
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
Uses the modern Fetch API with no-cors mode for cross-origin requests.
`typescript`
await tracker.firePixel(pixelUrl, { method: 'fetch' });
Pros: Modern API, better error handling
Cons: Not supported in older browsers, may be cancelled on page unload
Uses navigator.sendBeacon() for reliable tracking, especially during page unload.
`typescript`
await tracker.firePixel(pixelUrl, { method: 'beacon' });
Pros: Guaranteed delivery even during page unload
Cons: Limited browser support, POST requests only
For SSR frameworks like Next.js, Nuxt.js, or SvelteKit:
`typescript
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 =
;
`Error Handling
The library provides multiple ways to handle errors:
`typescript
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
`bash
Install dependencies
yarn installRun tests
yarn testBuild the library
yarn buildRun linter
yarn lint
``