npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

marketing-analytics-sdk

v1.0.0-40feb5c7

Published

Frontend SDK for Marketing Analytics Service

Readme

Marketing Analytics SDK

A comprehensive frontend SDK for tracking analytics events with multi-tenant support, automatic session management, and real-time event queuing.

Features

  • 🔐 Authentication & Security: API key-based authentication with tenant isolation
  • 🏢 Multi-Tenant Support: Isolated tracking per brand/tenant
  • 🌍 Environment Support: Development, staging, and production environments
  • 📊 Automatic Tracking: Page views, sessions, and user interactions
  • Event Queuing: Batched event sending with automatic retry
  • 🎯 Rich Event Types: Product views, cart actions, orders, and more
  • 🔧 TypeScript Support: Full type safety and IntelliSense
  • 🌐 Universal: Works in browsers and Node.js environments

Installation

npm install marketing-analytics-sdk

Quick Start

1. Initialize the SDK

import { MarketingAnalytics } from 'marketing-analytics-sdk';

const analytics = new MarketingAnalytics({
  apiKey: 'your-api-key',
  tenantSlug: 'your-brand-slug',
  environment: 'production', // or 'development', 'staging'
  debug: true, // Enable debug logging
});

// Initialize the SDK
await analytics.init();

2. Track Events

// Track a page view
analytics.trackPageView();

// Track a product view
analytics.trackProductViewed({
  id: 'product-123',
  name: 'Premium Widget',
  price: 99.99,
  currency: 'USD',
  category: 'Electronics',
});

// Track adding to cart
analytics.trackProductAddedToCart({
  id: 'product-123',
  name: 'Premium Widget',
  price: 99.99,
  currency: 'USD',
  quantity: 2,
});

// Track an order
analytics.trackOrderPlaced({
  id: 'order-456',
  items: [
    {
      id: 'product-123',
      name: 'Premium Widget',
      price: 99.99,
      currency: 'USD',
      quantity: 2,
    },
  ],
  total: 199.98,
  currency: 'USD',
  tax: 15.99,
  shipping: 9.99,
});

Configuration

SDK Configuration Options

interface SDKConfig {
  apiKey: string;                    // Required: Your API key
  tenantSlug: string;                // Required: Your brand/tenant slug
  environment?: Environment;          // Optional: 'development' | 'staging' | 'production'
  baseUrl?: string;                  // Optional: Custom API endpoint
  debug?: boolean;                   // Optional: Enable debug logging
  autoTrackPageViews?: boolean;      // Optional: Auto-track page views
  autoTrackSessions?: boolean;       // Optional: Auto-track sessions
}

Environment-Specific Configuration

// Development
const devAnalytics = new MarketingAnalytics({
  apiKey: 'dev-api-key',
  tenantSlug: 'my-brand-dev',
  environment: 'development',
  debug: true,
  baseUrl: 'http://localhost:8787',
});

// Production
const prodAnalytics = new MarketingAnalytics({
  apiKey: 'prod-api-key',
  tenantSlug: 'my-brand',
  environment: 'production',
  debug: false,
});

Event Types

Page Views

analytics.trackPageView({
  url: 'https://example.com/product/123',
  title: 'Product Details',
  referrer: 'https://google.com',
});

Product Events

// Product viewed
analytics.trackProductViewed(product);

// Added to cart
analytics.trackProductAddedToCart(product, 'cart-123');

// Removed from cart
analytics.trackProductRemovedFromCart(product, 'cart-123');

Cart Events

analytics.trackCartViewed({
  id: 'cart-123',
  items: [product1, product2],
  total: 199.98,
  currency: 'USD',
});

analytics.trackCheckoutStarted({
  id: 'cart-123',
  items: [product1, product2],
  total: 199.98,
  currency: 'USD',
});

Order Events

analytics.trackOrderPlaced({
  id: 'order-456',
  items: [product1, product2],
  total: 199.98,
  currency: 'USD',
  tax: 15.99,
  shipping: 9.99,
  discount: 10.00,
});

Customer Events

