@shopkit/analytics
v1.2.1
Published
A comprehensive analytics package combining event tracking and affiliate tracking for e-commerce applications with multiple platform adapters
Maintainers
Readme
@shopkit/analytics
A comprehensive, type-safe analytics package for e-commerce applications with support for multiple analytics platforms.
🚀 Quick Start
Installation
npm install @shopkit/analytics
# or
yarn add @shopkit/analytics
# or
bun add @shopkit/analyticsBasic Setup
import { ShopkitAnalytics } from "@shopkit/analytics";
export function App() {
return (
<ShopkitAnalytics
config={{
googleAnalytics: {
measurementId: "G-XXXXXXXXXX",
},
facebookPixel: {
pixelId: "123456789",
},
}}
>
<YourApp />
</ShopkitAnalytics>
);
}Track Events
import { publishEvent, EventType } from "@shopkit/analytics";
// Track page view
publishEvent({
type: EventType.PAGE_VIEW,
path: "/products/example",
title: "Product Page",
});
// Track add to cart
publishEvent({
type: EventType.ADD_TO_CART,
productId: "123",
productName: "Example Product",
price: 29.99,
quantity: 1,
});📊 Supported Platforms
| Platform | Events | Server-Side | Multi-Instance | |----------|:------:|:-----------:|:--------------:| | Google Analytics 4 | ✅ | ❌ | ❌ | | Facebook Pixel | ✅ | ✅ | ✅ | | MoEngage | ✅ | ❌ | ❌ | | PostHog | ✅ | ❌ | ❌ | | Shopify Analytics | ✅ | ❌ | ❌ | | KwikCheckout | ✅ | ❌ | ❌ | | KwikPass | ✅ | ❌ | ❌ |
📋 Event Support Matrix
The following table shows which events are supported by each analytics platform:
| Event Type | Google Analytics | Facebook Pixel | MoEngage | PostHog | Shopify Analytics | KwikCheckout | KwikPass | |------------|:----------------:|:--------------:|:--------:|:-------:|:----------------:|:------------:|:--------:| | Page View | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | | View Content | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | | Viewed Product | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | | Add to Cart | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | | Remove from Cart | ✅ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | | Search | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | | View Search Results | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | | Cart Viewed | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | | Initiate Checkout | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | | Add Payment Info | ✅ | ❌ | ❌ | ✅ | ❌ | ✅ | ❌ | | Purchase | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | | User Signup | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | | User Login | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | | Custom Events | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | | Specific Events | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | | GoKwik Events | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | | KwikPass Events | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ |
GoKwik-Specific Events (KwikCheckout Only)
| Event Type | Description |
|------------|-------------|
| STARTED_CHECKOUT_GK | Checkout process initiated |
| MOBILE_ADDED_GK | Mobile number added |
| ADDRESS_SELECTED_GK | Address selected |
| ADDRESS_COMPLETED_GK | Address form completed |
| ADDRESS_ADDED_GK | New address added |
| PIN_CODE_ADDED_GK | PIN code verification |
| PAYMENT_METHOD_SELECTED_GK | Payment method chosen |
| PAYMENT_COMPLETED_GK | Payment completed |
| ORDER_SUCCESS | Order success confirmation |
| ORDER_COMPLETED | Order fulfillment |
KwikPass-Specific Events (KwikPass Only)
| Event Type | Description |
|------------|-------------|
| PRODUCT_VIEW_KP | Product view through KwikPass |
| COLLECTION_VIEW_KP | Collection view through KwikPass |
| PAGE_VIEW_KP | Page view through KwikPass |
🎯 Core Features
✨ Key Benefits
- 🔧 Type-Safe: Full TypeScript support with IntelliSense
- 🎯 Unified API: Single event call reaches all platforms
- ⚡ Performance: Optimized for high-traffic applications
- 🛡️ Privacy: Built-in data protection and consent management
- 📊 Comprehensive: 20+ event types for complete e-commerce tracking
- 🔄 Reliable: Server-side backup with event deduplication
🏗️ Architecture
- Event-Driven: Publisher-subscriber pattern for flexible event handling
- Adapter Pattern: Clean, maintainable architecture with centralized processing
- Professional Logging: Structured logging with Pino for debugging and monitoring
- Affiliate Tracking: Built-in UTM parameter and attribution tracking
- Experiment Support: A/B testing parameter enhancement
📋 Event Types
Core E-commerce Events
// Product interactions
EventType.PAGE_VIEW // Page navigation
EventType.VIEWED_PRODUCT // Product view (20+ seconds)
EventType.VIEW_CONTENT // Content viewing
// Shopping cart
EventType.ADD_TO_CART // Add product to cart
EventType.REMOVE_FROM_CART // Remove from cart
EventType.CART_VIEWED // Cart page view
// Checkout flow
EventType.INITIATE_CHECKOUT // Begin checkout (GA4)
EventType.ADD_PAYMENT_INFO // Payment info added
EventType.PURCHASE // Purchase completed
// Discovery
EventType.SEARCH // Search performed
EventType.VIEW_SEARCH_RESULTS // Search results viewedUser Authentication (MoEngage)
EventType.USER_SIGNUP // Account creation
EventType.USER_LOGIN // User loginGoKwik Checkout Events
// Checkout flow
EventType.STARTED_CHECKOUT_GK // Checkout started
EventType.MOBILE_ADDED_GK // Mobile number added
EventType.PIN_CODE_ADDED_GK // PIN code added
// Address management
EventType.ADDRESS_ADDED_GK // New address added
EventType.ADDRESS_SELECTED_GK // Address selected
EventType.ADDRESS_COMPLETED_GK // Address completed
// Payment
EventType.PAYMENT_METHOD_SELECTED_GK // Payment method chosen
EventType.PAYMENT_COMPLETED_GK // Payment completed
// Order completion
EventType.ORDER_SUCCESS // Order success
EventType.ORDER_COMPLETED // Order fulfilledKwikPass Events
EventType.PRODUCT_VIEW_KP // Product view via KwikPass
EventType.COLLECTION_VIEW_KP // Collection view via KwikPass
EventType.PAGE_VIEW_KP // Page view via KwikPassCustom Events
EventType.CUSTOM // Custom event with flexible properties
EventType.SPECIFIC // Specific event with predefined structure🔧 Platform Configuration
Google Analytics 4
<ShopkitAnalytics
config={{
googleAnalytics: {
measurementId: "G-XXXXXXXXXX",
enableDebugLogs: true,
gokwikEnabled: false, // Skip checkout events when GoKwik is handling them
customDimensions: {
user_type: "premium",
},
},
}}
/>GoKwik Conflict Prevention
When using GoKwik checkout alongside Google Analytics, you can prevent duplicate event tracking by enabling the gokwikEnabled flag:
<ShopkitAnalytics
config={{
googleAnalytics: {
measurementId: "G-XXXXXXXXXX",
gokwikEnabled: true, // Prevents duplicate tracking of checkout events
},
}}
/>Events skipped when gokwikEnabled: true:
PURCHASE- Purchase completion
This prevents duplicate tracking since GoKwik already sends these events to Google Analytics and Meta when enabled.
Facebook Pixel (Single)
<ShopkitAnalytics
config={{
facebookPixel: {
pixelId: "123456789",
enableCAPI: true, // Server-side tracking (default: true)
gokwikEnabled: false, // Skip checkout events when GoKwik is handling them
enableAdvancedMatching: true,
},
}}
/>GoKwik Conflict Prevention
When using GoKwik checkout alongside Facebook Pixel, you can prevent duplicate event tracking by enabling the gokwikEnabled flag:
<ShopkitAnalytics
config={{
facebookPixel: {
pixelId: "123456789",
gokwikEnabled: true, // Prevents duplicate tracking of checkout events
},
}}
/>Events skipped when gokwikEnabled: true:
PURCHASE- Purchase completion
This prevents duplicate tracking since GoKwik already sends these events to Meta and Google Analytics when enabled.
Environment Variables:
FACEBOOK_CAPI_ACCESS_TOKEN="your_access_token"
NEXT_PUBLIC_PIXEL_ID="123456789"Facebook Multi-Pixel (Enterprise)
<ShopkitAnalytics
config={{
facebookMultiPixel: {
pixels: [
{ pixelId: "123456789", name: "Primary", enableCAPI: true },
{ pixelId: "987654321", name: "Secondary", enableCAPI: true },
{ pixelId: "555666777", name: "Retargeting", enableCAPI: false },
],
enableCAPI: true,
gokwikEnabled: false, // Skip checkout events when GoKwik is handling them
capiEndpoint: "/api/events/multi",
},
}}
/>GoKwik Conflict Prevention
When using GoKwik checkout alongside Facebook Multi-Pixel, you can prevent duplicate event tracking by enabling the gokwikEnabled flag:
<ShopkitAnalytics
config={{
facebookMultiPixel: {
pixels: [
{ pixelId: "123456789", name: "Primary", enableCAPI: true },
{ pixelId: "987654321", name: "Secondary", enableCAPI: true },
],
gokwikEnabled: true, // Prevents duplicate tracking across all pixels
},
}}
/>Events skipped when gokwikEnabled: true:
PURCHASE- Purchase completion
This prevents duplicate tracking across all configured pixels since GoKwik already sends these events to Meta and Google Analytics when enabled.
Environment Variables:
NEXT_PUBLIC_MULTI_PIXEL_IDS="123456789,987654321,555666777"
FACEBOOK_MULTI_CAPI_ACCESS_TOKENS="token1,token2,token3"MoEngage
<ShopkitAnalytics
config={{
moengage: {
appId: "YOUR_MOENGAGE_APP_ID",
region: "DEFAULT", // or "EU"
},
}}
/>PostHog
Note: Requires PostHog script to be loaded separately.
<ShopkitAnalytics
config={{
posthog: {
enableDebugLogs: true,
},
}}
/>Shopify Analytics
<ShopkitAnalytics
config={{
shopify: {
shopId: "your-shop-id",
domain: "your-shop.myshopify.com",
merchantName: "your-merchant-name",
currency: "USD",
},
}}
/>KwikCheckout (GoKwik)
<ShopkitAnalytics
config={{
kwikcheckout: {
mid: "your-gokwik-mid",
environment: "production", // or "staging"
storeId: "your-store-id",
},
}}
/>KwikPass
<ShopkitAnalytics
config={{
kwikpass: {
enableKwikPassEvents: true,
},
}}
/>🎛️ Advanced Features
Adapter-Specific Parameters
Customize event names and parameters per platform:
publishEvent({
type: EventType.ADD_TO_CART,
productId: "123",
productName: "Cool Product",
price: 29.99,
}, {
// Customize for each platform
GoogleAnalytics: {
event_name: "custom_add_to_cart",
custom_dimension_1: "premium_user",
},
FacebookPixel: {
event_name: "CustomAddToCart",
custom_parameter: "special_value",
},
PostHog: {
event_name: "add_to_cart_premium",
feature_flag: "new_checkout_flow",
},
});Selective Adapter Routing
Route events to specific platforms:
// Send to specific adapters only
publishEvent({
type: EventType.ADD_TO_CART,
productId: "123",
}, {}, {
adapters: ["GoogleAnalytics", "FacebookPixel"],
});
// Exclude specific adapters
publishEvent({
type: EventType.PAGE_VIEW,
path: "/internal-page",
}, {}, {
excludeAdapters: ["FacebookPixel"],
});Professional Logging
<ShopkitAnalytics
config={{
logger: {
enabled: true,
level: "info", // "trace" | "debug" | "info" | "warn" | "error" | "fatal"
prettyPrint: process.env.NODE_ENV === "development",
redact: ["password", "token", "apiKey"], // Hide sensitive data
},
}}
/>Affiliate Tracking
<ShopkitAnalytics
config={{
affiliate: {
enabled: true,
autoCapture: true,
config: {
utmParams: ["utm_source", "utm_medium", "utm_campaign"],
customParams: ["ref", "affiliate_id"],
expirationDays: 30,
},
},
}}
/>🔄 Server-Side Tracking (Facebook CAPI)
Facebook Pixel adapter supports server-side tracking through the Conversions API (CAPI) for improved data reliability and privacy compliance. CAPI is enabled by default for better data quality.
Quick Setup
- Set Environment Variables:
Single Pixel:
FACEBOOK_CAPI_ACCESS_TOKEN="your_access_token"
NEXT_PUBLIC_PIXEL_ID="123456789"
FACEBOOK_TEST_EVENT_CODE="TEST12345" # Optional: for testingMulti-Pixel:
NEXT_PUBLIC_MULTI_PIXEL_IDS="123456789,987654321,555666777"
FACEBOOK_MULTI_CAPI_ACCESS_TOKENS="token1,token2,token3"
FACEBOOK_TEST_EVENT_CODE="TEST12345" # Optional: for testing- Copy API Route Templates:
We provide ready-to-use templates for Next.js API routes:
Single Pixel Setup:
- App Router: Copy
node_modules/@shopkit/analytics/templates/nextjs/api-events-route.tstoapp/api/events/route.ts - Pages Router: Copy
node_modules/@shopkit/analytics/templates/nextjs/pages-api-events.tstopages/api/events.ts
Multi-Pixel Setup:
- App Router: Copy
node_modules/@shopkit/analytics/templates/nextjs/api-events-multi-route.tstoapp/api/events/multi/route.ts - Pages Router: Copy
node_modules/@shopkit/analytics/templates/nextjs/pages-api-events-multi.tstopages/api/events/multi.ts
- Configure Analytics:
Single Pixel:
<ShopkitAnalytics
config={{
facebookPixel: {
pixelId: process.env.NEXT_PUBLIC_PIXEL_ID!,
enableCAPI: true, // Default: enabled for better data reliability
},
}}
/>Multi-Pixel:
<ShopkitAnalytics
config={{
facebookMultiPixel: {
pixels: [
{ pixelId: "123456789", name: "Primary", enableCAPI: true },
{ pixelId: "987654321", name: "Secondary", enableCAPI: true },
{ pixelId: "555666777", name: "Retargeting", enableCAPI: false },
],
enableCAPI: true,
capiEndpoint: "/api/events/multi",
},
}}
/>Complete Setup Guide
For detailed setup instructions, troubleshooting, and testing guidance, see:
node_modules/@shopkit/analytics/templates/nextjs/README.md
This comprehensive guide includes:
- Step-by-step setup for both single and multi-pixel configurations
- How to get Facebook access tokens
- Testing procedures for development and production
- Troubleshooting common issues
- Debug logging configuration
- Performance considerations
Key Features
- 🔄 Automatic Fallback: Server-side tracking runs as backup to client-side
- 🆔 Event Deduplication: Unique event IDs prevent double-counting
- 🎯 Enhanced Matching: Browser fingerprinting for better user matching
- 🛡️ Privacy Compliant: Respects user privacy while improving data quality
- ⚡ Parallel Processing: Multi-pixel setup processes all pixels simultaneously
- 🔧 Individual Configuration: Each pixel can have different CAPI settings
🎣 React Hooks
Affiliate Tracking Hooks
import {
useAffiliateTracker,
useHasAffiliateData,
useAffiliateSource
} from "@shopkit/analytics";
function MyComponent() {
const hasAffiliateData = useHasAffiliateData();
const affiliateSource = useAffiliateSource();
const affiliateTracker = useAffiliateTracker();
if (hasAffiliateData) {
console.log("Affiliate source:", affiliateSource);
console.log("Affiliate data:", affiliateTracker.data);
}
return <div>Component content</div>;
}📚 API Reference
Core Methods
publishEvent(eventData, adapterParams?, options?)
publishEvent(
{
type: EventType.ADD_TO_CART,
productId: "123",
productName: "Product",
price: 29.99,
},
{
GoogleAnalytics: { event_name: "custom_add_to_cart" },
FacebookPixel: { event_name: "CustomAddToCart" },
},
{
adapters: ["GoogleAnalytics", "FacebookPixel"],
}
);getAffiliateParams()
const affiliateData = getAffiliateParams();
// Returns: { utm_source: "google", utm_campaign: "summer", ... }getExperimentParams()
const experimentData = getExperimentParams();
// Returns: { experiment_id: "test_123", variant: "A", ... }Configuration Interfaces
interface ShopkitAnalyticsConfig {
// Platform configurations
googleAnalytics?: GoogleAdapterConfig;
facebookPixel?: PixelAdapterConfig;
facebookMultiPixel?: MultiPixelAdapterConfig;
moengage?: MoengageAdapterConfig;
posthog?: PostHogAdapterConfig;
shopify?: ShopifyAdapterConfig;
kwikpass?: KwikPassConfig;
kwikcheckout?: KwikCheckoutConfig;
// Logging
logger?: {
enabled?: boolean;
level?: "trace" | "debug" | "info" | "warn" | "error" | "fatal";
prettyPrint?: boolean;
redact?: string[];
};
// Affiliate tracking
affiliate?: {
enabled?: boolean;
autoCapture?: boolean;
config?: AffiliateConfig;
};
}🔍 Event Examples
E-commerce Flow
// Product page view
publishEvent({
type: EventType.PAGE_VIEW,
path: "/products/wireless-headphones",
title: "Wireless Headphones - Premium Audio",
});
// Product viewed (after 20 seconds)
publishEvent({
type: EventType.VIEWED_PRODUCT,
productId: "headphones-123",
productName: "Wireless Headphones",
price: 199.99,
currency: "USD",
category: "Electronics",
});
// Add to cart
publishEvent({
type: EventType.ADD_TO_CART,
productId: "headphones-123",
productName: "Wireless Headphones",
price: 199.99,
quantity: 1,
variant: "Black",
});
// Begin checkout
publishEvent({
type: EventType.INITIATE_CHECKOUT,
cartValue: 199.99,
currency: "USD",
itemCount: 1,
items: [{
productId: "headphones-123",
productName: "Wireless Headphones",
price: 199.99,
quantity: 1,
}],
});
// Purchase completed
publishEvent({
type: EventType.PURCHASE,
value: 199.99,
currency: "USD",
transaction_id: "order_123",
items: [{
productId: "headphones-123",
productName: "Wireless Headphones",
price: 199.99,
quantity: 1,
}],
});GoKwik Checkout Flow
// Checkout started
publishEvent({
type: EventType.STARTED_CHECKOUT_GK,
cartValue: 199.99,
currency: "USD",
});
// Mobile added
publishEvent({
type: EventType.MOBILE_ADDED_GK,
mobile: "+1234567890",
});
// Address completed
publishEvent({
type: EventType.ADDRESS_COMPLETED_GK,
addressId: "addr_123",
});
// Payment completed
publishEvent({
type: EventType.PAYMENT_COMPLETED_GK,
amount: 199.99,
currency: "USD",
});
// Order success
publishEvent({
type: EventType.ORDER_SUCCESS,
orderId: "order_123",
amount: 199.99,
currency: "USD",
});🚨 Best Practices
Performance
- Use selective adapter routing for high-traffic events
- Enable server-side tracking for critical conversion events
- Configure appropriate log levels for production
Privacy & Security
- Store sensitive keys in environment variables
- Implement proper consent management
- Use data redaction for sensitive information
- Enable HTTPS for all server-side tracking
Development
- Enable debug logging in development
- Use TypeScript for type safety
- Validate event data before publishing
- Monitor analytics dashboards for data accuracy
Production
- Use structured JSON logging
- Set up error monitoring
- Implement retry logic for failed requests
- Monitor rate limits and quotas
🔧 Troubleshooting
Common Issues
Events not appearing in analytics platforms:
- Check environment variables are set correctly
- Verify API routes are working (for CAPI)
- Ensure analytics scripts are loaded
- Check browser console for errors
TypeScript errors:
- Ensure event data matches expected interfaces
- Check adapter parameter types
- Verify EventType imports
Performance issues:
- Use selective adapter routing
- Reduce log verbosity in production
- Optimize event payload size
Debug Checklist
- [ ] Environment variables configured
- [ ] Analytics scripts loaded
- [ ] API routes working (for server-side tracking)
- [ ] Event data structure is correct
- [ ] No console errors
- [ ] Network requests successful
📄 License
MIT License - see LICENSE file for details.
🤝 Contributing
- Fork the repository
- Create a feature branch
- Make your changes with tests
- Submit a pull request
📞 Support
@shopkit/analytics - The complete analytics solution for modern e-commerce applications.
