UNPKG

traclytics-js-sdk

Version:

Simple, privacy-focused analytics SDK for internal tools and applications. Track feature usage, measure engagement, and understand how your internal tools are being usedβ€”without the complexity of enterprise analytics platforms.

703 lines (562 loc) β€’ 17 kB
# Traclytics JavaScript SDK > Simple, privacy-focused analytics for internal tools and applications Track feature usage, measure engagement, and understand how your internal tools are being usedβ€”without the complexity of enterprise analytics platforms. [![npm version](https://img.shields.io/npm/v/traclytics-js-sdk.svg)](https://www.npmjs.com/package/traclytics-js-sdk) --- ## πŸ“‹ Table of Contents - [Why Traclytics?](#-why-traclytics) - [Features](#-features) - [Installation](#-installation) - [Quick Start](#-quick-start) - [Core Concepts](#-core-concepts) - [Usage Examples](#-usage-examples) - [API Reference](#-api-reference) - [Framework Integration](#-framework-integration) - [Best Practices](#-best-practices) - [Troubleshooting](#-troubleshooting) --- ## 🎯 Why Traclytics? Built specifically for **internal applications** of SSL Wireless where you need to answer questions like: - How many employees are actually using our HR portal? - Which features save the most time? - Where do users spend the most time? - Is our new automated features being adopted? --- ## ✨ Features - **πŸ“Š Accurate Time Tracking** - Measures active engagement time, excluding idle periods and tab switches - **🎯 Two Event Types** - Simple distinction between page views (duration) and actions (clicks) - **πŸ”’ Privacy-First** - Designed for internal use, no third-party tracking - **⚑ Lightweight** - < 10KB gzipped, zero dependencies - **🌐 Framework Agnostic** - Works with React, Vue, Angular, vanilla JS, or any framework - **πŸ“± Cross-Platform** - Browser, device, and OS detection built-in - **πŸ’Ύ Session Management** - Automatic session tracking across page refreshes - **πŸ”„ Offline Resilient** - Uses keepalive to ensure data reaches server even on page close --- ## πŸ“¦ Installation ```bash # npm npm install traclytics-js-sdk # yarn yarn add traclytics-js-sdk # pnpm pnpm add traclytics-js-sdk ``` ### CDN (Browser) ```html <script src="https://unpkg.com/traclytics-js-sdk@latest/dist/analytics.min.js"></script> <script> const tracker = new Traclytics.AnalyticsTracker(); </script> ``` --- ## πŸš€ Quick Start ### 1. Initialize the SDK ```javascript import { AnalyticsTracker } from 'traclytics-js-sdk'; // Create tracker instance const tracker = new AnalyticsTracker(); // Initialize once when your app starts tracker.init({ projectKey: 'your-project-key', accessToken: 'your-access-token', userId: 'user-123', // Optional: User identifier isHris: true, // true if HRIS Login API is used in project department: 'Engineering', // Required if isHris is false debug: false // Enable console logs for debugging }); ``` ### 2. Track Page Views ```javascript // Track when user visits a page/feature tracker.trackEvent('dashboard', { action_type: 'view' }); tracker.trackEvent('payroll-calculator', { action_type: 'view' }); ``` ### 3. Track User Actions ```javascript // Track button clicks, downloads, searches tracker.trackEvent('export-report', { action_type: 'action', format: 'xlsx', // custom field rows: 150 // custom field }); tracker.trackEvent('search-employee', { action_type: 'action', query: 'john doe' // custom field }); ``` That's it! πŸŽ‰ --- ## πŸ’‘ Core Concepts ### Two Event Types Traclytics uses a simple model with two types of events: | Type | When to Use | Duration Tracked? | Example | |------|-------------|-------------------|---------| | **`view`** | Page views, feature usage | βœ… Yes | Dashboard, Reports, Calculator | | **`action`** | Button clicks, downloads, searches | ❌ No | Export CSV, Download PDF, Filter | ### How Duration Tracking Works ```javascript // User visits Dashboard at 10:00 tracker.trackEvent('dashboard', { action_type: 'view' }); // User clicks export button at 10:03 (still on Dashboard) tracker.trackEvent('export-csv', { action_type: 'action' }); // βœ… Export action logged immediately // ⏱️ Dashboard duration still counting... // User navigates to Reports at 10:05 tracker.trackEvent('reports', { action_type: 'view' }); // βœ… Dashboard duration saved: 5 minutes // ⏱️ Reports duration starts counting... ``` **Key Points:** - βœ… **Views** track how long users spend on pages/features - βœ… **Actions** are instant events that don't interrupt view duration - βœ… Active time excludes tab switches and idle periods - βœ… Last page view sent when session ends (tab close) --- ## πŸ“š Usage Examples ### Example 1: Basic Setup (Single File) ```javascript // analytics.js - Create once and export import { AnalyticsTracker } from 'traclytics-js-sdk'; export const tracker = new AnalyticsTracker(); // Initialize tracker.init({ projectKey: 'your-project-key', accessToken: 'your-access-token', userId: 'user-123', isHris: true, debug: false }); ``` ```javascript // In your components - Import and use import { tracker } from './analytics'; tracker.trackEvent('dashboard', { action_type: 'view' }); ``` ### Example 2: Basic Page Tracking ```javascript import { tracker } from './analytics'; // When component mounts useEffect(() => { tracker.trackEvent('employee-directory', { action_type: 'view' }); }, []); ``` ### Example 3: Page with Actions ```javascript import { tracker } from './analytics'; function ReportsPage() { useEffect(() => { // Track page view tracker.trackEvent('reports-page', { action_type: 'view' }); }, []); const handleDownload = (format) => { // Track download action tracker.trackEvent('download-report', { action_type: 'action', format: format, reportType: 'monthly' }); }; const handleFilter = (filterValue) => { // Track filter action tracker.trackEvent('apply-filter', { action_type: 'action', filter: filterValue }); }; return ( <div> <button onClick={() => handleDownload('pdf')}>Download PDF</button> <button onClick={() => handleFilter('last-30-days')}>Filter</button> </div> ); } ``` ### Example 4: Tracking with Custom Metadata ```javascript import { tracker } from './analytics'; // Track with additional context tracker.trackEvent('expense-calculator', { action_type: 'view', department: 'Finance', calculationType: 'travel', timeSaved: 900000 // 15 minutes in ms }); // Track action with context tracker.trackEvent('submit-expense', { action_type: 'action', amount: 1250.50, category: 'travel', receipts: 3 }); ``` --- ## πŸ“– API Reference ### `new AnalyticsTracker()` Create a new tracker instance. ```javascript import { AnalyticsTracker } from 'traclytics-js-sdk'; const tracker = new AnalyticsTracker(); ``` ### `tracker.init(config)` Initialize the Traclytics SDK. Call once when your app starts. ```typescript interface AnalyticsConfig { projectKey: string; // Your project key (required) accessToken: string; // Your access token (required) userId?: string; // User identifier (optional) isHris: boolean; // Is HRIS Login API Used (required) department?: string; // Department name (required if isHris=false) debug?: boolean; // Enable debug logging (default: false) } ``` **Example:** ```javascript tracker.init({ projectKey: 'proj_abc123', accessToken: 'token_xyz789', userId: 'user-456', isHris: false, department: 'Engineering', debug: true }); ``` ### `tracker.trackEvent(eventType, details?)` Track an event (page view or action). ```typescript tracker.trackEvent( eventType: string, details?: { action_type?: 'view' | 'action', // Default: 'view' [key: string]: any // Custom metadata } ); ``` **Parameters:** - `eventType` (required): Name of the event (e.g., 'dashboard', 'export-csv') - `details.action_type`: Either `'view'` (duration tracked) or `'action'` (instant) - `details.*`: Any custom data you want to include **Examples:** ```javascript // Simple view tracker.trackEvent('dashboard'); // View with metadata tracker.trackEvent('reports', { action_type: 'view', reportType: 'sales' }); // Action tracker.trackEvent('export-csv', { action_type: 'action', format: 'xlsx' }); ``` --- ## πŸ”§ Framework Integration ### React ```javascript // analytics.js import { AnalyticsTracker } from 'traclytics-js-sdk'; export const tracker = new AnalyticsTracker(); tracker.init({ projectKey: 'your-project-key', accessToken: 'your-access-token', userId: 'user-123', isHris: true }); ``` ```javascript // Dashboard.jsx import { useEffect } from 'react'; import { tracker } from './analytics'; function Dashboard() { useEffect(() => { tracker.trackEvent('dashboard', { action_type: 'view' }); }, []); return <div>Dashboard content</div>; } ``` ### Vue 3 ```javascript // analytics.js import { AnalyticsTracker } from 'traclytics-js-sdk'; export const tracker = new AnalyticsTracker(); tracker.init({ projectKey: 'your-project-key', accessToken: 'your-access-token', userId: 'user-123', isHris: true }); ``` ```javascript // Dashboard.vue import { onMounted } from 'vue'; import { tracker } from './analytics'; export default { setup() { onMounted(() => { tracker.trackEvent('dashboard', { action_type: 'view' }); }); } } ``` ### Vue 2 ```javascript import { tracker } from './analytics'; export default { mounted() { tracker.trackEvent('dashboard', { action_type: 'view' }); } } ``` ### Angular ```typescript // analytics.service.ts import { Injectable } from '@angular/core'; import { AnalyticsTracker } from 'traclytics-js-sdk'; @Injectable({ providedIn: 'root' }) export class AnalyticsService { private tracker: AnalyticsTracker; constructor() { this.tracker = new AnalyticsTracker(); this.tracker.init({ projectKey: 'your-project-key', accessToken: 'your-access-token', userId: 'user-123', isHris: true }); } trackEvent(eventType: string, details?: any) { this.tracker.trackEvent(eventType, details); } } ``` ```typescript // dashboard.component.ts import { Component, OnInit } from '@angular/core'; import { AnalyticsService } from './analytics.service'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html' }) export class DashboardComponent implements OnInit { constructor(private analytics: AnalyticsService) {} ngOnInit() { this.analytics.trackEvent('dashboard', { action_type: 'view' }); } } ``` ### Next.js (App Router) ```javascript // analytics.js import { AnalyticsTracker } from 'traclytics-js-sdk'; export const tracker = new AnalyticsTracker(); if (typeof window !== 'undefined') { tracker.init({ projectKey: 'your-project-key', accessToken: 'your-access-token', userId: 'user-123', isHris: true }); } ``` ```javascript // app/dashboard/page.js 'use client'; import { useEffect } from 'react'; import { tracker } from '@/analytics'; export default function DashboardPage() { useEffect(() => { tracker.trackEvent('dashboard', { action_type: 'view' }); }, []); return <div>Dashboard</div>; } ``` ### Vanilla JavaScript ```html <!DOCTYPE html> <html> <head> <script src="https://unpkg.com/traclytics-js-sdk@latest/dist/analytics.min.js"></script> </head> <body> <button id="exportBtn">Export Data</button> <script> // Initialize const tracker = new Traclytics.AnalyticsTracker(); tracker.init({ projectKey: 'your-project-key', accessToken: 'your-access-token', userId: 'user-123', isHris: true }); // Track page view tracker.trackEvent('home-page', { action_type: 'view' }); // Track button click document.getElementById('exportBtn').addEventListener('click', () => { tracker.trackEvent('export-clicked', { action_type: 'action', format: 'csv' }); }); </script> </body> </html> ``` --- ## βœ… Best Practices ### 1. Create a Single Tracker Instance ```javascript // βœ… Good - Create once, import everywhere // analytics.js import { AnalyticsTracker } from 'traclytics-js-sdk'; export const tracker = new AnalyticsTracker(); tracker.init({ projectKey: 'your-project-key', accessToken: 'your-access-token', userId: 'user-123', isHris: true }); ``` ```javascript // In other files import { tracker } from './analytics'; tracker.trackEvent('dashboard', { action_type: 'view' }); ``` ```javascript // ❌ Bad - Creating multiple instances import { AnalyticsTracker } from 'traclytics-js-sdk'; function Dashboard() { const tracker = new AnalyticsTracker(); // Don't do this! tracker.init({ ... }); } ``` ### 2. Track All Major Pages For accurate duration metrics, track every major page or feature: ```javascript // βœ… Good - Track all pages tracker.trackEvent('dashboard', { action_type: 'view' }); tracker.trackEvent('reports', { action_type: 'view' }); tracker.trackEvent('settings', { action_type: 'view' }); // ⚠️ Be aware - Skipped pages affect previous page duration // If you skip tracking "Settings", the "Reports" duration // will include time spent on Settings ``` ### 3. Use Meaningful Event Names ```javascript // βœ… Good - Clear and descriptive tracker.trackEvent('employee-directory', { action_type: 'view' }); tracker.trackEvent('export-employee-list', { action_type: 'action' }); // ❌ Bad - Vague or inconsistent tracker.trackEvent('page1', { action_type: 'view' }); tracker.trackEvent('click', { action_type: 'action' }); ``` ### 4. Add Context with Metadata ```javascript // βœ… Good - Include relevant context tracker.trackEvent('payroll-calculator', { action_type: 'view', department: 'HR', employeeCount: 150, calculationType: 'monthly' }); // βœ… Good - Track what matters tracker.trackEvent('generate-report', { action_type: 'action', reportType: 'attendance', dateRange: '2024-01', timeSaved: 600000 // 10 minutes in ms }); ``` ### 5. Default to `view` for Pages ```javascript // Since 'view' is the default, you can omit it tracker.trackEvent('dashboard'); // Same as { action_type: 'view' } // But be explicit for actions tracker.trackEvent('export-csv', { action_type: 'action' }); ``` --- ## πŸ› Troubleshooting ### Events Not Appearing in Dashboard **Check:** 1. Is `tracker.init()` called before tracking events? 2. Are `projectKey` and `accessToken` correct? 3. Enable debug mode: `tracker.init({ ..., debug: true })` 4. Check browser console for errors 5. Are the features Registered in Traclytics Portal ### Last Page Duration Seems Too Long **This is normal.** If a user visits Page A but Page B doesn't call `trackEvent()`, Page A's duration includes time on Page B. **Solution:** Track events on all major pages. ### Duration Shows as Zero **Possible causes:** 1. Only one page tracked (need at least 2 events to calculate duration) 2. User closed tab immediately (session end captures this) 3. Check if `action_type: 'action'` was used (actions don't have duration) ### Events Sent Multiple Times **Check:** 1. Is `trackEvent()` inside a loop or effect without dependencies? 2. Is the component mounting multiple times? ```javascript // βœ… Correct useEffect(() => { tracker.trackEvent('dashboard', { action_type: 'view' }); }, []); // Empty dependency array // ❌ Wrong useEffect(() => { tracker.trackEvent('dashboard', { action_type: 'view' }); }); // Runs on every render! ``` ### TypeScript Errors ```typescript // If you get import errors, use this syntax import { AnalyticsTracker } from 'traclytics-js-sdk'; const tracker = new AnalyticsTracker(); ``` --- ## πŸ“Š What Gets Tracked Automatically Traclytics automatically captures: - βœ… **Session ID** - Unique identifier for each session - βœ… **Timestamps** - When events occur (local timezone) - βœ… **Duration** - Active time on views (excludes idle/tab-away time) - βœ… **Device Info** - Browser, OS, device type - βœ… **Tab Switches** - Counts when user switches away from tab - βœ… **Idle Time** - Time when tab is hidden or inactive - βœ… **Session Summary** - Total engagement when session ends --- ## πŸ”’ Privacy & Data - No cookies used - No third-party tracking - Data sent only to your Traclytics backend - User IDs are optional - Designed for internal tool analytics, not user tracking --- ## 🚦 Quick Reference Card ```javascript // 1. Install npm install traclytics-js-sdk // 2. Create instance and initialize (once) import { AnalyticsTracker } from 'traclytics-js-sdk'; const tracker = new AnalyticsTracker(); tracker.init({ projectKey: 'xxx', accessToken: 'xxx', userId: 'user-123', isHris: true, debug: false }); // 3. Track page views (duration tracked) tracker.trackEvent('page-name', { action_type: 'view' }); // 4. Track actions (instant, no duration) tracker.trackEvent('action-name', { action_type: 'action' }); // 5. With custom data tracker.trackEvent('feature-name', { action_type: 'view', customField: 'value' }); ``` ---