@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-analyticsFeatures
- 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-idWhen 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:
| 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 eventeventItem: 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 IDsessionId?: string- Filter by specific session IDeventType?: string- Filter by specific event type/namestartDate?: 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.
