
Security News
AGENTS.md Gains Traction as an Open Format for AI Coding Agents
AGENTS.md is a fast-growing open format giving AI coding agents a shared, predictable way to understand project setup, style, and workflows.
@threekit/lab-analytics
Advanced tools
Frontend analytics package for tracking user events and retrieving analytics data
A frontend analytics package for tracking user events and retrieving analytics data with Firebase authentication support.
npm install @threekit/lab-analytics
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",
});
// 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"
);
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 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:
// If you have a user ID from your authentication system
analytics.setUserId("user-123");
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 |
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 eventtrackPageView()
Track a page view event. This is called automatically if autoTrackPageViews
is enabled.
setUserId(userId)
Update the user ID for subsequent events.
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.
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
};
}
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
}
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;
}
This client is designed to work with the lab-analytics server, which provides:
/api/analytics
- Store analytics events/api/analytics/{clientName}
- Retrieve analytics dataThis package works in all modern browsers and is compatible with various frontend frameworks including React, Vue, Angular, and vanilla JavaScript applications.
Full TypeScript support is included with comprehensive type definitions for all interfaces and error types.
FAQs
Frontend analytics package for tracking user events and retrieving analytics data
The npm package @threekit/lab-analytics receives a total of 36 weekly downloads. As such, @threekit/lab-analytics popularity was classified as not popular.
We found that @threekit/lab-analytics demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
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.
Security News
AGENTS.md is a fast-growing open format giving AI coding agents a shared, predictable way to understand project setup, style, and workflows.
Security News
/Research
Malicious npm package impersonates Nodemailer and drains wallets by hijacking crypto transactions across multiple blockchains.
Security News
This episode explores the hard problem of reachability analysis, from static analysis limits to handling dynamic languages and massive dependency trees.