@integrations-cloudoffis/analytics-tracker
v1.2.0
Published
A comprehensive Angular analytics tracking library for frontend applications
Maintainers
Readme
Analytics Tracker
A comprehensive Angular analytics tracking library for frontend applications. This package provides easy-to-use services and directives for tracking user interactions, page views, and custom events across your Angular applications.
Features
- 🎯 Easy Integration: Simple module-based setup with configuration
- 📊 Comprehensive Tracking: Track page views, clicks, and custom events
- 🔧 Flexible Configuration: Customizable API endpoints and authentication
- 📱 Session Management: Automatic session and unique tab ID generation
- 🎨 Directive Support: Built-in directive for easy click tracking
- 🚀 TypeScript Support: Full TypeScript support with type definitions
- 📦 Angular 17+ Compatible: Built for modern Angular applications (17.x, 18.x, 19.x)
Installation
npm install @integrations-cloudoffis/analytics-trackerQuick Start
1. Import the Module
In your app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AnalyticsTrackerModule } from '@integrations-cloudoffis/analytics-tracker';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
AnalyticsTrackerModule.forRoot({
apiKey: 'your-api-key',
apiUrl: 'https://your-analytics-api.com/events'
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }2. Track Page Views
In your components:
import { Component } from '@angular/core';
import { AnalyticsTrackerService } from '@integrations-cloudoffis/analytics-tracker';
@Component({
selector: 'app-home',
template: '<h1>Welcome to Home Page</h1>'
})
export class HomeComponent {
constructor(private analytics: AnalyticsTrackerService) {
// Track page view
this.analytics.trackPageview('HomePage', 'Main');
}
}3. Track User Interactions
Using the Service
import { Component } from '@angular/core';
import { AnalyticsTrackerService } from '@integrations-cloudoffis/analytics-tracker';
@Component({
selector: 'app-button',
template: `
<button (click)="onButtonClick()">
Click Me
</button>
`
})
export class ButtonComponent {
constructor(private analytics: AnalyticsTrackerService) {}
onButtonClick() {
this.analytics.trackFeatureClick(
'ButtonClick',
'HomePage',
'Main',
{ buttonId: 'cta-button', value: 'clicked' }
);
}
}Using the Directive
import { Component } from '@angular/core';
@Component({
selector: 'app-feature',
template: `
<button
trackClick="FeatureButtonClick"
screenName="HomePage"
moduleName="Main"
type="UserInteraction"
[trackData]="{ feature: 'premium-upgrade' }"
jobId="job123"
jobName="Senior Developer"
firmName="Acme Corporation">
Upgrade to Premium
</button>
<!-- For navigation events -->
<a
trackClick="ViewAccountDetails"
screenName="AccountList"
moduleName="Accounting"
type="Navigation"
routerLink="/account/123">
View Account
</a>
`
})
export class FeatureComponent {}API Reference
AnalyticsTrackerService
Methods
trackPageview(screenName: string, moduleName?: string)
Tracks a page view event.
Parameters:
screenName(string): Name of the screen/page being viewedmoduleName(string, optional): Module name (defaults to 'Navigation')
trackFeatureClick(actionName: string, screenName: string, moduleName: string, extraData?: object)
Tracks a user interaction event.
Parameters:
actionName(string): Name of the action performedscreenName(string): Name of the screen where action occurredmoduleName(string): Module nameextraData(object, optional): Additional data to track
getCurrentTabId(): string
Gets the current tab ID for debugging purposes.
Returns: The unique tab ID for this tab
getCurrentSessionId(): string
Gets the current session ID for debugging purposes.
Returns: The session ID
trackEvent(eventName: string, extraData?: object): void
Tracks a simple custom event with just the event name.
Parameters:
eventName(string): Name of the event to trackextraData(object, optional): Additional data to include in the event
trackCustomEvent(eventName: string, screenName: string, moduleName: string, extraData?: object): void
Tracks a custom event with full control over the payload.
Parameters:
eventName(string): Name of the event to trackscreenName(string): Screen where the event occurredmoduleName(string): Module nameextraData(object, optional): Additional data to include in the event
setUserInfo(userId: string, userName: string, firmName: string): void
Sets user information for analytics tracking.
Parameters:
userId(string): The user IDuserName(string): The user namefirmName(string): The firm name (defaults to empty string if not provided)
setJobInfo(jobId: string, jobName: string): void
Sets job information for analytics tracking.
Parameters:
jobId(string): The job IDjobName(string): The job name
setToken(token: string): void
Sets authentication token for analytics tracking.
Parameters:
token(string): The authentication token
setFirmName(firmName: string): void
Sets firm information for analytics tracking.
Parameters:
firmName(string): The firm name
resetSession(): void
Clears the current session and creates a new one. Call this when a user logs out to start a fresh session.
Use case: User logout - creates a new session ID while keeping the tab ID
clearAllAnalyticsData(): void
Clears all analytics data including session, user, job, firm, and token information. Call this on user logout for a complete reset.
Use case: Complete logout - resets both session ID and tab ID
TrackClickDirective
A standalone directive for easy click tracking.
Inputs
trackClick(string): Action name to trackscreenName(string): Screen name where click occurredmoduleName(string): Module nametype(string, optional): Event type - 'UserInteraction', 'Navigation', or 'CustomEvent' (defaults to 'UserInteraction')trackData(object, optional): Additional data to trackjobId(string, optional): Job ID to include in this specific eventjobName(string, optional): Job name to include in this specific eventfirmName(string, optional): Firm name to include in this specific eventdebugMode(boolean, optional): Enable debug logging to troubleshoot binding issues (defaults to false)
AnalyticsConfig
Configuration interface for the analytics module.
interface AnalyticsConfig {
apiKey: string; // Your API key for authentication
apiUrl: string; // Your analytics API endpoint
}Event Payload Structure
All events are automatically enriched with the following data:
{
module: string, // Module name
action: string, // Action performed
screen: string, // Screen name
type: string, // Event type ('Navigation' or 'UserInteraction')
sessionId: string, // Unique session identifier
tabId: string, // Unique tab identifier
userId: string, // User identifier (from sessionStorage)
userName: string, // User name (from sessionStorage)
duration: number, // Session duration in seconds
jobId: string, // Job identifier (from sessionStorage)
jobName: string, // Job name (from sessionStorage)
firmName: string, // Firm name (from sessionStorage)
eventTimestamp: string, // ISO timestamp in IST (Indian Standard Time) without timezone offset
dataSource: 'FRONTEND', // Always 'FRONTEND'
token: string, // Authentication token (from sessionStorage)
...extraData // Any additional data provided
}Data Management
The library automatically reads various data from sessionStorage. You can set these values using the provided methods or directly in sessionStorage:
Using Service Methods (Recommended)
import { AnalyticsTrackerService } from '@integrations-cloudoffis/analytics-tracker';
constructor(private analytics: AnalyticsTrackerService) {}
// On user login
onLogin(user: any) {
// Set user information with firm name
this.analytics.setUserInfo(user.id, user.name, user.firmName);
// Set job information
this.analytics.setJobInfo(user.jobId, user.jobName);
// Set authentication token
this.analytics.setToken(user.token);
}
// On user logout - IMPORTANT: Call this to reset session
onLogout() {
// Option 1: Reset only the session (keeps tab ID, user can login again)
this.analytics.resetSession();
// Option 2: Clear all analytics data (recommended for complete logout)
this.analytics.clearAllAnalyticsData();
// Then continue with your normal logout logic
this.router.navigate(['/login']);
}Using sessionStorage Directly
// User information
sessionStorage.setItem('analytics_user_id', 'user123');
sessionStorage.setItem('analytics_user_name', 'John Doe');
// Job information
sessionStorage.setItem('analytics_job_id', 'job456');
sessionStorage.setItem('analytics_job_name', 'Senior Developer');
// Authentication token
sessionStorage.setItem('analytics_token', 'your-auth-token');
// Firm name
sessionStorage.setItem('analytics_firm_name', 'Acme Corporation');Session Management
- Session ID: Browser-wide session shared across all tabs
- Stored in
localStorage- same session ID for all tabs in the same browser - Persists until browser is closed or until
resetSession()/clearAllAnalyticsData()is called - Perfect for tracking a single user session across multiple tabs
- Stored in
- Tab ID: Unique ID for each individual tab with duplicate tab detection:
- Stored in
sessionStorage- different tab ID for each tab - Uses multiple uniqueness sources (timestamp, random, performance timing)
- Persists across page reloads within the same tab
- Detects duplicate tabs: When you duplicate a tab, a new unique tab ID is automatically generated
- Uses localStorage registry with heartbeat to track active tabs and prevent ID conflicts
- Stored in
- Auto-cleanup: Old tab registrations are automatically cleaned up after 5 seconds of inactivity
Development
Building the Library
# Build the library
npm run build:lib
# Build for production
npm run build:lib:prod
# Build and watch for changes
npm run build:lib:watchTesting
# Run unit tests
npm testPublishing
# Build the library
npm run build:lib:prod
# Pack the library (creates .tgz file)
npm run pack:lib
# Publish to npm
npm run publish:libRequirements
- Angular 17.0.0 or higher
- TypeScript 5.7.2 or higher
- Node.js 18 or higher
License
MIT
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Support
If you encounter any issues or have questions, please file an issue on the GitHub repository.
