@agroideas/event-tracker-sdk
v1.0.4
Published
A lightweight, framework-agnostic SDK for tracking frontend user behavior
Maintainers
Readme
@agroideas/event-tracker-sdk
A lightweight, framework-agnostic TypeScript SDK for tracking frontend user behavior. Automatically captures page views, session duration, and user interactions, sending them to a centralized analytics API.
Features
- 🚀 Lightweight: Zero dependencies, built with native Fetch API and DOM APIs
- 🔄 SPA Support: Handles navigation in Single Page Applications via History API interception
- 📦 Smart Batching: Events are batched by size and time interval for optimal performance
- 🔒 Reliable Delivery: Uses
sendBeaconwithkeepaliveto ensure events are sent on page unload - 🌐 Framework Agnostic: Works with any frontend framework (React, Vue, Angular, Vanilla JS)
- 📊 Rich Context: Automatically captures device, browser, and session metadata
Installation
npm
npm install @agroideas/event-tracker-sdkpnpm
pnpm add @agroideas/event-tracker-sdkyarn
yarn add @agroideas/event-tracker-sdkQuick Start
ESM / TypeScript
import { tracker } from '@agroideas/event-tracker-sdk';
// Initialize with required configuration
tracker.init({
apiKey: 'your-api-key',
endpoint: 'https://your-api.com/events',
debug: true, // Optional: logs events to console
});
// Identify users when they log in
tracker.identify('user-123', 'John Doe');
// Events are now being tracked automatically!IIFE / Script Tag
<script src="https://cdn.your-domain.com/event-tracker.global.js"></script>
<script>
window.EventTracker.init({
apiKey: 'your-api-key',
endpoint: 'https://your-api.com/events',
});
window.EventTracker.identify('user-123', 'John Doe');
</script>API Reference
tracker.init(config)
Initializes the tracker with configuration options.
| Parameter | Type | Required | Default | Description |
| ----------------- | -------------------- | -------- | ------- | ---------------------------------------- |
| apiKey | string | Yes | - | Your API key for authentication |
| endpoint | string | Yes | - | URL to send events to |
| batchInterval | number | No | 10000 | Milliseconds between batch sends |
| maxBufferSize | number | No | 15 | Maximum events before forced send |
| debug | boolean | No | false | Log events to console instead of sending |
| userId | string | No | - | Initial user ID |
| userName | string | No | - | Initial user name |
| excludePatterns | (string\|RegExp)[] | No | - | URLs to exclude from tracking |
tracker.init({
apiKey: 'your-api-key',
endpoint: 'https://api.example.com/track',
batchInterval: 5000,
maxBufferSize: 20,
debug: true,
excludePatterns: ['/tracker-reports', '/admin', /^\/private\//],
});tracker.identify(userId, userName?)
Identifies a user. Call this when a user logs in or when their information changes.
// After user logs in
tracker.identify('user-123', 'John Doe');
// Update user name
tracker.identify('user-123', 'Jane Doe');tracker.flush()
Immediately sends all pending events. Useful before critical actions like form submissions.
await tracker.flush();tracker.pause()
Pauses the tracker. No events will be recorded until resume() is called.
// Pause tracking
tracker.pause();
// Console: ⏸️ [EventTracker] Tracker pausado - No se registrarán eventostracker.resume()
Resumes the tracker after a pause. Events will be recorded again.
// Resume tracking
tracker.resume();
// Console: ▶️ [EventTracker] Tracker reanudado - Eventos serán registradostracker.toggleDebug()
Toggles debug mode on/off at runtime. Logs the status change to console.
// Toggle debug mode
tracker.toggleDebug();
// Console: 🔍 [EventTracker] Modo debug ACTIVADO ✅
// Console: 🔍 [EventTracker] Modo debug DESACTIVADO ❌tracker.destroy()
Stops all tracking and clears event buffers. Call this when users log out.
tracker.destroy();Automatically Tracked Events
The SDK automatically captures the following events:
page_view
Fired on initial page load and when the URL changes (including SPA navigation).
Data:
path: The current URL path
page_leave
Fired when the user leaves a page or closes the tab.
Data:
path: The page pathduration: Time spent on the page in seconds
user_click
Fired when the user clicks on interactive elements.
Data:
tagName: HTML element tag (e.g., "BUTTON", "A")id: Element ID (if present)className: CSS classes (if present)text: Inner text (truncated to 30 characters)selector: CSS selector path to the element
Context Data
All events include automatic context data:
| Field | Description |
| -------------- | -------------------------------------- |
| sessionId | Unique UUID stored in sessionStorage |
| userId | Current user ID (from identify()) |
| userName | Current user name (from identify()) |
| url | Full current URL |
| referrer | Document referrer |
| screenSize | Screen resolution (e.g., "1920x1080") |
| viewportSize | Viewport dimensions (e.g., "1280x720") |
| deviceType | Desktop, Mobile, or Tablet |
| browser | Browser name and version |
| os | Operating system |
| language | Browser language |
| timestamp | ISO 8601 timestamp |
Configuration Example
React Application
import { useEffect } from 'react';
import { tracker } from '@agroideas/event-tracker-sdk';
function App() {
useEffect(() => {
tracker.init({
apiKey: process.env.REACT_APP_TRACKER_API_KEY,
endpoint: process.env.REACT_APP_TRACKER_ENDPOINT,
});
return () => {
tracker.destroy();
};
}, []);
const handleLogin = () => {
// ... login logic
tracker.identify('user-123', 'John Doe');
};
const handleSubmit = async () => {
await tracker.flush();
// Submit form
};
return (
<button onClick={handleLogin}>Login</button>
<form onSubmit={handleSubmit}>
{/* form fields */}
</form>
);
}Vue 3 Application
import { tracker } from '@agroideas/event-tracker-sdk';
import { onMounted, onUnmounted } from 'vue';
export default {
setup() {
onMounted(() => {
tracker.init({
apiKey: import.meta.env.VITE_TRACKER_API_KEY,
endpoint: import.meta.env.VITE_TRACKER_ENDPOINT,
});
});
onUnmounted(() => {
tracker.destroy();
});
const login = (userId: string, userName: string) => {
tracker.identify(userId, userName);
};
return { login };
},
};Privacy Considerations
- Input Fields: The SDK automatically excludes password field values from click tracking
- Sensitive Data: No user data is stored locally; all data is sent directly to your endpoint
- User Consent: Implement your own consent management before initializing the tracker if required by GDPR/CCPA
Build Outputs
The SDK is compiled to multiple formats:
| Format | File | Usage |
| ---------- | ---------------------- | ------------------------------- |
| ES Module | dist/index.mjs | Modern browsers, bundlers |
| CommonJS | dist/index.js | Node.js, older bundlers |
| IIFE | dist/index.global.js | Direct script inclusion |
| TypeScript | dist/index.d.ts | IDE autocomplete, type checking |
Development
# Install dependencies
pnpm install
# Start development mode (watch mode)
pnpm dev
# Run linter
pnpm lint
# Format code
pnpm format
# Build for production
pnpm build
# Run type checking
pnpm type-checkContributing
- Fork the repository
- Create a feature branch
- Make your changes
- Run
pnpm lintandpnpm build - Submit a pull request
License
MIT License - see LICENSE file for details
