npm package: @shopkit/analytics
Description: A comprehensive analytics package combining event tracking and affiliate tracking for e-commerce applications with multiple platform adapters
Author: Shopkit Team
Latest version: 1.2.1

# @shopkit/analytics

A comprehensive, type-safe analytics package for e-commerce applications with support for multiple analytics platforms.

## 🚀 Quick Start

### Installation

```bash
npm install @shopkit/analytics
# or
yarn add @shopkit/analytics
# or
bun add @shopkit/analytics
```

### Basic Setup

```tsx
import { ShopkitAnalytics } from "@shopkit/analytics";

export function App() {
  return (
    <ShopkitAnalytics
      config={{
        googleAnalytics: {
          measurementId: "G-XXXXXXXXXX",
        },
        facebookPixel: {
          pixelId: "123456789",
        },
      }}
    >
      <YourApp />
    </ShopkitAnalytics>
  );
}
```

### Track Events

```tsx
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

```tsx
// 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 viewed
```

### User Authentication (MoEngage)

```tsx
EventType.USER_SIGNUP         // Account creation
EventType.USER_LOGIN          // User login
```

### GoKwik Checkout Events

```tsx
// 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 fulfilled
```

### KwikPass Events

```tsx
EventType.PRODUCT_VIEW_KP     // Product view via KwikPass
EventType.COLLECTION_VIEW_KP  // Collection view via KwikPass
EventType.PAGE_VIEW_KP        // Page view via KwikPass
```

### Custom Events

```tsx
EventType.CUSTOM              // Custom event with flexible properties
EventType.SPECIFIC            // Specific event with predefined structure
```

## 🔧 Platform Configuration

### Google Analytics 4

```tsx
<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:

```tsx
<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)

```tsx
<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:

```tsx
<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:**
```bash
FACEBOOK_CAPI_ACCESS_TOKEN="your_access_token"
NEXT_PUBLIC_PIXEL_ID="123456789"
```

### Facebook Multi-Pixel (Enterprise)

```tsx
<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:

```tsx
<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:**
```bash
NEXT_PUBLIC_MULTI_PIXEL_IDS="123456789,987654321,555666777"
FACEBOOK_MULTI_CAPI_ACCESS_TOKENS="token1,token2,token3"
```

### MoEngage

```tsx
<ShopkitAnalytics
  config={{
    moengage: {
      appId: "YOUR_MOENGAGE_APP_ID",
      region: "DEFAULT", // or "EU"
    },
  }}
/>
```

### PostHog

> **Note**: Requires PostHog script to be loaded separately.

```tsx
<ShopkitAnalytics
  config={{
    posthog: {
      enableDebugLogs: true,
    },
  }}
/>
```

### Shopify Analytics

```tsx
<ShopkitAnalytics
  config={{
    shopify: {
      shopId: "your-shop-id",
      domain: "your-shop.myshopify.com",
      merchantName: "your-merchant-name",
      currency: "USD",
    },
  }}
/>
```

### KwikCheckout (GoKwik)

```tsx
<ShopkitAnalytics
  config={{
    kwikcheckout: {
      mid: "your-gokwik-mid",
      environment: "production", // or "staging"
      storeId: "your-store-id",
    },
  }}
/>
```

### KwikPass

```tsx
<ShopkitAnalytics
  config={{
    kwikpass: {
      enableKwikPassEvents: true,
    },
  }}
/>
```

## 🎛️ Advanced Features

### Adapter-Specific Parameters

Customize event names and parameters per platform:

```tsx
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:

```tsx
// 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

```tsx
<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

```tsx
<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

1. **Set Environment Variables:**

**Single Pixel:**
```bash
FACEBOOK_CAPI_ACCESS_TOKEN="your_access_token"
NEXT_PUBLIC_PIXEL_ID="123456789"
FACEBOOK_TEST_EVENT_CODE="TEST12345"  # Optional: for testing
```

**Multi-Pixel:**
```bash
NEXT_PUBLIC_MULTI_PIXEL_IDS="123456789,987654321,555666777"
FACEBOOK_MULTI_CAPI_ACCESS_TOKENS="token1,token2,token3"
FACEBOOK_TEST_EVENT_CODE="TEST12345"  # Optional: for testing
```

2. **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.ts` to `app/api/events/route.ts`
- **Pages Router**: Copy `node_modules/@shopkit/analytics/templates/nextjs/pages-api-events.ts` to `pages/api/events.ts`

**Multi-Pixel Setup:**
- **App Router**: Copy `node_modules/@shopkit/analytics/templates/nextjs/api-events-multi-route.ts` to `app/api/events/multi/route.ts`
- **Pages Router**: Copy `node_modules/@shopkit/analytics/templates/nextjs/pages-api-events-multi.ts` to `pages/api/events/multi.ts`

3. **Configure Analytics:**

**Single Pixel:**
```tsx
<ShopkitAnalytics
  config={{
    facebookPixel: {
      pixelId: process.env.NEXT_PUBLIC_PIXEL_ID!,
      enableCAPI: true, // Default: enabled for better data reliability
    },
  }}
/>
```

**Multi-Pixel:**
```tsx
<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

```tsx
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?)`

```tsx
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()`

```tsx
const affiliateData = getAffiliateParams();
// Returns: { utm_source: "google", utm_campaign: "summer", ... }
```

#### `getExperimentParams()`

```tsx
const experimentData = getExperimentParams();
// Returns: { experiment_id: "test_123", variant: "A", ... }
```

### Configuration Interfaces

```tsx
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

```tsx
// 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

```tsx
// 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

1. Fork the repository
2. Create a feature branch
3. Make your changes with tests
4. Submit a pull request

## 📞 Support

- 📖 [Documentation](https://github.com/your-repo/analytics)
- 🐛 [Issues](https://github.com/your-repo/analytics/issues)
- 💬 [Discussions](https://github.com/your-repo/analytics/discussions)

---

**@shopkit/analytics** - The complete analytics solution for modern e-commerce applications.