Event Tracking Strategy for LogRocket
LogRocket automatically captures many events (page views, clicks, errors, network requests), but custom event tracking allows you to mark important user actions that make sessions searchable and actionable.
When to Track Custom Events
Track custom events for:
- Key business actions (signup, purchase, subscription change)
- Feature usage (important feature activations, settings changes)
- Workflow milestones (onboarding steps, tutorial completion)
- User-initiated actions (support ticket submission, feedback sent)
- Error states or edge cases (payment failure, validation errors)
Don't track custom events for:
- Every click or mouse move (use automatic tracking)
- Navigation between pages (use automatic page views)
- Generic interactions without business meaning
- High-volume repetitive actions (every scroll, every character typed)
Basic Event Tracking Implementation
Simple Event:
import LogRocket from 'logrocket';
LogRocket.track('Button Clicked');
Event with Properties:
LogRocket.track('Feature Enabled', {
featureName: 'Dark Mode',
enabledFrom: 'settings',
userPlan: 'Pro'
});
Event Naming Conventions
Use consistent naming to make events searchable and understandable.
Best Practices:
- Use Title Case: "Feature Enabled" not "feature_enabled"
- Use past tense: "Subscription Upgraded" not "Upgrade Subscription"
- Be specific but concise: "Payment Failed" not "Payment Processing Encountered an Error"
- Avoid generic names: "Feature Used" not "Event1" or "Action"
Good Event Names:
Signup CompletedTrial ExtendedSearch PerformedCheckout StartedIntegration Connected
Bad Event Names:
click(too generic)user_action_1(meaningless)feature_enabled_by_user_from_settings_page(too verbose)
Event Properties
Properties add context to events and make them searchable.
Property Guidelines:
- Use descriptive names:
subscriptionPlannotsp - Use appropriate data types: numbers for amounts, booleans for flags
- Keep property count reasonable (under 20 per event)
- Be consistent with naming across events
Example with Rich Properties:
LogRocket.track('Purchase Completed', {
// Transaction
orderId: 'ORD-12345',
amount: 299.99,
currency: 'USD',
// Items
itemCount: 3,
productIds: ['prod-1', 'prod-2', 'prod-3'],
// Context
paymentMethod: 'stripe',
discountCode: 'SAVE20',
discountAmount: 60,
// User state
firstPurchase: true,
userPlan: 'Free',
// Timing
checkoutDuration: 45 // seconds
});
Implementation Patterns by Framework
React
Functional Component:
import LogRocket from 'logrocket';
function CheckoutButton({ cartTotal, itemCount }) {
const handleCheckout = () => {
LogRocket.track('Checkout Started', {
cartTotal,
itemCount,
timestamp: new Date().toISOString()
});
// Continue with checkout logic
proceedToCheckout();
};
return <button
}
Class Component:
import React, { Component } from 'react';
import LogRocket from 'logrocket';
class FeatureToggle extends Component {
handleToggle = (featureName, enabled) => {
LogRocket.track('Feature Toggled', {
featureName,
enabled,
source: 'settings-page',
userRole: this.props.user.role
});
this.props.onToggle(featureName, enabled);
};
render() {
return (
<Switch => this.handleToggle('darkMode', e.target.checked)}
/>
);
}
}
Vue
Composition API:
import { defineComponent } from 'vue';
import LogRocket from 'logrocket';
export default defineComponent({
setup() {
const completeOnboarding = () => {
LogRocket.track('Onboarding Completed', {
stepsCompleted: 5,
timeSpent: 180,
skippedSteps: []
});
// Continue with onboarding logic
};
return { completeOnboarding };
}
});
Options API:
export default {
methods: {
submitFeedback(rating, comment) {
LogRocket.track('Feedback Submitted', {
rating,
hasComment: !!comment,
feedbackLength: comment?.length || 0,
page: this.$route.path
});
this.sendFeedback({ rating, comment });
}
}
};
Angular
Component:
import { Component } from '@angular/core';
import LogRocket from 'logrocket';
@Component({
selector: 'app-subscription',
templateUrl: './subscription.component.html'
})
export class SubscriptionComponent {
upgradeSubscription(plan: string) {
LogRocket.track('Subscription Upgraded', {
oldPlan: this.currentPlan,
newPlan: plan,
priceDifference: this.calculatePriceDiff(plan)
});
this.subscriptionService.upgrade(plan);
}
}
Service:
import { Injectable } from '@angular/core';
import LogRocket from 'logrocket';
@Injectable({ providedIn: 'root' })
export class AnalyticsService {
trackEvent(eventName: string, properties: Record<string, any>) {
LogRocket.track(eventName, properties);
}
trackFeatureUsage(featureName: string) {
this.trackEvent('Feature Used', {
featureName,
timestamp: new Date().toISOString()
});
}
}
Common Event Tracking Patterns
Authentication Events
// Signup
LogRocket.track('Signup Completed', {
method: 'email', // email, google, github
referrer: document.referrer,
utmSource: getUTMSource(),
timestamp: new Date().toISOString()
});
// Login
LogRocket.track('Login Successful', {
method: 'email',
mfaEnabled: user.mfaEnabled,
lastLogin: user.lastLoginDate
});
// Logout
LogRocket.track('User Logged Out', {
sessionDuration: getSessionDuration(),
actionsPerformed: getActionCount()
});
Subscription/Billing Events
// Trial Started
LogRocket.track('Trial Started', {
planName: 'Professional',
trialDuration: 14,
source: 'pricing-page'
});
// Subscription Created
LogRocket.track('Subscription Created', {
planName: 'Professional',
billingCycle: 'annual',
amount: 199,
currency: 'USD',
paymentMethod: 'stripe'
});
// Subscription Upgraded
LogRocket.track('Subscription Upgraded', {
oldPlan: 'Basic',
newPlan: 'Professional',
priceDifference: 100
});
// Subscription Canceled
LogRocket.track('Subscription Canceled', {
planName: 'Professional',
cancellationReason: 'too-expensive',
monthsSubscribed: 6
});
Feature Usage Events
// Feature Enabled
LogRocket.track('Feature Enabled', {
featureName: 'API Access',
enabledFrom: 'settings',
userPlan: 'Enterprise',
requiresUpgrade: false
});
// Export Data
LogRocket.track('Data Exported', {
exportType: 'CSV',
recordCount: 1500,
exportDuration: 3.2, // seconds
dataType: 'customer-records'
});
// Integration Connected
LogRocket.track('Integration Connected', {
integrationType: 'Slack',
connectionMethod: 'OAuth',
permissionsGranted: ['read', 'write']
});
E-commerce Events
// Product Viewed
LogRocket.track('Product Viewed', {
productId: 'SKU-12345',
productName: 'Wireless Headphones',
price: 199.99,
category: 'Electronics',
inStock: true
});
// Added to Cart
LogRocket.track('Product Added to Cart', {
productId: 'SKU-12345',
quantity: 1,
price: 199.99,
cartTotal: 199.99,
cartItemCount: 1
});
// Checkout Started
LogRocket.track('Checkout Started', {
cartTotal: 399.98,
itemCount: 2,
shippingMethod: 'standard'
});
// Purchase Completed
LogRocket.track('Purchase Completed', {
orderId: 'ORD-789',
total: 446.98,
tax: 32.00,
shipping: 15.00,
itemCount: 2,
paymentMethod: 'credit_card',
firstPurchase: true
});
Error and Support Events
// Payment Failed
LogRocket.track('Payment Failed', {
errorCode: 'card_declined',
errorMessage: 'Your card was declined',
amount: 199,
paymentMethod: 'stripe',
attemptNumber: 2
});
// Support Ticket Submitted
LogRocket.track('Support Ticket Submitted', {
category: 'bug-report',
priority: 'high',
sessionURL: LogRocket.sessionURL, // Attach session URL
description: ticket.description.substring(0, 100) // First 100 chars
});
// Error Encountered
LogRocket.track('Error Displayed', {
errorType: 'validation',
errorMessage: 'Email address is invalid',
fieldName: 'email',
formName: 'signup'
});
Event Tracking Helpers
Create helper functions for consistent event tracking.
Event Tracking Utility:
// utils/analytics.js
import LogRocket from 'logrocket';
export const analytics = {
track(eventName, properties = {}) {
// Add default properties
const enrichedProperties = {
...properties,
timestamp: new Date().toISOString(),
page: window.location.pathname,
environment: process.env.NODE_ENV
};
LogRocket.track(eventName, enrichedProperties);
},
trackFeatureUsage(featureName) {
this.track('Feature Used', {
featureName,
userPlan: getCurrentUser().plan
});
},
trackError(errorType, errorMessage, context = {}) {
this.track('Error Encountered', {
errorType,
errorMessage,
...context
});
}
};
Usage:
import { analytics } from './utils/analytics';
// Simple tracking
analytics.track('Button Clicked', { buttonName: 'signup' });
// Feature usage
analytics.trackFeatureUsage('Advanced Reporting');
// Error tracking
analytics.trackError('validation', 'Invalid email address', {
field: 'email',
form: 'signup'
});
Combining with User Identification
Always identify users before tracking events for full context.
// After login
function handleLogin(user) {
// Identify user first
LogRocket.identify(user.id, {
email: user.email,
name: user.name,
plan: user.plan,
role: user.role
});
// Then track login event
LogRocket.track('Login Successful', {
method: 'email',
mfaEnabled: user.mfaEnabled
});
}
Testing and Validation
Browser Console Testing:
// Test event tracking
LogRocket.track('Test Event', {
testProperty: 'test value',
timestamp: new Date().toISOString()
});
// Verify session URL
console.log('Session URL:', LogRocket.sessionURL);
// Output: https://app.logrocket.com/your-app/sessions/abc123
// Visit session in LogRocket dashboard to see event in timeline
Automated Testing:
// Mock LogRocket in tests
jest.mock('logrocket', () => ({
track: jest.fn(),
identify: jest.fn(),
sessionURL: 'https://app.logrocket.com/test/sessions/test123'
}));
// Test event tracking
import LogRocket from 'logrocket';
test('tracks feature usage', () => {
const component = render(<FeatureToggle />);
fireEvent.click(component.getByRole('switch'));
expect(LogRocket.track).toHaveBeenCalledWith('Feature Toggled', {
featureName: 'Dark Mode',
enabled: true
});
});
Best Practices
Do:
- Track meaningful user actions, not every interaction
- Include context in event properties
- Use consistent naming conventions
- Identify users before tracking events
- Document event taxonomy for team reference
Don't:
- Track excessive events (affects performance and costs)
- Use generic event names ("click", "action")
- Include PII in event properties without sanitization
- Forget to test event tracking before deploying
- Track events without properties (lose valuable context)
Deployment Checklist
- Event tracking implemented for key user actions
- Event naming follows consistent conventions (Title Case, past tense)
- Properties include relevant context and use descriptive names
- User identification called before event tracking
- Events tested in LogRocket dashboard (visible in session timeline)
- Event taxonomy documented for team reference
- No PII or sensitive data in event properties
- Event tracking tested in non-production environment first
Additional Resources: