Socket
Book a DemoInstallSign in
Socket

@threekit/lab-analytics

Package Overview
Dependencies
Maintainers
0
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@threekit/lab-analytics

Frontend analytics package for tracking user events and retrieving analytics data

1.1.1
latest
npmnpm
Version published
Weekly downloads
40
60%
Maintainers
0
Weekly downloads
 
Created
Source

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:

  • Initialize Firebase with the environment variables
  • Sign in anonymously
  • 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

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

Configuration Options

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

OptionTypeDescriptionRequired
endpointstringURL of your analytics server endpointYes
clientNamestringIdentifier for your applicationYes
userIdstringUser identifierNo
sessionIdstringSession identifier (auto-generated if not provided)No
debugbooleanEnable debug logging to consoleNo
autoTrackPageViewsbooleanAutomatically track page viewsNo
headersobjectAdditional headers to include with requestsNo

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.

Keywords

analytics

FAQs

Package last updated on 24 Jul 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.