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 🙏

© 2025 – Pkg Stats / Ryan Hefner

analytics-gateway

v1.0.1

Published

A TypeScript frontend library that acts as a gateway for multiple analytics providers

Readme

Analytics Gateway

A TypeScript frontend library that acts as a gateway for multiple analytics providers, allowing developers to easily toggle providers on/off and configure them during instantiation.

Features

  • Multi-Provider Support: Built-in support for Mixpanel, Google Analytics 4 (GA4), LogRocket, and Amplitude
  • Automatic Script Loading: Each provider automatically loads its required script when initialized - no manual script tags needed!
  • Easy Toggle: Enable/disable individual providers or all providers at once
  • Unified Interface: Single API for tracking events, user identification, and page views across all providers
  • TypeScript Support: Full TypeScript support with comprehensive type definitions
  • Flexible Configuration: Configure providers during instantiation with runtime updates
  • Global Properties: Set properties that are automatically included in all events
  • Debug Mode: Built-in debugging and logging capabilities
  • Framework Agnostic: Works with any JavaScript framework (React, Vue, Angular, vanilla JS, etc.)
  • Zero Dependencies: No runtime dependencies, providers load via CDN dynamically

Supported Providers

  • Mixpanel: Event tracking, user identification, and custom properties
  • Google Analytics 4: Event tracking, user properties, and page views
  • LogRocket: Session recording, error tracking, and user identification
  • Amplitude: Event tracking, user properties, and behavioral analytics

Installation

npm install analytics-gateway

The library has zero runtime dependencies. Analytics providers (Mixpanel, Amplitude, GA4, LogRocket) are loaded dynamically via script tags and accessed through their global APIs.

Optional Peer Dependencies

  • Analytics provider SDKs are optional and loaded dynamically at runtime

Quick Start

Basic Usage

import { AnalyticsGateway } from "analytics-gateway";

// Configure your analytics providers
const config = {
  providers: {
    mixpanel: {
      enabled: true,
      token: "your-mixpanel-token",
      debug: true,
    },
    ga4: {
      enabled: true,
      measurementId: "G-XXXXXXXXXX",
      debugMode: false,
    },
    logrocket: {
      enabled: false, // Disabled by default
      appId: "your-logrocket-app-id",
    },
    amplitude: {
      enabled: true,
      apiKey: "your-amplitude-api-key",
    },
  },
  globalProperties: {
    appVersion: "1.0.0",
    environment: "production",
  },
  enableDebug: true,
};

// Initialize the analytics gateway
// Each enabled provider will automatically load its script!
const analytics = new AnalyticsGateway(config);

// Track events
analytics.trackEvent({
  name: "Button Clicked",
  properties: {
    buttonId: "signup-button",
    page: "homepage",
  },
});

// Identify users
analytics.identifyUser({
  id: "user-123",
  properties: {
    name: "John Doe",
    email: "[email protected]",
  },
});

// Track page views
analytics.trackPageView({
  url: "/dashboard",
  title: "Dashboard",
});

Toggle Providers

// Disable a specific provider
analytics.disableProvider("mixpanel");

// Enable a provider
analytics.enableProvider("logrocket");

// Disable all providers
analytics.disableAllProviders();

// Enable all providers
analytics.enableAllProviders();

// Check provider status
const status = analytics.getProviderStatus();
console.log(status); // { mixpanel: false, ga4: true, logrocket: true, amplitude: true }

Update Configuration

// Update configuration at runtime
analytics.updateConfig({
  providers: {
    mixpanel: {
      enabled: false, // Disable Mixpanel
      token: "your-mixpanel-token",
    },
  },
  globalProperties: {
    appVersion: "1.1.0", // Update app version
  },
});

React Integration

Automatic Script Loading

The library automatically loads required scripts for each enabled provider. You don't need to manually load scripts!

import React, { useEffect, useState } from "react";
import { AnalyticsGateway } from "analytics-gateway";

const AnalyticsExample = () => {
  const [analyticsGateway, setAnalyticsGateway] =
    useState<AnalyticsGateway | null>(null);

  useEffect(() => {
    // Simply initialize - scripts load automatically!
    const gateway = new AnalyticsGateway({
      providers: {
        amplitude: {
          enabled: true,
          apiKey: "your-api-key",
        },
        mixpanel: {
          enabled: true,
          token: "your-token",
        },
        ga4: {
          enabled: true,
          measurementId: "G-XXXXXXXXXX",
        },
      },
    });

    setAnalyticsGateway(gateway);
  }, []);

  return (
    <div>
      {/* Your component content */}
      {analyticsGateway && <p>Analytics ready!</p>}
    </div>
  );
};

Using the Analytics Provider

import React from "react";
import { AnalyticsProvider, useAnalytics } from "analytics-gateway";

const App = () => {
  const config = {
    providers: {
      mixpanel: {
        enabled: true,
        token: "your-mixpanel-token",
      },
      ga4: {
        enabled: true,
        measurementId: "G-XXXXXXXXXX",
      },
    },
  };

  return (
    <AnalyticsProvider config={config}>
      <YourApp />
    </AnalyticsProvider>
  );
};

