13 min read
Best Practices
Master pxlpeak implementation with proven best practices for tracking, analytics, and team workflows.
Introduction
Following best practices ensures you get accurate, actionable data from pxlpeak while maintaining clean, scalable tracking. This guide covers implementation patterns, naming conventions, data quality, and team workflows that leading analytics teams follow.
Tracking Implementation
Event Naming Conventions
Consistent naming makes data analysis easier and prevents duplicate events.
code
// Event naming structure
// Format: object_action or action_object (pick one, be consistent)
// RECOMMENDED: object_action format
const eventNamingConvention = {
structure: 'object_action',
case: 'snake_case',
examples: {
good: [
'page_viewed',
'button_clicked',
'form_submitted',
'user_signed_up',
'order_completed',
'product_added_to_cart',
'search_performed',
'video_played',
'download_started'
],
bad: [
'PageViewed', // Use snake_case
'click-button', // Inconsistent format
'Submit Form', // No spaces
'UserSignUp', // Use snake_case
'order complete', // No spaces, past tense
'productAddCart' // Use full words
]
}
};
// Event naming guidelines
const namingRules = {
1: 'Use snake_case for all events',
2: 'Use past tense for completed actions (form_submitted, not submit_form)',
3: 'Be specific but concise (order_completed, not user_completed_checkout_order)',
4: 'Avoid abbreviations unless universally understood',
5: 'Include object and action in every event name',
6: 'Use consistent vocabulary across your tracking plan'
};Property Standards
code
// Property naming and typing standards
interface PropertyStandards {
naming: {
case: 'snake_case';
prefixes: {
user: 'user_*'; // User properties
page: 'page_*'; // Page context
session: 'session_*'; // Session properties
product: 'product_*'; // E-commerce
content: 'content_*'; // Content properties
};
};
types: {
ids: 'string'; // Always strings for IDs
counts: 'integer'; // Whole numbers
amounts: 'number'; // Currency as number (not string)
booleans: 'boolean'; // True/false flags
timestamps: 'ISO 8601'; // Standard date format
lists: 'array'; // Arrays for multiple values
};
required: {
all_events: ['timestamp', 'event_id'];
page_events: ['page_path', 'page_title'];
conversion_events: ['conversion_type', 'value'];
ecommerce_events: ['product_id', 'product_name', 'currency'];
};
}
// Example implementation
pxlpeak.track('order_completed', {
// Order properties
order_id: 'ORD-12345', // String ID
order_total: 149.99, // Number, not string
order_currency: 'USD', // ISO currency code
order_item_count: 3, // Integer
order_discount_applied: true, // Boolean
// Product properties (array for multiple products)
products: [
{
product_id: 'SKU-001',
product_name: 'Premium Plan',
product_category: 'subscription',
product_price: 99.00,
product_quantity: 1
}
],
// User context
user_id: 'usr_abc123',
user_is_new: false,
user_lifetime_value: 599.99,
// Attribution context
utm_source: 'google',
utm_medium: 'cpc',
utm_campaign: 'brand_2026'
});Tracking Plan Documentation
code
// Tracking plan structure
interface TrackingPlanEntry {
event_name: string;
description: string;
trigger: string;
properties: {
name: string;
type: string;
required: boolean;
description: string;
example: any;
}[];
implementation_status: 'planned' | 'in_progress' | 'implemented' | 'verified';
owner: string;
last_updated: string;
}
// Example tracking plan entry
const trackingPlanExample: TrackingPlanEntry = {
event_name: 'checkout_started',
description: 'Fired when a user initiates the checkout process',
trigger: 'User clicks "Proceed to Checkout" button',
properties: [
{
name: 'cart_id',
type: 'string',
required: true,
description: 'Unique identifier for the cart',
example: 'cart_abc123'
},
{
name: 'cart_total',
type: 'number',
required: true,
description: 'Total cart value in account currency',
example: 149.99
},
{
name: 'cart_item_count',
type: 'integer',
required: true,
description: 'Number of items in cart',
example: 3
},
{
name: 'cart_coupon',
type: 'string',
required: false,
description: 'Applied coupon code if any',
example: 'SAVE20'
}
],
implementation_status: 'implemented',
owner: 'analytics-team',
last_updated: '2026-01-12'
};Data Quality
Validation & QA
code
// Data validation checklist
const dataQualityChecklist = {
pre_launch: [
'All events firing correctly in staging',
'Property values match expected types',
'Required properties always present',
'No PII in event properties',
'UTM parameters captured correctly',
'Cross-domain tracking working',
'Conversion values accurate',
'User identification correct'
],
post_launch: [
'Event volumes match expected patterns',
'No sudden drops in tracking',
'Conversion rates within expected range',
'No duplicate events',
'Property values look correct',
'Funnel progression makes sense'
],
ongoing: [
'Weekly data quality review',
'Monitor for tracking anomalies',
'Validate new feature implementations',
'Audit third-party integrations',
'Review bot and spam filtering'
]
};
// Automated validation rules
const validationRules = {
order_completed: {
required_properties: ['order_id', 'order_total', 'products'],
property_validations: {
order_total: {
type: 'number',
min: 0,
max: 100000
},
order_id: {
type: 'string',
pattern: /^ORD-[A-Z0-9]+$/
},
products: {
type: 'array',
minLength: 1
}
}
}
};
// QA testing approach
async function qaTrackingImplementation(testCases: TestCase[]) {
const results: TestResult[] = [];
for (const testCase of testCases) {
// Perform action
await performAction(testCase.action);
// Wait for event to fire
const event = await waitForEvent(testCase.expected_event, 5000);
// Validate event
const validation = validateEvent(event, testCase.expected_properties);
results.push({
testCase: testCase.name,
passed: validation.passed,
errors: validation.errors
});
}
return results;
}PII Protection
code
// PII handling best practices
const piiGuidelines = {
never_track: [
'Full names (use user_id instead)',
'Email addresses (hash if needed)',
'Phone numbers',
'Physical addresses',
'Credit card numbers',
'Social Security numbers',
'Passwords',
'Health information',
'Biometric data'
],
hash_if_needed: [
'Email (SHA256 for matching)',
'Phone (SHA256 for matching)'
],
acceptable: [
'User ID (opaque identifier)',
'Session ID',
'Device type',
'Browser',
'Country/Region (not precise location)',
'Company name (B2B)',
'Job title (B2B)'
]
};
// Safe user identification
function safeIdentify(user: UserData) {
pxlpeak.identify({
// Opaque user ID - GOOD
user_id: user.id,
// Hashed email for matching - OK if needed
email_hash: hashSHA256(user.email.toLowerCase()),
// Non-PII user attributes - GOOD
account_type: user.accountType,
plan_name: user.plan,
company_size: user.companySize,
industry: user.industry,
signup_date: user.signupDate,
// NEVER include:
// email: user.email, // BAD - PII
// name: user.fullName, // BAD - PII
// phone: user.phone, // BAD - PII
});
}Bot & Invalid Traffic Filtering
code
// Bot filtering configuration
const botFilteringConfig = {
// Automatic filtering
automatic: {
known_bots: true, // Filter known bot user agents
data_center_traffic: true, // Filter known data center IPs
suspicious_patterns: true // Filter rapid-fire requests
},
// Custom rules
custom_rules: [
{
name: 'internal_traffic',
condition: 'ip_range',
value: '192.168.1.0/24',
action: 'exclude'
},
{
name: 'qa_traffic',
condition: 'query_param',
value: 'qa_mode=true',
action: 'exclude'
},
{
name: 'staging_domain',
condition: 'hostname',
value: 'staging.example.com',
action: 'exclude'
}
],
// Traffic quality metrics
quality_indicators: {
bounce_rate_threshold: 95, // Flag if above
session_duration_min: 1, // Seconds
pages_per_session_min: 1
}
};
// Exclude internal traffic
if (typeof window !== 'undefined') {
// Check for internal user
const isInternal = document.cookie.includes('pxlpeak_internal=true');
const isQA = new URLSearchParams(window.location.search).has('qa_mode');
if (isInternal || isQA) {
pxlpeak.opt_out(); // Exclude from tracking
}
}User Identification
Identity Resolution
code
// Identity management best practices
interface IdentityStrategy {
anonymous_tracking: {
// Before user identifies
device_id: 'Auto-generated, stored in cookie';
session_id: 'Generated per session';
tracking_enabled: true;
};
identified_user: {
// After user signs up/logs in
user_id: 'Your system user ID';
merge_anonymous: true;
persist_identity: true;
};
cross_device: {
// For logged-in users across devices
user_id_required: true;
merge_sessions: true;
};
}
// Proper identification flow
function handleUserIdentification() {
// On signup/login
function onUserAuthenticated(user: User) {
// Identify the user
pxlpeak.identify({
user_id: user.id,
traits: {
plan: user.plan,
signup_date: user.createdAt,
company_id: user.companyId
}
});
// Merge anonymous activity with identified user
pxlpeak.alias({
previous_id: pxlpeak.getAnonymousId(),
user_id: user.id
});
}
// On logout
function onUserLogout() {
// Reset identity for privacy
pxlpeak.reset();
}
// On page load for logged-in user
function onPageLoad() {
const user = getCurrentUser();
if (user) {
// Re-identify on each page for consistency
pxlpeak.identify({
user_id: user.id
});
}
}
}Group/Account Tracking (B2B)
code
// B2B account tracking
function trackB2BAccount(account: Account) {
// Associate user with account
pxlpeak.group('company', account.id, {
name: account.name,
industry: account.industry,
employee_count: account.employeeCount,
plan: account.plan,
mrr: account.mrr,
signup_date: account.createdAt,
account_owner: account.ownerId
});
}
// Track account-level events
pxlpeak.track('feature_enabled', {
feature_name: 'sso',
enabled_by: currentUser.id,
// Account context is automatically attached
});
// Query account-level metrics
const accountMetrics = await pxlpeak.analytics.query({
groupBy: ['company.id', 'company.plan'],
metrics: ['users', 'events', 'conversions'],
dateRange: { last: '30d' }
});Event Design
Funnel Event Structure
code
// Design events to enable funnel analysis
const funnelEventDesign = {
// Registration funnel
registration_funnel: [
{
event: 'signup_page_viewed',
stage: 1,
properties: ['referrer', 'utm_params']
},
{
event: 'signup_form_started',
stage: 2,
properties: ['form_type']
},
{
event: 'signup_form_submitted',
stage: 3,
properties: ['form_type', 'signup_method']
},
{
event: 'email_verified',
stage: 4,
properties: ['verification_method']
},
{
event: 'onboarding_started',
stage: 5,
properties: ['onboarding_variant']
},
{
event: 'onboarding_completed',
stage: 6,
properties: ['steps_completed', 'time_to_complete']
}
],
// Purchase funnel
purchase_funnel: [
{
event: 'product_viewed',
stage: 1,
properties: ['product_id', 'product_name', 'product_category', 'price']
},
{
event: 'product_added_to_cart',
stage: 2,
properties: ['product_id', 'quantity', 'cart_total']
},
{
event: 'checkout_started',
stage: 3,
properties: ['cart_id', 'cart_total', 'item_count']
},
{
event: 'payment_info_entered',
stage: 4,
properties: ['payment_method']
},
{
event: 'order_completed',
stage: 5,
properties: ['order_id', 'order_total', 'products']
}
]
};
// Include funnel context in events
pxlpeak.track('checkout_started', {
// Funnel context
funnel_name: 'purchase',
funnel_step: 3,
funnel_session_id: getCurrentFunnelSession(),
// Event-specific properties
cart_id: cart.id,
cart_total: cart.total,
item_count: cart.items.length
});Experiment Tracking
code
// A/B test tracking
interface ExperimentTracking {
experiment_id: string;
experiment_name: string;
variant_id: string;
variant_name: string;
}
// Track experiment exposure
function trackExperimentExposure(experiment: Experiment) {
pxlpeak.track('experiment_viewed', {
experiment_id: experiment.id,
experiment_name: experiment.name,
variant_id: experiment.variantId,
variant_name: experiment.variantName
});
// Also set as user property for segmentation
pxlpeak.identify({
traits: {
[`experiment_${experiment.id}`]: experiment.variantName
}
});
}
// Include experiment context in conversion events
pxlpeak.track('signup_completed', {
// Conversion properties
signup_method: 'email',
// Experiment context
experiments: [
{
experiment_id: 'signup_flow_v2',
variant: 'simplified'
},
{
experiment_id: 'pricing_test',
variant: 'annual_first'
}
]
});Performance Optimization
Efficient Tracking
code
// Performance best practices
const trackingPerformance = {
// Batch events when possible
batching: {
enabled: true,
maxBatchSize: 10,
flushInterval: 5000 // ms
},
// Defer non-critical tracking
defer_tracking: {
critical: ['page_view', 'signup', 'purchase'],
deferrable: ['scroll_depth', 'time_on_page', 'video_progress']
},
// Use sendBeacon for reliability
use_beacon: true,
// Compression for large payloads
compression: true
};
// Defer non-critical events
function trackScrollDepth(depth: number) {
// Use requestIdleCallback for non-critical tracking
if ('requestIdleCallback' in window) {
requestIdleCallback(() => {
pxlpeak.track('scroll_depth_reached', { depth });
});
} else {
setTimeout(() => {
pxlpeak.track('scroll_depth_reached', { depth });
}, 0);
}
}
// Throttle high-frequency events
const throttledTrack = throttle((event: string, props: object) => {
pxlpeak.track(event, props);
}, 1000);
window.addEventListener('scroll', () => {
throttledTrack('page_scrolled', {
scroll_position: window.scrollY
});
});Script Loading
code
// Optimal script loading
const scriptLoadingBestPractices = {
// Load asynchronously
async_loading: true,
// Placement
placement: 'head_or_before_body_close',
// Preconnect for faster loading
preconnect: [
'https://api.pxlpeak.com',
'https://cdn.pxlpeak.com'
]
};
// HTML implementation
const htmlSnippet = `
<!-- Preconnect to pxlpeak -->
<link rel="preconnect" href="https://api.pxlpeak.com">
<link rel="dns-prefetch" href="https://api.pxlpeak.com">
<!-- Load pxlpeak asynchronously -->
<script async src="https://cdn.pxlpeak.com/v1/pxlpeak.min.js"></script>
<script>
window.pxlpeak = window.pxlpeak || [];
window.pxlpeak.push(['init', 'YOUR_SITE_ID']);
</script>
`;Team Workflows
Governance Model
code
// Analytics governance structure
const governanceModel = {
roles: {
analytics_owner: {
responsibilities: [
'Overall tracking strategy',
'Approve tracking plan changes',
'Data quality oversight',
'Tool administration'
]
},
implementation_lead: {
responsibilities: [
'Technical implementation',
'Code review for tracking',
'QA process management',
'Developer enablement'
]
},
stakeholder: {
responsibilities: [
'Request new tracking',
'Define business requirements',
'Validate data quality',
'Use data for decisions'
]
}
},
processes: {
new_tracking_request: {
steps: [
'1. Stakeholder submits request',
'2. Analytics owner reviews',
'3. Implementation lead specs',
'4. Developer implements',
'5. QA validates',
'6. Analytics owner approves',
'7. Deploy to production'
]
},
tracking_plan_update: {
frequency: 'Monthly review',
participants: ['Analytics owner', 'Implementation lead', 'Key stakeholders']
}
}
};Change Management
code
// Tracking change process
interface TrackingChangeRequest {
id: string;
type: 'new_event' | 'modify_event' | 'deprecate_event' | 'new_property';
title: string;
description: string;
business_justification: string;
requestor: string;
priority: 'high' | 'medium' | 'low';
status: 'pending' | 'approved' | 'in_progress' | 'completed' | 'rejected';
implementation_notes?: string;
affected_reports?: string[];
}
// Version control for tracking
const trackingVersioning = {
// Semantic versioning for tracking plan
current_version: '2.3.0',
// Changelog
changes: [
{
version: '2.3.0',
date: '2026-01-12',
changes: [
'Added: experiment_viewed event',
'Modified: order_completed now includes discount_amount',
'Deprecated: legacy_signup event (use signup_completed)'
]
}
],
// Deprecation policy
deprecation: {
notice_period: '90 days',
migration_guide: true,
backward_compatibility: true
}
};Documentation
code
// Documentation requirements
const documentationStandards = {
tracking_plan: {
required_fields: [
'Event name',
'Description',
'Trigger',
'Properties with types',
'Example payload',
'Owner',
'Last updated'
],
format: 'Google Sheets or Notion',
update_frequency: 'On every change'
},
implementation_docs: {
required: [
'Setup instructions',
'Code examples',
'Testing procedures',
'Troubleshooting guide'
]
},
reporting_docs: {
required: [
'Report purpose',
'Data sources',
'Calculation methodology',
'Refresh frequency',
'Owner'
]
}
};Reporting Best Practices
Dashboard Design
code
// Dashboard design principles
const dashboardPrinciples = {
hierarchy: {
executive: {
metrics: ['Revenue', 'Conversions', 'Active Users'],
granularity: 'Weekly/Monthly',
visualizations: 'KPI cards, trend lines'
},
operational: {
metrics: ['Detailed funnel metrics', 'Feature usage', 'Engagement'],
granularity: 'Daily/Hourly',
visualizations: 'Tables, detailed charts'
},
exploratory: {
metrics: 'Ad-hoc analysis',
granularity: 'Flexible',
visualizations: 'Interactive'
}
},
design_rules: [
'Start with the question you\'re trying to answer',
'Show trends, not just point-in-time numbers',
'Include context (benchmarks, targets, comparisons)',
'Limit to 5-7 key metrics per view',
'Use consistent color coding',
'Include data freshness indicator'
]
};Alert Configuration
code
// Smart alerting configuration
const alertingBestPractices = {
alert_types: {
anomaly: {
description: 'Automatic detection of unusual patterns',
threshold: 'Statistical (2+ standard deviations)',
use_case: 'Unexpected drops or spikes'
},
threshold: {
description: 'Fixed value triggers',
threshold: 'Manual configuration',
use_case: 'Known important thresholds'
},
trend: {
description: 'Direction over time',
threshold: 'Percent change over period',
use_case: 'Gradual degradation'
}
},
configuration_tips: [
'Start with fewer alerts, add as needed',
'Set appropriate severity levels',
'Route to the right team/person',
'Include context in alert message',
'Define clear escalation paths',
'Review and tune regularly'
],
example_alerts: [
{
name: 'Conversion rate drop',
condition: 'conversion_rate < 7d_average * 0.8',
severity: 'high',
notification: 'Slack + Email'
},
{
name: 'Tracking outage',
condition: 'event_count < 1 for 1 hour',
severity: 'critical',
notification: 'PagerDuty'
}
]
};Checklist Summary
Implementation Checklist
code
## pxlpeak Implementation Checklist
### Before Launch
- [ ] Tracking plan documented and approved
- [ ] Events follow naming conventions
- [ ] Properties typed correctly
- [ ] No PII in tracking
- [ ] QA testing completed
- [ ] Bot filtering configured
- [ ] Internal traffic excluded
### Go Live
- [ ] Script loaded asynchronously
- [ ] All critical events firing
- [ ] Conversions tracking correctly
- [ ] User identification working
- [ ] Attribution capturing correctly
### Post Launch
- [ ] Data quality monitoring active
- [ ] Alerts configured
- [ ] Team trained on dashboards
- [ ] Documentation complete
- [ ] Review schedule establishedNext Steps
- Create Your Tracking Plan - Document all events before implementing
- Set Up QA Process - Validate tracking before every release
- Establish Governance - Define roles and change processes
- Build Core Dashboards - Start with essential metrics
- Train Your Team - Ensure everyone knows how to use the data
Related Guides: