Understanding User Behavior
User behavior analytics tracks how users interact with your product. It reveals patterns, identifies pain points, and guides improvements.
typescript
interface UserEvent {
userId: string;
action: string;
context: Record<string, any>;
timestamp: Date;
}Tracking User Actions
Event Types
typescript
// Page views
trackPageView('/dashboard', {
referrer: document.referrer,
loadTime: performance.now()
});
// Clicks
trackClick('button-purchase', {
page: '/checkout',
variant: 'A'
});
// Form submissions
trackFormSubmit('signup-form', {
fields: ['email', 'name'],
errors: 0
});
// Errors
trackError('api-failure', {
endpoint: '/api/users',
status: 500
});User Sessions
Session Tracking
typescript
class SessionTracker {
private sessionId: string;
private startTime: Date;
private events: UserEvent[] = [];
constructor() {
this.sessionId = generateUUID();
this.startTime = new Date();
}
track(action: string, context: Record<string, any>) {
const event: UserEvent = {
userId: this.getUserId(),
action,
context,
timestamp: new Date()
};
this.events.push(event);
this.send(event);
}
getDuration(): number {
return Date.now() - this.startTime.getTime();
}
getSessionData() {
return {
sessionId: this.sessionId,
duration: this.getDuration(),
eventCount: this.events.length,
events: this.events
};
}
}Behavioral Patterns
User Journeys
typescript
function analyzeUserJourney(userId: string) {
const events = getEventsForUser(userId);
const journey = [];
for (const event of events) {
journey.push({
action: event.action,
timestamp: event.timestamp,
page: event.context.page,
duration: calculateDuration(event)
});
}
return journey;
}Drop-off Analysis
typescript
function identifyDropOffs(journey: JourneyEvent[]) {
const dropOffs = [];
for (let i = 0; i < journey.length - 1; i++) {
const current = journey[i];
const next = journey[i + 1];
const timeDiff = next.timestamp.getTime() - current.timestamp.getTime();
// If gap > 30 minutes, potential drop-off
if (timeDiff > 30 * 60 * 1000) {
dropOffs.push({
from: current.action,
to: next.action,
timeGap: timeDiff,
reason: 'session_timeout'
});
}
}
return dropOffs;
}Heatmaps and Click Tracking
Mouse Tracking
typescript
function trackMouseMovement() {
document.addEventListener('mousemove', (e) => {
analytics.track('mouse_move', {
x: e.clientX,
y: e.clientY,
page: window.location.pathname
});
});
}
function trackClicks() {
document.addEventListener('click', (e) => {
analytics.track('element_click', {
element: e.target.tagName,
id: e.target.id,
class: e.target.className,
x: e.clientX,
y: e.clientY
});
});
}Scroll Depth
typescript
function trackScrollDepth() {
let maxDepth = 0;
window.addEventListener('scroll', () => {
const scrollPercent = (
(window.scrollY + window.innerHeight) / document.body.scrollHeight
) * 100;
if (scrollPercent > maxDepth) {
maxDepth = scrollPercent;
analytics.track('scroll_depth', {
depth: Math.round(maxDepth),
page: window.location.pathname
});
}
});
}Form Analytics
Field Tracking
typescript
function trackFormFields(form: HTMLFormElement) {
const fields = form.querySelectorAll('input, textarea, select');
fields.forEach(field => {
let focusTime = 0;
let focusStart = 0;
field.addEventListener('focus', () => {
focusStart = Date.now();
});
field.addEventListener('blur', () => {
focusTime += Date.now() - focusStart;
analytics.track('field_completed', {
fieldName: field.name,
fieldType: field.type,
timeSpent: focusTime,
wasModified: field.value !== field.defaultValue
});
});
});
}Best Practices
- 1Respect privacy (GDPR, CCPA)
- 2Don't track sensitive data
- 3Provide opt-out options
- 4Keep performance impact minimal
- 5Use sampling for high-traffic sites
Conclusion
User behavior analytics reveals how users interact with your product. Use insights to improve UX, increase engagement, and drive growth.
Understand your users!