const YourComponent = () => {
  const analytics = useAnalytics();

  const handleClick = () => {
    analytics.trackEvent({
      name: "Button Clicked",
      properties: { buttonId: "my-button" },
    });
  };

  return <button onClick={handleClick}>Click Me</button>;
};

Configuration Options

Provider Configuration

Each provider can be configured with the following options:

Mixpanel

mixpanel: {
  enabled: boolean;
  token: string;
  debug?: boolean;
}

Google Analytics 4

ga4: {
  enabled: boolean;
  measurementId: string;
  debugMode?: boolean;
}

LogRocket

logrocket: {
  enabled: boolean;
  appId: string;
  options?: Record<string, any>;
}

Amplitude

amplitude: {
  enabled: boolean;
  apiKey: string;
  options?: Record<string, any>;
}

Global Configuration

{
  providers: { /* provider configs */ };
  globalProperties?: Record<string, any>; // Properties included in all events
  enableDebug?: boolean; // Enable debug logging
}

API Reference

Core Methods

trackEvent(event: AnalyticsEvent)

Track a custom event across all enabled providers.

analytics.trackEvent({
  name: "Purchase Completed",
  properties: {
    amount: 99.99,
    currency: "USD",
    productId: "prod-123",
  },
  userId: "user-456",
  timestamp: Date.now(),
});

identifyUser(user: AnalyticsUser)

Identify a user across all enabled providers.

analytics.identifyUser({
  id: "user-123",
  properties: {
    name: "John Doe",
    email: "[email protected]",
    plan: "premium",
  },
});

trackPageView(pageView: AnalyticsPageView)

Track a page view across all enabled providers.

analytics.trackPageView({
  url: "/dashboard",
  title: "Dashboard",
  properties: {
    referrer: "google.com",
    utm_source: "email",
  },
});

Provider Management

enableProvider(providerName: ProviderName)

Enable a specific analytics provider.

disableProvider(providerName: ProviderName)

Disable a specific analytics provider.

enableAllProviders()

Enable all configured analytics providers.

disableAllProviders()

Disable all analytics providers.

isProviderEnabled(providerName: ProviderName): boolean

Check if a specific provider is enabled.

getProviderStatus(): Record<ProviderName, boolean>

Get the status of all providers.

getAvailableProviders(): ProviderName[]

Get a list of all available provider names.

Configuration Management

setGlobalProperties(properties: Record<string, any>)

Set global properties that will be included in all events.

updateConfig(newConfig: Partial<AnalyticsGatewayConfig>)

Update the configuration at runtime.

getConfig(): AnalyticsGatewayConfig

Get the current configuration.

TypeScript Support

The library is built with TypeScript and provides comprehensive type definitions:

import type {
  AnalyticsEvent,
  AnalyticsUser,
  AnalyticsPageView,
  AnalyticsGatewayConfig,
  ProviderName,
  IAnalyticsProvider,
} from "analytics-gateway";

Error Handling

The library includes built-in error handling and logging:

  • All provider operations are wrapped in try-catch blocks
  • Errors are logged to the console in development mode
  • Failed operations don't break the application flow
  • Debug mode provides detailed logging for troubleshooting

Browser Compatibility

  • Modern browsers (Chrome 60+, Firefox 55+, Safari 12+, Edge 79+)
  • ES2020 support required
  • DOM APIs for script loading and page view tracking

Development

This project uses Vite for fast building and development.

Building the Library

npm run build

Builds the library for production using Vite. Outputs ES modules (.mjs) and CommonJS (.cjs) formats with TypeScript declarations.

Development Mode

npm run dev

Runs Vite in watch mode for development, automatically rebuilding on file changes.

Running Tests

# Run tests once
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with UI
npm run test:ui

# Run tests with coverage
npm run test:coverage

Tests are powered by Vitest, a blazing fast unit test framework.

Linting

# Check for linting issues
npm run lint

# Fix linting issues automatically
npm run lint:fix

Type Checking

npm run type-check

Runs TypeScript compiler to check for type errors without emitting files.

Examples

The examples/ directory contains working examples with their own dependencies. To run the examples:

cd examples
npm install
npm run dev

This will start a development server with live examples you can interact with. See examples/README.md for more details.

Dependency Structure

This project follows a clean dependency structure:

Main Library (package.json)

  • Runtime dependencies: None
  • Peer dependencies: react (optional, for hooks)
  • Dev dependencies: Build tools, testing frameworks, TypeScript types

Examples (examples/package.json)

  • Dependencies: React, analytics provider SDKs (Mixpanel, Amplitude, etc.)
  • Dev dependencies: Vite, React plugins

This separation ensures:

  • The library bundle stays minimal (no external dependencies bundled)
  • Examples can use actual analytics SDKs for testing
  • Users only install what they need

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

License

MIT License - see LICENSE file for details.

Support

For issues and questions, please open an issue on GitHub or contact the maintainers.