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

@threekit/lab-analytics

v1.2.3

Published

Frontend analytics package for tracking user events and retrieving analytics data

Downloads

215

Readme

Lab Analytics

A frontend analytics package for tracking user events and retrieving analytics data with Firebase authentication support.

Installation

npm install @threekit/lab-analytics

Features

  • Event tracking
  • Page view tracking
  • Analytics data retrieval
  • Firebase authentication integration
  • Anonymous user tracking
  • Session management
  • Query filtering and pagination
  • TypeScript support

Usage

Basic Setup

import { Analytics } from "@threekit/lab-analytics";

const analytics = new Analytics({
  endpoint: "https://your-analytics-api.com/api/analytics",
  clientName: "web-app",
  debug: true, // Set to false in production
  autoTrackPageViews: true,
});

// Track an event
analytics.trackEvent("button_click", {
  button_id: "signup-button",
  page_section: "hero",
});

Retrieving Analytics Data

// Get all analytics data for your client
const allData = await analytics.getAnalytics();
console.log(`Total events: ${allData.metadata.total}`);
console.log(`Events:`, allData.data);

// Get analytics with filtering and pagination
const filteredData = await analytics.getAnalytics({
  eventType: "page_view",
  startDate: "2024-01-01T00:00:00Z",
  endDate: "2024-01-31T23:59:59Z",
  limit: 100,
  offset: 0,
  orderBy: "timestamp",
  orderDirection: "desc"
});

// Get user-specific analytics
const userAnalytics = await analytics.getUserAnalytics("user-123", {
  startDate: "2024-01-01T00:00:00Z",
  limit: 50
});

// Get session-specific analytics
const sessionAnalytics = await analytics.getSessionAnalytics("session-456");

// Get analytics for specific event types
const buttonClicks = await analytics.getEventAnalytics("button_click");

// Get analytics for a date range
const weeklyData = await analytics.getAnalyticsInDateRange(
  "2024-01-01T00:00:00Z",
  "2024-01-07T23:59:59Z"
);

Error Handling

import { AnalyticsApiError } from "@threekit/lab-analytics";

try {
  const data = await analytics.getAnalytics({
    startDate: "2024-01-01",
    endDate: "2024-12-31" // This will fail - exceeds 90 day limit
  });
} catch (error) {
  if (error instanceof AnalyticsApiError) {
    console.error(`API Error (${error.statusCode}):`, error.details);
  } else {
    console.error("Unexpected error:", error);
  }
}

Firebase Authentication

Firebase is configured using environment variables. Make sure the following environment variables are set in your build environment:

FIREBASE_API_KEY=your-api-key
FIREBASE_AUTH_DOMAIN=your-project.firebaseapp.com
FIREBASE_PROJECT_ID=your-project-id
FIREBASE_STORAGE_BUCKET=your-project.appspot.com
FIREBASE_MESSAGING_SENDER_ID=your-sender-id
FIREBASE_APP_ID=your-app-id
FIREBASE_MEASUREMENT_ID=your-measurement-id

When no userId is provided, the library will:

  1. Initialize Firebase with the environment variables
  2. Sign in anonymously
  3. Include the Firebase token in API requests

Manual User ID Setting

// If you have a user ID from your authentication system
analytics.setUserId("user-123");

How It Works

  1. Firebase authentication is configured using environment variables
  2. If no user ID is provided, it automatically signs in anonymously
  3. Firebase auth token is included in API requests to your backend
  4. Events include user ID, session ID, and other contextual information
  5. Retrieve analytics data using the same authentication system

Configuration Options

When initializing the Analytics client, you can provide various configuration options:

| Option | Type | Description | Required | | -------------------- | ------- | --------------------------------------------------- | -------- | | endpoint | string | URL of your analytics server endpoint | Yes | | clientName | string | Identifier for your application | Yes | | userId | string | User identifier | No | | sessionId | string | Session identifier (auto-generated if not provided) | No | | debug | boolean | Enable debug logging to console | No | | autoTrackPageViews | boolean | Automatically track page views | No | | headers | object | Additional headers to include with requests | No |

API Reference

Event Tracking

new Analytics(options)

Creates a new analytics client instance with the provided options.

trackEvent(eventName, eventData?, eventItem?)

Track a custom event with optional data and item identifier.

  • eventName: Name of the event (e.g., 'button_click')
  • eventData: Object containing additional data about the event
  • eventItem: Optional identifier for the item associated with the event

trackPageView()

Track a page view event. This is called automatically if autoTrackPageViews is enabled.

setUserId(userId)

Update the user ID for subsequent events.

Analytics Data Retrieval

getAnalytics(params?): Promise<AnalyticsDataResponse>

Retrieve analytics data with optional filtering and pagination.

Query Parameters:

  • userId?: string - Filter by specific user ID
  • sessionId?: string - Filter by specific session ID
  • eventType?: string - Filter by specific event type/name
  • startDate?: string - Start date for date range filter (ISO string, max 90 days range)
  • endDate?: string - End date for date range filter (ISO string)
  • limit?: number - Number of results (default: 50, max: 500)
  • offset?: number - Number of results to skip (default: 0)
  • orderBy?: 'timestamp' | 'event_name' - Field to order by (default: 'timestamp')
  • orderDirection?: 'asc' | 'desc' - Order direction (default: 'desc')

getUserAnalytics(userId, additionalParams?): Promise<AnalyticsDataResponse>

Get analytics data for a specific user.

getSessionAnalytics(sessionId, additionalParams?): Promise<AnalyticsDataResponse>

Get analytics data for a specific session.

getEventAnalytics(eventType, additionalParams?): Promise<AnalyticsDataResponse>

Get analytics data for a specific event type.

getAnalyticsInDateRange(startDate, endDate, additionalParams?): Promise<AnalyticsDataResponse>

Get analytics data for a specific date range.

Response Format

Analytics Data Response

interface AnalyticsDataResponse {
  data: AnalyticsEventData[];
  metadata: {
    total: number;        // Total results available
    limit: number;        // Results per page
    offset: number;       // Results skipped
    hasMore: boolean;     // More results available
    queryTimeMs: number;  // Query execution time
    clientName: string;   // Client name queried
  };
}

Individual Event Data

interface AnalyticsEventData {
  event_timestamp: string;           // ISO timestamp
  event_name: string;               // Event type/name
  session_id: string | null;       // Session identifier
  user_id: string | null;          // User identifier
  client_name: string | null;      // Client name
  page_url: string | null;         // Page URL
  referer_url: string | null;      // Referrer URL
  event_data: object | null;       // Additional event data
  event_item: string | null;       // Event item
  user_agent: string | null;       // User agent string
}

Event Structure

Events sent to the server follow this structure:

{
  event_name: string;
  event_timestamp: string; // ISO format
  session_id: string;
  user_id?: string;
  client_name: string;
  page_url?: string;
  referer_url?: string;
  event_data?: object;
  event_item?: string;
  user_agent?: string;
}

Rate Limiting & Best Practices

Retrieving Analytics Data

  • Date Range: Maximum 90 days between startDate and endDate
  • Pagination: Maximum 500 results per request
  • Authentication: Firebase token required for all data retrieval
  • Caching: API responses are cached (5 minutes for recent data, 1 hour for historical)

Sending Events

  • Events are sent asynchronously and don't block your application
  • Failed events are logged in debug mode but don't throw errors
  • Authentication is handled automatically

Server Integration

This client is designed to work with the lab-analytics server, which provides:

  • POST /api/analytics - Store analytics events
  • GET /api/analytics/{clientName} - Retrieve analytics data

Browser Compatibility

This package works in all modern browsers and is compatible with various frontend frameworks including React, Vue, Angular, and vanilla JavaScript applications.

TypeScript Support

Full TypeScript support is included with comprehensive type definitions for all interfaces and error types.