traclytics-js-sdk
v1.1.4
Published
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.
Maintainers
Readme
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.
📋 Table of Contents
- Why Traclytics?
- Features
- Installation
- Quick Start
- Core Concepts
- Usage Examples
- API Reference
- Framework Integration
- Best Practices
- 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
# npm
npm install traclytics-js-sdk
# yarn
yarn add traclytics-js-sdk
# pnpm
pnpm add traclytics-js-sdkCDN (Browser)
<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
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
userName: 'John Doe', // Optional: User name
isHris: true, // true if HRIS Login API is used in project
department: 'Engineering', // Optional: Department name
debug: false, // Enable console logs for debugging
isEnable: true // Enable/disable event tracking (default: true)
});2. Track Page Views
// Track when user visits a page/feature
tracker.trackEvent('dashboard', {
action_type: 'view'
});
tracker.trackEvent('payroll-calculator', {
action_type: 'view'
});3. Track User Actions
// 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
// 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)
// 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', // Optional: User identifier
userName: 'John Doe', // Optional: User name
isHris: true, // true if HRIS Login API is used in project
department: 'Engineering', // Optional: Department name
debug: false, // Enable console logs for debugging
isEnable: true // Enable/disable event tracking (default: true)
});// In your components - Import and use
import { tracker } from './analytics';
tracker.trackEvent('dashboard', { action_type: 'view' });Example 2: Basic Page Tracking
import { tracker } from './analytics';
// When component mounts
useEffect(() => {
tracker.trackEvent('employee-directory', { action_type: 'view' });
}, []);Example 3: Page with Actions
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
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.
import { AnalyticsTracker } from 'traclytics-js-sdk';
const tracker = new AnalyticsTracker();tracker.init(config)
Initialize the Traclytics SDK. Call once when your app starts.
interface AnalyticsConfig {
projectKey: string; // Your project key (required)
accessToken: string; // Your access token (required)
userId?: string; // User identifier (optional)
userName?: string; // User name (optional)
isHris: boolean; // Is HRIS Login API Used (required)
department?: string; // Department name (optional)
debug?: boolean; // Enable debug logging (default: false)
isEnable?: boolean; // Enable/disable event tracking (default: true)
}Example:
tracker.init({
projectKey: 'proj_abc123',
accessToken: 'token_xyz789',
userId: 'user-456',
userName: 'Jane Smith',
isHris: false,
department: 'Engineering',
debug: true,
isEnable: true // Set to false to disable all event tracking
});Note: When isEnable is set to false, no events will be sent to the server. This is useful for disabling tracking in development environments or based on user preferences. By default, isEnable is true, so tracking is enabled unless explicitly disabled.
tracker.trackEvent(eventType, details?)
Track an event (page view or action).
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:
// 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
// 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', // Optional: User identifier
userName: 'John Doe', // Optional: User name
isHris: true, // true if HRIS Login API is used in project
department: 'Engineering', // Optional: Department name
debug: false, // Enable console logs for debugging
isEnable: true // Enable/disable event tracking (default: true)
});// 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
// 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', // Optional: User identifier
userName: 'John Doe', // Optional: User name
isHris: true, // true if HRIS Login API is used in project
department: 'Engineering', // Optional: Department name
debug: false, // Enable console logs for debugging
isEnable: true // Enable/disable event tracking (default: true)
});// Dashboard.vue
import { onMounted } from 'vue';
import { tracker } from './analytics';
export default {
setup() {
onMounted(() => {
tracker.trackEvent('dashboard', { action_type: 'view' });
});
}
}Vue 2
import { tracker } from './analytics';
export default {
mounted() {
tracker.trackEvent('dashboard', { action_type: 'view' });
}
}Angular
// 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', // Optional: User identifier
userName: 'John Doe', // Optional: User name
isHris: true, // true if HRIS Login API is used in project
department: 'Engineering', // Optional: Department name
debug: false, // Enable console logs for debugging
isEnable: true // Enable/disable event tracking (default: true)
});
}
trackEvent(eventType: string, details?: any) {
this.tracker.trackEvent(eventType, details);
}
}// 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)
// 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', // Optional: User identifier
userName: 'John Doe', // Optional: User name
isHris: true, // true if HRIS Login API is used in project
department: 'Engineering', // Optional: Department name
debug: false, // Enable console logs for debugging
isEnable: true // Enable/disable event tracking (default: true)
});
}// 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
<!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', // Optional: User identifier
userName: 'John Doe', // Optional: User name
isHris: true, // true if HRIS Login API is used in project
department: 'Engineering', // Optional: Department name
debug: false, // Enable console logs for debugging
isEnable: true // Enable/disable event tracking (default: 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
// ✅ 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', // Optional: User identifier
userName: 'John Doe', // Optional: User name
isHris: true, // true if HRIS Login API is used in project
department: 'Engineering', // Optional: Department name
debug: false, // Enable console logs for debugging
isEnable: true // Enable/disable event tracking (default: true)
});// In other files
import { tracker } from './analytics';
tracker.trackEvent('dashboard', { action_type: 'view' });// ❌ 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:
// ✅ 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 Settings3. Use Meaningful Event Names
// ✅ 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
// ✅ 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
// 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:
- Is
tracker.init()called before tracking events? - Are
projectKeyandaccessTokencorrect? - Enable debug mode:
tracker.init({ ..., debug: true }) - Check browser console for errors
- 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:
- Only one page tracked (need at least 2 events to calculate duration)
- User closed tab immediately (session end captures this)
- Check if
action_type: 'action'was used (actions don't have duration)
Events Sent Multiple Times
Check:
- Is
trackEvent()inside a loop or effect without dependencies? - Is the component mounting multiple times?
// ✅ 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
// 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
// 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: 'your-project-key',
accessToken: 'your-access-token',
userId: 'user-123', // Optional: User identifier
userName: 'John Doe', // Optional: User name
isHris: true, // true if HRIS Login API is used in project
department: 'Engineering', // Optional: Department name
debug: false, // Enable console logs for debugging
isEnable: true // Enable/disable event tracking (default: true)
});
// 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'
});