observify-tracker
v1.1.1
Published
Lightweight web observability SDK for tracking errors, performance, and network requests in real-time
Maintainers
Readme
- Automatic Error Tracking - Captures uncaught errors and promise rejections
- Breadcrumbs - Track user journey with automatic and manual breadcrumbs
- Performance Monitoring - Tracks page load times and web vitals
- Network Monitoring - Monitors fetch requests (status, duration, failures)
- Session Tracking - Groups events by user session
- Zero Dependencies - Pure vanilla JavaScript
- Tiny Bundle - < 5KB gzipped
- TypeScript Support - Full type definitions included
- Framework Agnostic - Works with React, Vue, Angular, or vanilla JS
Installation
npm
npm install @observify/trackeryarn
yarn add @observify/trackerCDN
<script src="https://cdn.jsdelivr.net/npm/@observify/tracker/dist/tracker.bundle.js"></script>Quick Start
ES Modules (Recommended)
import { Tracker } from '@observify/tracker';
const tracker = new Tracker(
'your-api-key',
'https://your-backend.com/ingest',
1.0 // 100% sampling rate
);
tracker.start();CommonJS
const { Tracker } = require('@observify/tracker');
const tracker = new Tracker(
'your-api-key',
'https://your-backend.com/ingest'
);
tracker.start();CDN / Browser
<script src="https://cdn.jsdelivr.net/npm/@observify/tracker/dist/tracker.bundle.js"></script>
<script>
const tracker = new Observify.Tracker(
'your-api-key',
'https://your-backend.com/ingest'
);
tracker.start();
</script>Usage
Basic Setup
import { Tracker } from '@observify/tracker';
// Initialize tracker
const tracker = new Tracker(
'your-api-key', // Your API key
'https://api.example.com/ingest', // Backend endpoint
1.0 // Sample rate (1.0 = 100%, 0.5 = 50%)
);
// Start tracking
tracker.start();Manual Event Tracking
// Track custom events
tracker.queue({
type: 'custom',
action: 'button_click',
buttonId: 'checkout',
userId: '12345',
ts: Date.now()
});
// Track business metrics
tracker.queue({
type: 'conversion',
event: 'purchase_completed',
amount: 99.99,
currency: 'USD'
});Configuration Options
const tracker = new Tracker(apiKey, endpoint, sampleRate);
// Customize flush interval (default: 3000ms)
tracker.flushInterval = 5000; // Flush every 5 seconds
// Access session ID
console.log(tracker.sessionId); // Unique session identifier
// Check buffer
console.log(tracker.buffer); // Current queued eventsEvent Types
Observify automatically captures these event types:
| Type | Description | Auto-Captured |
|------|-------------|---------------|
| init | Tracker initialization | ✅ |
| error | JavaScript errors | ✅ |
| rejection | Unhandled promise rejections | ✅ |
| network | Successful fetch requests | ✅ |
| network-error | Failed fetch requests | ✅ |
| performance | Page load metrics | ✅ |
| breadcrumb | User journey tracking | ✅ (auto) / ❌ (manual) |
| custom | Your custom events | ❌ (manual) |
🔧 Advanced Usage
Sampling
Control what percentage of sessions are tracked:
// Track 50% of sessions
const tracker = new Tracker('api-key', 'https://api.example.com/ingest', 0.5);
// Track 10% of sessions
const tracker = new Tracker('api-key', 'https://api.example.com/ingest', 0.1);Manual Flush
// Flush events immediately
await tracker.flush();React Integration
import { useEffect } from 'react';
import { Tracker } from '@observify/tracker';
function App() {
useEffect(() => {
const tracker = new Tracker(
process.env.REACT_APP_OBSERVIFY_KEY,
process.env.REACT_APP_OBSERVIFY_ENDPOINT
);
tracker.start();
return () => {
tracker.flush(); // Flush on unmount
};
}, []);
return <div>Your App</div>;
}Vue Integration
import { Tracker } from '@observify/tracker';
export default {
created() {
this.tracker = new Tracker(
process.env.VUE_APP_OBSERVIFY_KEY,
process.env.VUE_APP_OBSERVIFY_ENDPOINT
);
this.tracker.start();
},
beforeUnmount() {
this.tracker.flush();
}
};🍞 Breadcrumbs
Breadcrumbs help you understand the user journey leading up to an error or event. Observify automatically captures breadcrumbs for common user interactions and allows you to add custom breadcrumbs.
Automatic Breadcrumbs
Observify automatically captures breadcrumbs for:
- Navigation: Page loads and URL changes
- User Clicks: Button and link clicks (with XPath)
- Network Requests: Fetch API calls (URL, method, status, duration)
// Breadcrumbs are captured automatically when you start the tracker
tracker.start();
// Now all navigation, clicks, and network requests are tracked!Manual Breadcrumbs
Add custom breadcrumbs to track business logic, user flows, or important events:
// Basic breadcrumb
tracker.addBreadcrumb({
message: 'User started checkout',
category: 'navigation'
});
// Breadcrumb with additional data
tracker.addBreadcrumb({
message: 'Item added to cart',
category: 'user-action',
level: 'info',
data: {
productId: '12345',
quantity: 2,
price: 29.99
}
});
// Error-level breadcrumb
tracker.addBreadcrumb({
message: 'Payment validation failed',
category: 'business-logic',
level: 'error',
data: {
reason: 'Invalid card number',
attemptCount: 3
}
});Breadcrumb Properties
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| message | string | ✅ | Description of the breadcrumb |
| category | string | ❌ | Category (e.g., 'navigation', 'user-action', 'network') |
| level | 'info' \| 'warning' \| 'error' \| 'debug' | ❌ | Severity level (default: 'info') |
| data | object | ❌ | Additional context data |
| timestamp | number | ❌ | Auto-generated if not provided |
Breadcrumbs in Error Events
When an error occurs, Observify automatically attaches the last 50 breadcrumbs to the error event:
// User journey:
// 1. Clicked "Add to Cart" button
// 2. Navigated to /checkout
// 3. Filled payment form
// 4. Error occurred!
// The error event will include all breadcrumbs:
{
type: 'error',
message: 'Payment processing failed',
breadcrumbs: [
{ type: 'ui.click', message: 'Clicked button#add-to-cart', ... },
{ type: 'navigation', message: 'Navigated to /checkout', ... },
{ type: 'user-action', message: 'Filled payment form', ... }
],
// ... other error properties
}Breadcrumb Limits
- Maximum breadcrumbs: 50 (configurable via
tracker.maxBreadcrumbs) - Oldest breadcrumbs are removed when limit is reached
- Breadcrumbs are session-scoped (cleared on page reload)
// Customize max breadcrumbs (default: 50)
tracker.maxBreadcrumbs = 100;Accessing Breadcrumbs
// View current breadcrumbs
console.log(tracker.breadcrumbs);
// Get breadcrumb count
console.log(`Total breadcrumbs: ${tracker.breadcrumbs.length}`);Backend Setup
You need a backend to receive events. See the full project for a complete backend implementation.
Quick backend example:
// Express.js endpoint
app.post('/ingest', (req, res) => {
const events = req.body.events;
// Store events in database
console.log('Received events:', events);
res.json({ ok: true });
});API Reference
Tracker
Constructor
new Tracker(apiKey: string, endpoint: string, sampleRate?: number)Parameters:
apiKey- Your API key for authenticationendpoint- Backend ingestion URLsampleRate- Sampling rate 0-1 (default: 1)
Methods
start()
- Initializes event listeners
- Starts auto-flush timer
- Sends init event
queue(event: TrackerEvent)
- Manually queue an event
- Auto-flushes if buffer reaches 8 events
flush(): Promise<void>
- Manually flush buffered events
- Returns a promise
addBreadcrumb(breadcrumb: Partial<Breadcrumb>)
- Manually add a breadcrumb to track user journey
- Breadcrumbs are automatically attached to error events
- Maximum 50 breadcrumbs kept (configurable)
Properties
buffer: TrackerEvent[]- Current event buffersessionId: string- Unique session IDflushInterval: number- Flush interval in ms (default: 3000)breadcrumbs: Breadcrumb[]- Current breadcrumbs arraymaxBreadcrumbs: number- Maximum breadcrumbs to keep (default: 50)
Contributing
Contributions are welcome! Please see the GitHub repository.
License
MIT © Rethash
Links
Support
- Email: [email protected]
- Issues: GitHub Issues
- Discussions: GitHub Discussions
Made by Rethash LinkedIn: https://www.linkedin.com/in/rethash-reddy/ GitHub: https://github.com/reth0608