analytics.trackProfileCompleted({
  id: 'customer-123',
  email: '[email protected]',
  firstName: 'John',
  lastName: 'Doe',
  phone: '+1234567890',
  address: {
    street: '123 Main St',
    city: 'New York',
    state: 'NY',
    zip: '10001',
    country: 'USA',
  },
});

Custom Events

analytics.trackCustomEvent('trackQuestionnaireCompleted', {
  questionnaireId: 'quiz-123',
  answers: {
    age: '25-34',
    income: '50k-100k',
    interests: ['technology', 'fitness'],
  },
});

Event Catalog System

The SDK now supports a dynamic event catalog system that allows you to create, manage, and track custom event types with categories and time-sensitivity settings.

Event Categories

Events are organized into categories for better management:

  • CONVERSION: Purchase, order, checkout events
  • PAGE_VIEW: Page view and navigation events
  • BUTTON_CLICK: User interaction events
  • FORM_SUBMISSION: Form completion events
  • USER_ACTION: User behavior events
  • SYSTEM_EVENT: System-generated events
  • CUSTOM: Custom business events

Managing Event Types

// Get all available event types
const allEventTypes = await analytics.getEventTypes();
console.log('Available events:', allEventTypes);

// Get events by category
const conversionEvents = await analytics.getEventTypesByCategory('CONVERSION');
const timeSensitiveEvents = await analytics.getTimeSensitiveEventTypes();

// Check if an event type exists
const exists = await analytics.eventTypeExists('trackCustomFeature');

// Get specific event details
const eventType = await analytics.getEventTypeByName('trackOrderPlaced');

Creating Custom Event Types

// Create a new custom event type
const newEventType = await analytics.createEventType({
  name: 'trackCustomFeature',
  display_name: 'Custom Feature Used',
  description: 'Track when users use a custom feature',
  category: 'USER_ACTION',
  is_time_sensitive: false,
  platforms: ['klaviyo', 'meta'],
  metadata_schema: {
    type: 'object',
    properties: {
      feature_name: { type: 'string' },
      usage_count: { type: 'number' },
    },
  },
});

Smart Event Tracking

The SDK provides intelligent tracking methods that automatically choose the best processing method:

// Smart tracking - automatically chooses immediate or queued processing
await analytics.trackSmart('trackOrderPlaced', {
  orderId: 'order-123',
  total: 99.99,
  currency: 'USD',
});

// Immediate tracking for time-sensitive events
await analytics.trackImmediate('trackOrderPlaced', {
  orderId: 'order-456',
  total: 149.99,
  currency: 'USD',
});

// Smart order tracking with full order data
await analytics.trackOrderPlacedSmart({
  id: 'order-789',
  items: [{ id: 'product-1', name: 'Product', price: 49.99, quantity: 1 }],
  total: 49.99,
  currency: 'USD',
  tax: 4.99,
  shipping: 5.99,
});

Browser-Specific Features

Browser Utilities

import { browserUtils } from '@marketing-analytics/sdk/browser';

// Get Facebook Pixel data
const { fbp, fbc } = browserUtils.getFacebookPixelData();

// Get Google Analytics client ID
const gaClientId = browserUtils.getGoogleAnalyticsClientId();

// Get referrer information
const { referrer, referrerDomain, isInternal } = browserUtils.getReferrerInfo();

// Get user agent information
const { userAgent, isMobile, browser, os } = browserUtils.getUserAgentInfo();

Enhanced Tracking with Browser Data

const analytics = new MarketingAnalytics({
  apiKey: 'your-api-key',
  tenantSlug: 'your-brand',
  debug: true,
});

await analytics.init();

// Track page view with enhanced data
analytics.trackPageView({
  metadata: {
    ...browserUtils.getFacebookPixelData(),
    ...browserUtils.getReferrerInfo(),
    ...browserUtils.getUserAgentInfo(),
  },
});

Session Management

The SDK automatically manages sessions and client IDs:

// Get current session data
const session = analytics.getSession();
console.log(session);
// {
//   sessionId: 'session-123',
//   clientId: 'client-456',
//   startTime: 1640995200000,
//   lastActivity: 1640995260000
// }

// Get queue status
const queueStatus = analytics.getQueueStatus();
console.log(queueStatus);
// {
//   events: [...],
//   maxSize: 50,
//   flushInterval: 5000,
//   isFlushing: false
// }

Event Queuing

Events are automatically queued and sent in batches:

// Manually flush events
await analytics.flush();

// Update configuration
analytics.updateConfig({
  debug: true,
  flushInterval: 3000, // 3 seconds
});

React Integration

React Hook Example

import { useEffect, useRef } from 'react';
import { MarketingAnalytics } from '@marketing-analytics/sdk';

export function useAnalytics(apiKey: string, tenantSlug: string) {
  const analyticsRef = useRef<MarketingAnalytics | null>(null);

  useEffect(() => {
    if (!analyticsRef.current) {
      analyticsRef.current = new MarketingAnalytics({
        apiKey,
        tenantSlug,
        debug: process.env.NODE_ENV === 'development',
      });

      analyticsRef.current.init();
    }

    return () => {
      analyticsRef.current?.destroy();
    };
  }, [apiKey, tenantSlug]);

  return analyticsRef.current;
}

React Component Example

import React from 'react';
import { useAnalytics } from './useAnalytics';

export function ProductCard({ product }: { product: ProductData }) {
  const analytics = useAnalytics('your-api-key', 'your-brand');

  const handleView = () => {
    analytics?.trackProductViewed(product);
  };

  const handleAddToCart = () => {
    analytics?.trackProductAddedToCart(product);
  };

  return (
    <div>
      <h3>{product.name}</h3>
      <p>${product.price}</p>
      <button onClick={handleView}>View Details</button>
      <button onClick={handleAddToCart}>Add to Cart</button>
    </div>
  );
}

Error Handling

try {
  await analytics.init();
} catch (error) {
  console.error('Failed to initialize analytics:', error);
}

// Events are automatically queued and retried
analytics.trackProductViewed(product);
// If network is down, events will be queued and sent when connection is restored

Cleanup

// Clean up when done
analytics.destroy();

TypeScript Support

The SDK is fully typed with TypeScript:

import { 
  MarketingAnalytics, 
  ProductData, 
  TrackEventType,
  SDKConfig 
} from '@marketing-analytics/sdk';

const config: SDKConfig = {
  apiKey: 'your-api-key',
  tenantSlug: 'your-brand',
};

const product: ProductData = {
  id: 'product-123',
  name: 'Widget',
  price: 99.99,
  currency: 'USD',
};

API Reference

Core Methods

  • init(): Initialize the SDK
  • trackPageView(data?): Track a page view
  • trackProductViewed(product): Track product view
  • trackProductAddedToCart(product, cartId?): Track add to cart
  • trackProductRemovedFromCart(product, cartId?): Track remove from cart
  • trackCartViewed(cart): Track cart view
  • trackCheckoutStarted(cart): Track checkout start
  • trackOrderPlaced(order): Track order placement
  • trackProfileCompleted(customer): Track profile completion
  • trackCustomEvent(type, data): Track custom event
  • trackImmediate(type, data): Track event with immediate processing
  • trackSmart(type, data): Track event with smart processing (auto-chooses immediate/queued)
  • trackOrderPlacedImmediate(order): Track order with immediate processing
  • trackOrderPlacedSmart(order): Track order with smart processing
  • flush(): Manually flush queued events
  • destroy(): Clean up the SDK

Event Catalog Methods

  • getEventTypes(): Get all available event types
  • getEventTypesByCategory(category): Get events by category
  • getTimeSensitiveEventTypes(): Get time-sensitive events
  • eventTypeExists(name): Check if event type exists
  • getEventTypeByName(name): Get specific event type details
  • createEventType(eventType): Create a new custom event type

Utility Methods

  • getSession(): Get current session data
  • getQueueStatus(): Get event queue status
  • updateConfig(config): Update SDK configuration

Browser Support

  • Chrome 60+
  • Firefox 55+
  • Safari 12+
  • Edge 79+

License

MIT