Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:32:40 +08:00
commit 0ea8352871
72 changed files with 30043 additions and 0 deletions

View File

@@ -0,0 +1,168 @@
---
name: ga4-events-fundamentals
description: Comprehensive guide to GA4 event architecture including automatically collected events, enhanced measurement, recommended events, and custom events. Use when understanding GA4 event structure, implementing event tracking, configuring event parameters, working with event scopes (event/user/item), or troubleshooting event collection. Covers event naming conventions, parameter limits (25 parameters, 40 char names), and the four event categories.
---
# GA4 Events Fundamentals
## Overview
Google Analytics 4 uses an event-based architecture where every user interaction is tracked as an event. Understanding GA4's event structure, parameter system, and scoping model is fundamental to successful implementation. This skill provides comprehensive guidance on the four event categories, parameter configuration, and best practices for event tracking.
## When to Use This Skill
Invoke this skill when:
- Learning GA4 event-based architecture fundamentals
- Understanding differences between event types (automatic, enhanced, recommended, custom)
- Implementing event tracking on websites or applications
- Configuring event parameters and understanding parameter limits
- Working with event scopes (event-scoped, user-scoped, item-scoped)
- Troubleshooting why events aren't firing correctly
- Analyzing event parameters in DebugView
- Planning event taxonomy and naming conventions
- Understanding parameter constraints (25 per event, 40 char names)
- Configuring enhanced measurement settings
## Core Capabilities
### Four Event Categories
**1. Automatically Collected Events**
Events that fire without additional configuration once GA4 is installed.
Core automatic events:
- `session_start` - User session begins
- `first_visit` - User's first visit to site
- `user_engagement` - Page in focus for 1+ second
- `page_view` - Page loads (when enhanced measurement enabled)
**2. Enhanced Measurement Events**
Automatically tracked interactions that can be toggled on/off in GA4 settings.
Configurable enhanced measurement events:
- `scroll` - User scrolls to 90% page depth
- `click` - Outbound link clicks
- `file_download` - Downloads of common file types
- `video_start`, `video_progress`, `video_complete` - YouTube video engagement
- `view_search_results` - Site search performed
- `form_start`, `form_submit` - Form interactions
**3. Recommended Events**
Google-defined event names with standardized parameters for consistency.
Key recommended events:
- `login` / `sign_up` - User authentication
- `purchase` - Ecommerce transaction (most critical)
- `add_to_cart` / `remove_from_cart` - Shopping cart actions
- `begin_checkout` - Checkout initiated
- `view_item` / `view_item_list` - Product views
- `search` - Site search
- `generate_lead` - Lead generation
**4. Custom Events**
Business-specific events created for unique tracking needs.
Examples:
- `video_tutorial_watched`
- `whitepaper_downloaded`
- `demo_requested`
- `pricing_calculator_used`
### Event Structure
Every GA4 event consists of:
- **Event name** (required) - Max 40 characters, snake_case
- **Event parameters** (optional) - Up to 25 parameters per event
- **Event timestamp** (automatic)
- **User information** (automatic)
### Parameter Scopes
**Event Scope**
Applies to single event occurrence. Use for event-specific data.
Example: button_name, form_id, video_title
**User Scope**
Applies to all events from that user. Use for user attributes.
Example: subscription_tier, customer_segment, loyalty_level
**Item Scope**
Applies to products in ecommerce events. Use for product data.
Example: item_color, item_size, supplier_name
### Event and Parameter Limits
Critical constraints:
- Maximum 500 distinct event names per property
- Maximum 25 parameters per event
- Event names: 40 character limit
- Parameter names: 40 character limit
- Parameter values: 100 character limit (exceptions: page_title 300, page_referrer 420, page_location 1000)
- Event-scoped custom dimensions: 50 per property (standard)
- User-scoped custom dimensions: 25 per property (standard)
- Item-scoped custom dimensions: 10 per property (standard)
## Event Naming Conventions
**Best Practices:**
- Use snake_case (lowercase with underscores)
- Be descriptive and action-oriented
- Start with verb when possible
- Keep under 40 characters
- Avoid generic names
**Pattern:**
```
[action]_[object]_[context]
Examples:
- video_tutorial_started
- whitepaper_downloaded
- demo_request_submitted
- pricing_calculator_used
```
**Avoid:**
- event1, event2, data, click (too generic)
- MyCustomEvent, customEvent (wrong case)
- very_long_descriptive_event_name_that_exceeds_limits (too long)
## Quick Reference
### Common Event Parameters
```
value - Monetary value
currency - ISO currency code (USD, EUR, GBP)
transaction_id - Unique transaction identifier
items - Array of product objects (ecommerce)
method - Login/signup method
search_term - User search query
```
### Accessing Event Data
- **DebugView:** Admin → DebugView (real-time event stream)
- **Realtime Reports:** Reports → Realtime (last 30 minutes)
- **Standard Reports:** Reports → Engagement → Events (24hr+ delay)
## Integration with Other Skills
- **ga4-setup** - Foundation prerequisite for GA4 installation
- **ga4-recommended-events** - Implementing specific recommended events with proper parameters
- **ga4-custom-events** - Creating custom events beyond fundamentals
- **ga4-custom-dimensions** - Registering event parameters as custom dimensions
- **ga4-gtag-implementation** - Implementing events via gtag.js
- **ga4-gtm-integration** - Implementing events via Google Tag Manager
- **ga4-debugview** - Verifying event firing and parameters
## References
Detailed documentation in references directory:
- **references/event-types-complete.md** - Comprehensive guide to all four event categories with examples
- **references/event-parameters-guide.md** - Complete event parameter reference and usage patterns
- **references/parameter-scopes.md** - Deep dive into event, user, and item scopes
- **references/event-naming-conventions.md** - Best practices and naming patterns with examples
Code examples available in assets directory:
- **assets/event-structure-examples.js** - Ready-to-use event implementation examples for all event types

View File

@@ -0,0 +1,806 @@
/**
* GA4 Event Structure Examples
*
* Comprehensive code examples for all four event categories:
* 1. Automatically Collected Events
* 2. Enhanced Measurement Events
* 3. Recommended Events
* 4. Custom Events
*
* Note: These examples assume gtag.js is already installed on the page.
*/
// ============================================================================
// CATEGORY 1: AUTOMATICALLY COLLECTED EVENTS
// ============================================================================
// These fire automatically when GA4 is installed - no code needed
// Listed here for reference only
/*
Automatic Events (No implementation needed):
- session_start
- first_visit
- user_engagement
- page_view (when enhanced measurement enabled)
*/
// ============================================================================
// CATEGORY 2: ENHANCED MEASUREMENT EVENTS
// ============================================================================
// These are configured in GA4 Admin (Data Streams → Enhanced measurement)
// Toggle on/off for automatic collection
/*
Enhanced Measurement Events (Configured in GA4 Admin):
- page_view
- scroll
- click (outbound links)
- file_download
- video_start, video_progress, video_complete
- view_search_results
- form_start, form_submit
Enable in: Admin → Data Streams → Web Stream → Enhanced measurement (gear icon)
*/
// ============================================================================
// CATEGORY 3: RECOMMENDED EVENTS
// ============================================================================
// ----------------------------------------------------------------------------
// Engagement Events
// ----------------------------------------------------------------------------
// Login Event
gtag('event', 'login', {
'method': 'google' // or 'email', 'facebook', 'phone'
});
// Sign Up Event
gtag('event', 'sign_up', {
'method': 'email' // or 'google', 'facebook'
});
// Search Event
gtag('event', 'search', {
'search_term': 'blue widgets'
});
// Select Content
gtag('event', 'select_content', {
'content_type': 'article',
'item_id': 'A123'
});
// Share Event
gtag('event', 'share', {
'method': 'twitter',
'content_type': 'article',
'item_id': 'A123'
});
// ----------------------------------------------------------------------------
// Ecommerce Recommended Events
// ----------------------------------------------------------------------------
// View Item (Product Page)
gtag('event', 'view_item', {
'items': [
{
'item_id': 'SKU_12345',
'item_name': 'Stan and Friends Tee',
'affiliation': 'Google Merchandise Store',
'coupon': 'SUMMER_FUN',
'discount': 2.22,
'index': 0,
'item_brand': 'Google',
'item_category': 'Apparel',
'item_category2': 'Adult',
'item_category3': 'Shirts',
'item_category4': 'Crew',
'item_category5': 'Short sleeve',
'item_list_id': 'related_products',
'item_list_name': 'Related Products',
'item_variant': 'green',
'location_id': 'ChIJIQBpAG2ahYAR_6128GcTUEo',
'price': 10.01,
'quantity': 3
}
],
'currency': 'USD',
'value': 30.03
});
// View Item List (Product Listing Page)
gtag('event', 'view_item_list', {
'item_list_id': 'related_products',
'item_list_name': 'Related products',
'items': [
{
'item_id': 'SKU_12345',
'item_name': 'Stan and Friends Tee',
'affiliation': 'Google Merchandise Store',
'coupon': 'SUMMER_FUN',
'discount': 2.22,
'index': 0,
'item_brand': 'Google',
'item_category': 'Apparel',
'item_list_id': 'related_products',
'item_list_name': 'Related Products',
'item_variant': 'green',
'location_id': 'ChIJIQBpAG2ahYAR_6128GcTUEo',
'price': 10.01,
'quantity': 3
}
]
});
// Select Item (Item Clicked from List)
gtag('event', 'select_item', {
'item_list_id': 'related_products',
'item_list_name': 'Related products',
'items': [
{
'item_id': 'SKU_12345',
'item_name': 'Stan and Friends Tee',
'item_brand': 'Google',
'item_category': 'Apparel',
'item_variant': 'green',
'price': 10.01,
'index': 0
}
]
});
// Add to Wishlist
gtag('event', 'add_to_wishlist', {
'currency': 'USD',
'value': 30.03,
'items': [
{
'item_id': 'SKU_12345',
'item_name': 'Stan and Friends Tee',
'item_brand': 'Google',
'item_category': 'Apparel',
'item_variant': 'green',
'price': 10.01,
'quantity': 3
}
]
});
// Add to Cart
gtag('event', 'add_to_cart', {
'currency': 'USD',
'value': 30.03,
'items': [
{
'item_id': 'SKU_12345',
'item_name': 'Stan and Friends Tee',
'item_brand': 'Google',
'item_category': 'Apparel',
'item_variant': 'green',
'price': 10.01,
'quantity': 3
}
]
});
// Remove from Cart
gtag('event', 'remove_from_cart', {
'currency': 'USD',
'value': 10.01,
'items': [
{
'item_id': 'SKU_12345',
'item_name': 'Stan and Friends Tee',
'item_brand': 'Google',
'item_category': 'Apparel',
'item_variant': 'green',
'price': 10.01,
'quantity': 1
}
]
});
// View Cart
gtag('event', 'view_cart', {
'currency': 'USD',
'value': 30.03,
'items': [
{
'item_id': 'SKU_12345',
'item_name': 'Stan and Friends Tee',
'item_brand': 'Google',
'item_category': 'Apparel',
'item_variant': 'green',
'price': 10.01,
'quantity': 3
}
]
});
// Begin Checkout
gtag('event', 'begin_checkout', {
'currency': 'USD',
'value': 30.03,
'coupon': 'SUMMER_FUN',
'items': [
{
'item_id': 'SKU_12345',
'item_name': 'Stan and Friends Tee',
'item_brand': 'Google',
'item_category': 'Apparel',
'item_variant': 'green',
'price': 10.01,
'quantity': 3
}
]
});
// Add Shipping Info
gtag('event', 'add_shipping_info', {
'currency': 'USD',
'value': 30.03,
'coupon': 'SUMMER_FUN',
'shipping_tier': 'Ground',
'items': [
{
'item_id': 'SKU_12345',
'item_name': 'Stan and Friends Tee',
'item_brand': 'Google',
'item_category': 'Apparel',
'item_variant': 'green',
'price': 10.01,
'quantity': 3
}
]
});
// Add Payment Info
gtag('event', 'add_payment_info', {
'currency': 'USD',
'value': 30.03,
'coupon': 'SUMMER_FUN',
'payment_type': 'Credit Card',
'items': [
{
'item_id': 'SKU_12345',
'item_name': 'Stan and Friends Tee',
'item_brand': 'Google',
'item_category': 'Apparel',
'item_variant': 'green',
'price': 10.01,
'quantity': 3
}
]
});
// Purchase (MOST IMPORTANT)
gtag('event', 'purchase', {
'transaction_id': 'T_12345',
'affiliation': 'Google Merchandise Store',
'value': 142.52,
'tax': 10.00,
'shipping': 5.00,
'currency': 'USD',
'coupon': 'SUMMER_SALE',
'items': [
{
'item_id': 'SKU_12345',
'item_name': 'Stan and Friends Tee',
'affiliation': 'Google Merchandise Store',
'coupon': 'SUMMER_FUN',
'discount': 2.22,
'index': 0,
'item_brand': 'Google',
'item_category': 'Apparel',
'item_category2': 'Adult',
'item_category3': 'Shirts',
'item_category4': 'Crew',
'item_category5': 'Short sleeve',
'item_list_id': 'related_products',
'item_list_name': 'Related Products',
'item_variant': 'green',
'location_id': 'ChIJIQBpAG2ahYAR_6128GcTUEo',
'price': 10.01,
'quantity': 3
},
{
'item_id': 'SKU_12346',
'item_name': 'Google Grey Women\'s Tee',
'affiliation': 'Google Merchandise Store',
'coupon': 'SUMMER_FUN',
'discount': 3.33,
'index': 1,
'item_brand': 'Google',
'item_category': 'Apparel',
'item_category2': 'Adult',
'item_category3': 'Shirts',
'item_category4': 'Crew',
'item_category5': 'Short sleeve',
'item_list_id': 'related_products',
'item_list_name': 'Related Products',
'item_variant': 'gray',
'location_id': 'ChIJIQBpAG2ahYAR_6128GcTUEo',
'price': 20.99,
'quantity': 2
}
]
});
// Refund
gtag('event', 'refund', {
'transaction_id': 'T_12345',
'value': 30.03,
'tax': 4.90,
'shipping': 5.99,
'currency': 'USD',
'items': [
{
'item_id': 'SKU_12345',
'item_name': 'Stan and Friends Tee',
'affiliation': 'Google Merchandise Store',
'coupon': 'SUMMER_FUN',
'discount': 2.22,
'index': 0,
'item_brand': 'Google',
'item_category': 'Apparel',
'item_variant': 'green',
'price': 10.01,
'quantity': 3
}
]
});
// ----------------------------------------------------------------------------
// Promotion Events
// ----------------------------------------------------------------------------
// View Promotion
gtag('event', 'view_promotion', {
'creative_name': 'Summer Banner',
'creative_slot': 'featured_app_1',
'promotion_id': 'P_12345',
'promotion_name': 'Summer Sale',
'items': [
{
'item_id': 'SKU_12345',
'item_name': 'Stan and Friends Tee',
'affiliation': 'Google Merchandise Store',
'coupon': 'SUMMER_FUN',
'discount': 2.22,
'index': 0,
'item_brand': 'Google',
'item_category': 'Apparel',
'item_variant': 'green',
'price': 10.01,
'quantity': 3
}
]
});
// Select Promotion
gtag('event', 'select_promotion', {
'creative_name': 'Summer Banner',
'creative_slot': 'featured_app_1',
'promotion_id': 'P_12345',
'promotion_name': 'Summer Sale',
'items': [
{
'item_id': 'SKU_12345',
'item_name': 'Stan and Friends Tee',
'affiliation': 'Google Merchandise Store',
'coupon': 'SUMMER_FUN',
'discount': 2.22,
'index': 0,
'item_brand': 'Google',
'item_category': 'Apparel',
'item_variant': 'green',
'price': 10.01,
'quantity': 3
}
]
});
// ----------------------------------------------------------------------------
// Other Recommended Events
// ----------------------------------------------------------------------------
// Generate Lead
gtag('event', 'generate_lead', {
'value': 99.99,
'currency': 'USD'
});
// ============================================================================
// CATEGORY 4: CUSTOM EVENTS
// ============================================================================
// ----------------------------------------------------------------------------
// SaaS / Software Examples
// ----------------------------------------------------------------------------
// Feature Activation
gtag('event', 'feature_activated', {
'feature_name': 'advanced_analytics',
'feature_tier': 'enterprise',
'activation_source': 'settings_page',
'first_time_use': true
});
// Product Tour Completion
gtag('event', 'product_tour_completed', {
'tour_name': 'onboarding_v2',
'tour_version': '2.1',
'completion_time_seconds': 180,
'steps_completed': 7,
'steps_skipped': 2
});
// Trial Signup
gtag('event', 'trial_started', {
'plan_type': 'professional',
'trial_duration_days': 14,
'source': 'landing_page',
'variation': 'b'
});
// Account Upgrade
gtag('event', 'account_upgraded', {
'previous_tier': 'basic',
'new_tier': 'premium',
'upgrade_value': 99.99,
'currency': 'USD',
'billing_frequency': 'monthly'
});
// ----------------------------------------------------------------------------
// E-Learning Examples
// ----------------------------------------------------------------------------
// Course Enrollment
gtag('event', 'course_enrollment', {
'course_id': 'GA4_101',
'course_name': 'GA4 Fundamentals',
'instructor': 'John Doe',
'price': 99.99,
'currency': 'USD',
'level': 'beginner',
'enrollment_method': 'direct'
});
// Lesson Completion
gtag('event', 'lesson_completed', {
'course_id': 'GA4_101',
'lesson_id': 'lesson_3',
'lesson_title': 'Event Tracking Basics',
'time_spent_minutes': 15,
'quiz_score': 85,
'attempts': 1
});
// Certificate Earned
gtag('event', 'certificate_earned', {
'course_id': 'GA4_101',
'course_name': 'GA4 Fundamentals',
'completion_date': '2025-11-10',
'final_score': 92,
'certificate_id': 'CERT_12345'
});
// ----------------------------------------------------------------------------
// Media / Publishing Examples
// ----------------------------------------------------------------------------
// Article Read Complete
gtag('event', 'article_read_complete', {
'article_id': 'A123',
'article_title': 'Complete GA4 Guide',
'category': 'analytics',
'author': 'Jane Smith',
'word_count': 2500,
'time_to_read_minutes': 10,
'scroll_depth_percent': 100
});
// Content Shared
gtag('event', 'content_shared', {
'content_type': 'article',
'content_id': 'A123',
'content_title': 'Complete GA4 Guide',
'share_method': 'twitter',
'share_location': 'article_footer'
});
// Newsletter Subscription
gtag('event', 'newsletter_subscribed', {
'newsletter_type': 'weekly',
'subscription_source': 'article_inline',
'article_id': 'A123',
'email_domain': 'gmail.com'
});
// ----------------------------------------------------------------------------
// E-Commerce Examples (Custom Beyond Recommended)
// ----------------------------------------------------------------------------
// Product Comparison
gtag('event', 'product_comparison_viewed', {
'comparison_type': 'feature_matrix',
'products_compared': 3,
'product_ids': 'SKU_123,SKU_124,SKU_125',
'category': 'electronics'
});
// Wishlist Shared
gtag('event', 'wishlist_shared', {
'wishlist_id': 'WL_123',
'item_count': 5,
'share_method': 'email',
'total_value': 499.95,
'currency': 'USD'
});
// Size Chart Viewed
gtag('event', 'size_chart_viewed', {
'product_id': 'SKU_123',
'product_name': 'Blue T-Shirt',
'category': 'apparel',
'view_location': 'product_page'
});
// ----------------------------------------------------------------------------
// Video Tracking Examples (Custom)
// ----------------------------------------------------------------------------
// Video Tutorial Watched
gtag('event', 'video_tutorial_watched', {
'video_id': 'VID_123',
'video_title': 'GA4 Event Tracking',
'video_duration': 1200,
'completion_percent': 100,
'difficulty_level': 'beginner',
'category': 'analytics',
'language': 'en',
'watch_time_seconds': 1180
});
// Video Quality Changed
gtag('event', 'video_quality_changed', {
'video_id': 'VID_123',
'previous_quality': 'sd',
'new_quality': 'hd',
'auto_switched': false,
'playback_time_seconds': 120
});
// ----------------------------------------------------------------------------
// Form Tracking Examples (Custom)
// ----------------------------------------------------------------------------
// Multi-Step Form Progress
gtag('event', 'form_step_completed', {
'form_id': 'registration_form',
'form_name': 'Account Registration',
'step_number': 2,
'step_name': 'contact_information',
'total_steps': 4,
'time_on_step_seconds': 45
});
// Form Field Interaction
gtag('event', 'form_field_focused', {
'form_id': 'contact_form',
'field_name': 'email',
'field_type': 'email',
'field_required': true,
'field_position': 2
});
// Form Validation Error
gtag('event', 'form_validation_error', {
'form_id': 'contact_form',
'error_field': 'email',
'error_type': 'invalid_format',
'error_message': 'Please enter a valid email address'
});
// ----------------------------------------------------------------------------
// Calculator / Tool Examples
// ----------------------------------------------------------------------------
// Calculator Used
gtag('event', 'calculator_used', {
'calculator_type': 'roi',
'calculator_name': 'ROI Calculator',
'inputs_entered': 5,
'calculation_performed': true,
'result_value': 15000
});
// Pricing Calculator
gtag('event', 'pricing_calculator_used', {
'plan_selected': 'enterprise',
'users_count': 50,
'billing_frequency': 'annual',
'calculated_price': 4999.99,
'currency': 'USD'
});
// ----------------------------------------------------------------------------
// Error Tracking Examples
// ----------------------------------------------------------------------------
// Error Encountered
gtag('event', 'error_encountered', {
'error_type': 'api_error',
'error_code': '500',
'error_message': 'Internal Server Error',
'error_page': '/checkout',
'user_action': 'submit_payment'
});
// Payment Failed
gtag('event', 'payment_failed', {
'payment_method': 'credit_card',
'failure_reason': 'insufficient_funds',
'transaction_value': 99.99,
'currency': 'USD',
'retry_available': true
});
// ============================================================================
// ADVANCED PATTERNS
// ============================================================================
// ----------------------------------------------------------------------------
// Dynamic Parameter Population
// ----------------------------------------------------------------------------
// Get product data from page
function trackProductView() {
const productId = document.querySelector('[data-product-id]').textContent;
const productName = document.querySelector('.product-title').textContent;
const productPrice = parseFloat(document.querySelector('.product-price').textContent);
gtag('event', 'view_item', {
'items': [{
'item_id': productId,
'item_name': productName,
'price': productPrice,
'item_category': 'Electronics',
'quantity': 1
}],
'value': productPrice,
'currency': 'USD'
});
}
// ----------------------------------------------------------------------------
// Event with Conditional Parameters
// ----------------------------------------------------------------------------
function trackCheckout(userTier, couponCode) {
const eventParams = {
'items': getCartItems(),
'value': getCartTotal(),
'currency': 'USD'
};
// Add optional parameters if they exist
if (userTier) {
eventParams.user_tier = userTier;
}
if (couponCode) {
eventParams.coupon = couponCode;
}
gtag('event', 'begin_checkout', eventParams);
}
// ----------------------------------------------------------------------------
// Event with Calculated Parameters
// ----------------------------------------------------------------------------
function trackVideoComplete(videoElement) {
const duration = videoElement.duration;
const watchedTime = videoElement.currentTime;
const completionPercent = Math.round((watchedTime / duration) * 100);
gtag('event', 'video_complete', {
'video_id': videoElement.id,
'video_duration': Math.round(duration),
'watch_time_seconds': Math.round(watchedTime),
'completion_percent': completionPercent,
'engagement_rate': completionPercent
});
}
// ----------------------------------------------------------------------------
// User Property Setting
// ----------------------------------------------------------------------------
// Set user properties (user-scoped)
function setUserProperties(userId, userTier, accountAge) {
gtag('set', {
'user_id': userId,
'subscription_tier': userTier,
'account_age_days': accountAge,
'account_status': 'active'
});
}
// Clear user properties on logout
function clearUserProperties() {
gtag('set', {
'user_id': null // MUST be null, not empty string
});
}
// ----------------------------------------------------------------------------
// Event Callback (for SPAs)
// ----------------------------------------------------------------------------
function trackFormSubmitAndNavigate(destination) {
gtag('event', 'form_submit', {
'form_id': 'contact-form',
'form_destination': destination,
'eventCallback': function() {
// Navigate after event is sent
window.location.href = destination;
},
'eventTimeout': 2000 // Timeout fallback
});
}
// ============================================================================
// DEBUGGING EXAMPLES
// ============================================================================
// Enable debug mode for testing
gtag('config', 'G-XXXXXXXXXX', {
'debug_mode': true
});
// Or for specific events
gtag('event', 'test_event', {
'test_parameter': 'test_value',
'debug_mode': true
});
// ============================================================================
// NOTES & BEST PRACTICES
// ============================================================================
/*
Best Practices:
1. Use snake_case for event and parameter names
2. Keep event names under 40 characters
3. Keep parameter names under 40 characters
4. Keep parameter values under 100 characters (exceptions noted)
5. Maximum 25 parameters per event
6. Use ISO currency codes (USD, EUR, GBP) not symbols ($)
7. Send numeric values as numbers, not strings
8. Test in DebugView before deploying to production
9. Register custom parameters as custom dimensions in GA4 Admin
10. Document all custom events in tracking plan
Common Mistakes to Avoid:
1. Missing currency parameter on value events
2. Using $ instead of USD for currency
3. Exceeding 25 parameters per event
4. Sending PII (personally identifiable information)
5. Using generic event names (click, event, data)
6. Not testing in DebugView
7. Forgetting to register custom dimensions
Character Limits:
- Event name: 40 characters
- Parameter name: 40 characters
- Parameter value: 100 characters (standard)
- page_title: 300 characters
- page_referrer: 420 characters
- page_location: 1000 characters
*/

View File

@@ -0,0 +1,734 @@
# Event Naming Conventions Best Practices
## Overview
Consistent, descriptive event naming is essential for maintainable GA4 implementations. This guide provides comprehensive best practices, patterns, and examples for naming events and parameters.
## Core Naming Principles
### 1. Use snake_case
**Format:** lowercase_with_underscores
```javascript
// ✅ CORRECT
'button_click'
'form_submit'
'video_tutorial_watched'
'pricing_calculator_used'
// ❌ WRONG
'buttonClick' // camelCase
'ButtonClick' // PascalCase
'button-click' // kebab-case
'BUTTON_CLICK' // UPPERCASE
'button click' // spaces
```
**Why snake_case:**
- GA4 standard convention
- Consistent with Google-recommended events
- Readable and parseable
- Works across all platforms
---
### 2. Be Descriptive and Action-Oriented
**Pattern:** Start with verb (action) when possible
```javascript
// ✅ CORRECT - Descriptive, action-oriented
'video_tutorial_started'
'whitepaper_downloaded'
'demo_request_submitted'
'pricing_tier_selected'
'account_upgrade_completed'
// ❌ WRONG - Too generic or vague
'video'
'download'
'form'
'click'
'event'
```
---
### 3. Keep Under 40 Characters
**Limit:** Maximum 40 characters for event names
```javascript
// ✅ CORRECT - 38 characters
'enterprise_demo_scheduling_completed'
// ⚠️ WARNING - 48 characters (too long)
'enterprise_customer_onboarding_demo_scheduling_completed'
// ✅ BETTER - Abbreviated to 35 characters
'enterprise_demo_onboarding_complete'
```
**Character Count Check:**
```javascript
'video_tutorial_watched'.length // 22 characters ✅
'very_long_descriptive_event_name_exceeding_limits'.length // 50 characters ❌
```
---
### 4. Avoid Reserved Names
**Don't Use:** Google-reserved automatic and recommended event names for custom events
```javascript
// ❌ WRONG - Using reserved recommended event names
'login' // Reserved
'sign_up' // Reserved
'purchase' // Reserved
'page_view' // Reserved
// ✅ CORRECT - Custom variations when needed
'custom_login_attempt'
'trial_signup_completed'
'demo_purchase_simulation'
'virtual_page_view'
```
**Reserved Event Names to Avoid:**
- All automatically collected events (session_start, first_visit, user_engagement)
- All enhanced measurement events (scroll, click, file_download, video_start, etc.)
- All recommended events (login, sign_up, purchase, add_to_cart, etc.)
---
### 5. Be Consistent Across Implementation
**Maintain Consistency:**
- Use same naming pattern throughout site/app
- Document naming conventions
- Share with team
- Create naming reference guide
```javascript
// ✅ CORRECT - Consistent pattern
'video_tutorial_started'
'video_tutorial_paused'
'video_tutorial_completed'
// ❌ WRONG - Inconsistent pattern
'videoTutorialStarted' // Different case
'video_tutorial_paused' // Consistent
'VideoTutorialComplete' // Different case, missing 'd'
```
---
## Event Naming Patterns
### Pattern 1: [action]_[object]
**Structure:** verb_noun
**Examples:**
```javascript
'button_clicked'
'form_submitted'
'video_started'
'file_downloaded'
'account_created'
'payment_completed'
'newsletter_subscribed'
```
**Use When:** Simple, single-action events
---
### Pattern 2: [object]_[action]
**Structure:** noun_verb
**Examples:**
```javascript
'cart_abandoned'
'product_viewed'
'coupon_applied'
'search_performed'
'filter_applied'
'wishlist_added'
```
**Use When:** Object-focused tracking
---
### Pattern 3: [action]_[object]_[context]
**Structure:** verb_noun_descriptor
**Examples:**
```javascript
'video_tutorial_started'
'demo_request_submitted'
'pricing_calculator_opened'
'trial_signup_completed'
'whitepaper_pdf_downloaded'
'enterprise_demo_scheduled'
```
**Use When:** Need additional context for clarity
---
### Pattern 4: [object]_[attribute]_[action]
**Structure:** noun_descriptor_verb
**Examples:**
```javascript
'free_trial_started'
'premium_tier_selected'
'annual_plan_purchased'
'mobile_app_downloaded'
'beta_feature_activated'
```
**Use When:** Attribute is critical to event meaning
---
### Pattern 5: [category]_[object]_[action]
**Structure:** category_noun_verb
**Examples:**
```javascript
'ecommerce_checkout_started'
'ecommerce_payment_failed'
'content_article_shared'
'content_video_completed'
'account_password_reset'
'account_email_verified'
```
**Use When:** Organizing events by category
---
## Industry-Specific Naming Examples
### SaaS / Software
```javascript
// Feature Usage
'feature_activated'
'feature_trial_started'
'feature_upgrade_clicked'
'feature_limit_reached'
// Onboarding
'onboarding_started'
'onboarding_step_completed'
'onboarding_skipped'
'onboarding_completed'
// Account Management
'account_upgraded'
'account_downgraded'
'account_cancelled'
'account_reactivated'
// Product Tours
'product_tour_started'
'product_tour_step_viewed'
'product_tour_completed'
'product_tour_dismissed'
// Collaboration
'team_member_invited'
'workspace_created'
'document_shared'
'comment_posted'
```
---
### E-Commerce
```javascript
// Product Discovery
'product_search_performed'
'product_filter_applied'
'product_sort_changed'
'category_browsed'
// Product Interaction
'product_image_zoomed'
'product_variant_selected'
'product_size_chart_viewed'
'product_review_read'
// Cart & Checkout
'cart_item_added'
'cart_item_removed'
'cart_viewed'
'checkout_started'
'checkout_step_completed'
'promo_code_applied'
// Post-Purchase
'order_confirmed'
'review_submitted'
'product_returned'
'subscription_renewed'
```
---
### Education / E-Learning
```javascript
// Course Discovery
'course_search_performed'
'course_preview_watched'
'course_syllabus_viewed'
'instructor_profile_viewed'
// Enrollment
'course_enrolled'
'course_trial_started'
'course_purchased'
'bundle_selected'
// Learning Progress
'lesson_started'
'lesson_completed'
'quiz_attempted'
'quiz_passed'
'certificate_earned'
// Engagement
'discussion_post_created'
'question_asked'
'resource_downloaded'
'video_lecture_watched'
```
---
### Media / Publishing
```javascript
// Content Consumption
'article_opened'
'article_read_complete'
'gallery_image_viewed'
'video_started'
'podcast_played'
// Engagement
'article_shared'
'article_bookmarked'
'comment_posted'
'author_followed'
// Subscription
'paywall_encountered'
'subscription_modal_viewed'
'free_trial_started'
'subscription_purchased'
// Navigation
'category_selected'
'related_article_clicked'
'search_performed'
'navigation_used'
```
---
### Financial Services
```javascript
// Account Actions
'account_application_started'
'account_opened'
'account_verified'
'account_linked'
// Transactions
'transfer_initiated'
'payment_scheduled'
'bill_paid'
'investment_made'
// Tools & Calculators
'loan_calculator_used'
'retirement_planner_opened'
'budget_tool_accessed'
'rate_comparison_viewed'
// Security
'two_factor_enabled'
'security_question_set'
'password_changed'
'device_authorized'
```
---
### Healthcare
```javascript
// Appointments
'appointment_scheduled'
'appointment_rescheduled'
'appointment_cancelled'
'telehealth_started'
// Patient Portal
'test_results_viewed'
'prescription_refill_requested'
'medical_record_downloaded'
'message_sent_to_provider'
// Information
'symptom_checker_used'
'provider_search_performed'
'insurance_verified'
'health_article_read'
```
---
## Parameter Naming Conventions
### General Rules
**Same Conventions as Events:**
- Use snake_case
- Keep under 40 characters
- Be descriptive
- Avoid reserved names
- Be consistent
### Parameter Naming Patterns
#### Pattern 1: [object]_[attribute]
```javascript
'video_duration'
'video_title'
'video_quality'
'button_name'
'button_location'
'button_id'
'form_name'
'form_type'
'form_destination'
'product_id'
'product_name'
'product_category'
```
#### Pattern 2: [context]_[measurement]
```javascript
'completion_percent'
'scroll_depth'
'engagement_time'
'page_views'
'time_spent_seconds'
```
#### Pattern 3: [category]_[object]_[attribute]
```javascript
'ecommerce_item_price'
'ecommerce_item_quantity'
'user_subscription_tier'
'user_account_age'
'content_article_word_count'
```
---
## Common Naming Mistakes
### Mistake 1: Too Generic
```javascript
// ❌ WRONG - Too generic
'click'
'event'
'action'
'data'
'custom_event'
// ✅ CORRECT - Specific and descriptive
'cta_button_clicked'
'form_submit_completed'
'video_play_started'
'filter_applied'
'search_performed'
```
---
### Mistake 2: Inconsistent Naming
```javascript
// ❌ WRONG - Inconsistent pattern
'videoStarted' // camelCase
'video_paused' // snake_case
'VideoPaused' // PascalCase
'video-completed' // kebab-case
// ✅ CORRECT - Consistent snake_case
'video_started'
'video_paused'
'video_resumed'
'video_completed'
```
---
### Mistake 3: Using Abbreviations
```javascript
// ❌ WRONG - Unclear abbreviations
'btn_clk'
'frm_sub'
'vid_cmpltd'
'usr_rgstr'
// ✅ CORRECT - Full words
'button_clicked'
'form_submitted'
'video_completed'
'user_registered'
```
**Exception:** Well-known abbreviations are acceptable
```javascript
// ✅ ACCEPTABLE - Common abbreviations
'pdf_downloaded' // PDF is standard
'cta_clicked' // CTA = Call To Action
'url_shared' // URL is standard
'id_verified' // ID is standard
```
---
### Mistake 4: Including Dynamic Data
```javascript
// ❌ WRONG - Dynamic data in event name
'product_SKU123_viewed'
'user_john_logged_in'
'page_pricing_viewed'
// ✅ CORRECT - Dynamic data in parameters
gtag('event', 'product_viewed', {
'product_id': 'SKU123'
});
gtag('event', 'user_logged_in', {
'user_name': 'john'
});
gtag('event', 'page_viewed', {
'page_type': 'pricing'
});
```
---
### Mistake 5: Too Long
```javascript
// ❌ WRONG - 64 characters (exceeds 40 limit)
'enterprise_customer_onboarding_demo_scheduling_request_completed'
// ✅ CORRECT - 35 characters
'enterprise_demo_scheduled'
// Alternative approach - use parameters for detail
gtag('event', 'demo_scheduled', {
'customer_tier': 'enterprise',
'demo_type': 'onboarding',
'request_status': 'completed'
});
```
---
## Event Naming Checklist
Before finalizing event names:
- [ ] Uses snake_case (lowercase with underscores)
- [ ] Under 40 characters
- [ ] Descriptive and action-oriented
- [ ] Doesn't conflict with reserved Google event names
- [ ] Consistent with other event names in implementation
- [ ] No abbreviations (unless standard like PDF, URL)
- [ ] No dynamic data in name (use parameters instead)
- [ ] No spaces or special characters
- [ ] Documented in event tracking plan
- [ ] Reviewed by team for clarity
---
## Documentation Template
### Event Documentation Format
```
Event Name: [event_name]
Description: [What this event tracks]
When to Fire: [User action or trigger]
Pattern Used: [action_object, object_action, etc.]
Category: [engagement, conversion, navigation, etc.]
Parameters:
- parameter_1: [description] (type: string/number/boolean)
- parameter_2: [description] (type: string/number/boolean)
Example Implementation:
gtag('event', 'event_name', {
'parameter_1': 'value',
'parameter_2': 123
});
Expected Volume: [events per day/week/month]
Key Event: [Yes/No]
Custom Dimensions Needed: [Yes/No - list if yes]
```
### Example Documentation
```
Event Name: video_tutorial_completed
Description: User completes watching a video tutorial
When to Fire: Video reaches 100% completion
Pattern Used: object_action_completed
Category: engagement
Parameters:
- video_id: Unique video identifier (type: string)
- video_title: Title of video (type: string)
- video_duration: Length in seconds (type: number)
- completion_time: Seconds to complete (type: number)
- video_category: Tutorial category (type: string)
Example Implementation:
gtag('event', 'video_tutorial_completed', {
'video_id': 'VID_123',
'video_title': 'GA4 Fundamentals',
'video_duration': 1200,
'completion_time': 1180,
'video_category': 'analytics'
});
Expected Volume: 500 events/week
Key Event: Yes
Custom Dimensions Needed:
- video_category (event-scoped)
- video_duration (metric)
```
---
## Event Taxonomy Example
### Organizing Events by Category
```
Engagement Events:
├── video_started
├── video_paused
├── video_completed
├── article_read
├── article_shared
└── comment_posted
Conversion Events:
├── lead_generated
├── trial_started
├── subscription_purchased
├── account_upgraded
└── demo_requested
Navigation Events:
├── menu_opened
├── search_performed
├── filter_applied
├── category_selected
└── page_scrolled
Feature Usage Events:
├── feature_activated
├── tool_opened
├── calculator_used
├── export_generated
└── settings_changed
Error Events:
├── form_validation_failed
├── payment_declined
├── upload_failed
├── session_timeout
└── error_encountered
```
---
## Naming Convention Quick Reference
| Element | Format | Example | Max Length |
|---------|--------|---------|------------|
| **Event Name** | snake_case | `video_tutorial_watched` | 40 chars |
| **Parameter Name** | snake_case | `video_duration` | 40 chars |
| **Parameter Value (string)** | Any | `HD Quality` | 100 chars* |
| **Currency Code** | ISO 4217 | `USD` | 3 chars |
| **Boolean Value** | true/false | `true` | N/A |
*Exceptions: page_title (300), page_referrer (420), page_location (1000)
---
## Testing Event Names
### DebugView Validation
1. Enable Google Analytics Debugger extension
2. Navigate to Admin → DebugView
3. Trigger event
4. Verify:
- Event name appears correctly
- Event name is not truncated
- Event name follows convention
- Parameters are attached
### Common DebugView Issues
| What You See | Problem | Solution |
|-------------|---------|----------|
| Event name truncated | >40 characters | Shorten name |
| Event name capitalized wrong | Wrong case used | Use snake_case |
| Event not firing | Name typo | Check implementation |
| Multiple similar events | Inconsistent naming | Standardize |
---
## Additional Resources
- Google Analytics Event Naming: https://support.google.com/analytics/answer/9322688
- Recommended Events: https://support.google.com/analytics/answer/9267735
- Event Limits: https://support.google.com/analytics/answer/9267744

View File

@@ -0,0 +1,660 @@
# Event Parameters Complete Guide
## Overview
Event parameters provide context and detail about user interactions in GA4. Understanding parameter structure, limits, and best practices is essential for effective event tracking.
## What Are Event Parameters?
**Definition:** Additional data points attached to events that provide context about user actions.
**Structure:**
```javascript
gtag('event', 'event_name', {
'parameter_name_1': 'value',
'parameter_name_2': 123,
'parameter_name_3': true
});
```
## Parameter Types
### 1. Automatically Collected Parameters
Parameters GA4 collects without additional configuration.
#### Web Stream Standard Parameters
**Page Parameters:**
- `page_location` - Full page URL (max 1000 chars)
- `page_referrer` - Previous page URL (max 420 chars)
- `page_title` - Page title from `<title>` tag (max 300 chars)
**User/Device Parameters:**
- `language` - Browser language (e.g., en-us)
- `screen_resolution` - Device screen size (e.g., 1920x1080)
- `client_id` - Anonymous user identifier
**Engagement Parameters:**
- `engagement_time_msec` - Time engaged in milliseconds
- `session_id` - Current session identifier
- `session_number` - Count of sessions for user
#### App Stream Standard Parameters
- `app_version` - Current application version
- `firebase_screen_id` - Unique screen identifier
- `firebase_screen_class` - Screen class name
- `platform` - iOS or Android
### 2. Enhanced Measurement Parameters
Parameters automatically collected with enhanced measurement events.
#### Scroll Event Parameters
- `engagement_time_msec` - Time engaged before scroll
#### Click Event Parameters
- `link_classes` - CSS classes on link
- `link_domain` - Destination domain
- `link_id` - Element ID
- `link_url` - Full destination URL
- `outbound` - true (for outbound links)
#### File Download Parameters
- `file_extension` - File type (.pdf, .xlsx)
- `file_name` - Name of file
- `link_classes` - CSS classes
- `link_id` - Element ID
- `link_text` - Link text
- `link_url` - Download URL
#### Video Engagement Parameters
- `video_title` - YouTube video title
- `video_url` - YouTube video URL
- `video_duration` - Total length (seconds)
- `video_current_time` - Playback position
- `video_percent` - Milestone reached (10, 25, 50, 75)
- `video_provider` - youtube.com
- `visible` - Viewport visibility (true/false)
#### Form Interaction Parameters
- `form_id` - HTML form ID
- `form_name` - HTML form name
- `form_destination` - Form action URL
- `form_submit_text` - Submit button text
#### Search Parameters
- `search_term` - User's search query
- `unique_search_term` - First occurrence flag
### 3. Recommended Event Parameters
Standardized parameters for Google-defined recommended events.
#### Authentication Parameters
**login event:**
- `method` - Authentication method (email, google, facebook, phone)
**sign_up event:**
- `method` - Registration method (email, google, facebook)
#### Ecommerce Parameters
**Required for purchase event:**
- `transaction_id` - Unique transaction identifier (CRITICAL - must be unique)
- `value` - Total transaction value (numeric)
- `currency` - ISO 4217 currency code (USD, EUR, GBP)
**Recommended for purchase:**
- `tax` - Tax amount (numeric)
- `shipping` - Shipping cost (numeric)
- `items` - Array of product objects (see Items Array section)
- `coupon` - Coupon code applied (string)
- `affiliation` - Store/affiliate name (string)
**Item-level parameters (in items array):**
- `item_id` - Product SKU/ID
- `item_name` - Product name
- `price` - Unit price
- `quantity` - Number of units
- `item_category` - Primary category
- `item_category2` through `item_category5` - Hierarchical categories
- `item_brand` - Brand name
- `item_variant` - Size, color, variant
- `coupon` - Item-level coupon
- `discount` - Discount amount
- `affiliation` - Store name
- `index` - Position in list (0-based)
- `item_list_id` - List identifier
- `item_list_name` - List name
- `location_id` - Physical location ID
#### Search Parameters
- `search_term` - User's search query
#### Content Selection Parameters
- `content_type` - Type of content (article, video, product)
- `item_id` - Content identifier
#### Promotion Parameters
- `promotion_id` - Promotion identifier
- `promotion_name` - Promotion name
- `creative_name` - Creative asset name
- `creative_slot` - Position (banner_slot_1)
### 4. Custom Parameters
Business-specific parameters created for custom events.
**Examples:**
```javascript
// Video tutorial tracking
gtag('event', 'video_tutorial_watched', {
'tutorial_id': 'VID_123',
'tutorial_name': 'GA4 Basics',
'tutorial_duration': 1200, // seconds
'completion_percent': 100,
'difficulty_level': 'beginner',
'language': 'en'
});
// SaaS feature usage
gtag('event', 'feature_activated', {
'feature_name': 'advanced_reporting',
'feature_tier': 'enterprise',
'activation_source': 'settings_page',
'first_time_use': true
});
// E-learning course
gtag('event', 'course_enrollment', {
'course_id': 'COURSE_101',
'course_name': 'Advanced Analytics',
'instructor': 'John Doe',
'price': 99.99,
'currency': 'USD',
'level': 'advanced',
'enrollment_method': 'direct'
});
```
## Parameter Limits and Constraints
### Critical Limits
| Limit Type | Standard GA4 | GA4 360 |
|------------|-------------|---------|
| Parameters per event | 25 | 25 |
| Event-scoped custom dimensions | 50 | 125 |
| User-scoped custom dimensions | 25 | 100 |
| Item-scoped custom dimensions | 10 | 25 |
### Character Limits
| Element | Maximum Characters |
|---------|-------------------|
| Parameter name | 40 |
| Parameter value (standard) | 100 |
| `page_title` parameter | 300 |
| `page_referrer` parameter | 420 |
| `page_location` parameter | 1000 |
### Data Type Constraints
**Supported Types:**
- String (text)
- Number (integer or float)
- Boolean (true/false)
- Array (for items parameter)
**Not Supported:**
- Objects (except items array)
- Nested objects
- Functions
- Null values (use for clearing only)
## Parameter Naming Conventions
### Best Practices
**DO:**
- Use snake_case (lowercase with underscores)
- Be descriptive but concise
- Use consistent naming across events
- Keep under 40 characters
**DON'T:**
- Use spaces or special characters
- Use camelCase or PascalCase
- Use generic names (param1, value, data)
- Include personally identifiable information (PII)
### Naming Patterns
**Recommended Patterns:**
```
[object]_[attribute]
Examples: product_id, user_tier, video_duration
[action]_[attribute]
Examples: purchase_value, scroll_depth, form_name
[category]_[subcategory]_[attribute]
Examples: ecommerce_item_price, video_completion_percent
```
### Reserved Parameter Names
GA4 reserves certain parameter names. Avoid using these for custom parameters:
- `client_id`
- `session_id`
- `session_number`
- `page_location`
- `page_referrer`
- `page_title`
- `language`
- `screen_resolution`
- All recommended event parameter names (transaction_id, value, currency, etc.)
## Items Array Structure
### Overview
The `items` parameter is a special array structure for ecommerce events containing product information.
### Required Fields
At minimum, each item must have:
- `item_id` OR `item_name` (at least one required)
### Complete Item Object
```javascript
{
// Required (at least one)
'item_id': 'SKU_12345',
'item_name': 'Stan and Friends Tee',
// Highly Recommended
'price': 10.01,
'quantity': 3,
'item_category': 'Apparel',
// Optional but Useful
'item_brand': 'Google',
'item_variant': 'green',
'item_category2': 'Adult',
'item_category3': 'Shirts',
'item_category4': 'Crew',
'item_category5': 'Short sleeve',
// Ecommerce Context
'affiliation': 'Google Merchandise Store',
'coupon': 'SUMMER_FUN',
'discount': 2.22,
'index': 0,
'item_list_id': 'related_products',
'item_list_name': 'Related Products',
'location_id': 'L_12345',
// Custom Item Parameters
'item_color': 'green',
'item_size': 'large',
'supplier': 'Vendor_A'
}
```
### Items Array Limits
- Maximum 27 items per event
- Maximum 10 item-scoped custom dimensions per property (standard GA4)
- Maximum 25 item-scoped custom dimensions per property (GA4 360)
### Items Array Example
```javascript
gtag('event', 'purchase', {
'transaction_id': 'TXN_12345',
'value': 142.52,
'currency': 'USD',
'items': [
{
'item_id': 'SKU_001',
'item_name': 'Product A',
'price': 49.99,
'quantity': 2,
'item_category': 'Electronics'
},
{
'item_id': 'SKU_002',
'item_name': 'Product B',
'price': 29.99,
'quantity': 1,
'item_category': 'Accessories'
}
]
});
```
## Parameter Value Formatting
### Currency Values
**Format:** Numeric (not string)
```javascript
// ✅ CORRECT
'value': 99.99,
'currency': 'USD'
// ❌ WRONG
'value': '$99.99',
'currency': '$'
```
**ISO 4217 Currency Codes:**
- USD - US Dollar
- EUR - Euro
- GBP - British Pound
- JPY - Japanese Yen
- CAD - Canadian Dollar
- AUD - Australian Dollar
- CHF - Swiss Franc
### Boolean Values
**Format:** true/false (not string)
```javascript
// ✅ CORRECT
'first_time_user': true,
'promotional_email_opt_in': false
// ❌ WRONG
'first_time_user': 'true',
'promotional_email_opt_in': 'false'
```
### Numeric Values
**Format:** Number (integer or float)
```javascript
// ✅ CORRECT
'quantity': 5,
'duration_seconds': 120,
'rating': 4.5
// ❌ WRONG
'quantity': '5',
'duration_seconds': '120',
'rating': '4.5'
```
### String Values
**Format:** Text within character limits
```javascript
// ✅ CORRECT
'product_name': 'Blue Widget',
'category': 'Widgets',
'description': 'High-quality blue widget'
// ⚠️ WARNING - Will be truncated
'very_long_description': 'This is an extremely long description that exceeds the 100 character limit and will be truncated in GA4 reports which may cause data loss'
```
## Parameter Scopes
Parameters have different scopes determining their application. See **references/parameter-scopes.md** for complete details.
### Quick Reference
**Event Scope:**
Applies to single event occurrence.
Example: `button_name`, `form_id`, `video_title`
**User Scope:**
Applies to all events from user across sessions.
Example: `subscription_tier`, `customer_segment`, `account_type`
**Item Scope:**
Applies to products in ecommerce items array.
Example: `item_color`, `item_size`, `supplier_name`
## Registering Parameters as Custom Dimensions
### Why Register
Custom parameters won't appear in GA4 reports until registered as custom dimensions.
### Registration Process
1. **Send Parameter in Event:**
```javascript
gtag('event', 'video_watched', {
'video_quality': 'hd', // Custom parameter
'video_duration': 300
});
```
2. **Navigate to GA4 Admin:**
Admin → Data Display → Custom Definitions
3. **Create Custom Dimension:**
- Dimension Name: "Video Quality"
- Scope: Event
- Event Parameter: "video_quality"
- Description: "Quality setting of watched videos"
- Click Save
4. **Wait 24-48 Hours:**
Data will populate in reports after processing delay
### Registration Best Practices
**DO:**
- Use descriptive dimension names (appear in reports)
- Match parameter name exactly (case-sensitive)
- Choose correct scope
- Plan dimensions before hitting quota limits
- Document all custom dimensions
**DON'T:**
- Register high-cardinality parameters (unique IDs, timestamps)
- Use dimension names with special characters
- Change scope after creation (not possible)
- Expect immediate data (24-48hr delay)
- Register parameters you won't analyze
## Common Parameter Mistakes
### 1. Missing Currency Parameter
```javascript
// ❌ WRONG - Missing currency
gtag('event', 'purchase', {
'transaction_id': 'TXN_123',
'value': 99.99
});
// ✅ CORRECT
gtag('event', 'purchase', {
'transaction_id': 'TXN_123',
'value': 99.99,
'currency': 'USD'
});
```
### 2. Using Currency Symbols
```javascript
// ❌ WRONG - Currency symbol
'currency': '$'
// ✅ CORRECT - ISO code
'currency': 'USD'
```
### 3. Exceeding Parameter Limit
```javascript
// ❌ WRONG - 30 parameters (exceeds 25 limit)
gtag('event', 'custom_event', {
'param_1': 'value1',
'param_2': 'value2',
// ... 28 more parameters
'param_30': 'value30' // This won't be collected
});
```
### 4. Parameter Name Too Long
```javascript
// ❌ WRONG - 52 characters
'this_is_a_very_long_parameter_name_that_exceeds_limit': 'value'
// ✅ CORRECT - 28 characters
'descriptive_param_name': 'value'
```
### 5. Sending PII
```javascript
// ❌ WRONG - Contains PII
gtag('event', 'form_submit', {
'user_email': 'john@example.com',
'user_phone': '555-1234',
'user_name': 'John Doe'
});
// ✅ CORRECT - No PII
gtag('event', 'form_submit', {
'email_domain': 'example.com',
'form_type': 'contact',
'form_location': 'footer'
});
```
### 6. Wrong Data Types
```javascript
// ❌ WRONG - Numeric values as strings
'quantity': '5',
'price': '99.99',
'in_stock': 'true'
// ✅ CORRECT - Proper types
'quantity': 5,
'price': 99.99,
'in_stock': true
```
## Parameter Testing Checklist
Before deploying event parameters:
- [ ] Parameter names follow snake_case convention
- [ ] Parameter names are under 40 characters
- [ ] Parameter values are under 100 characters (or applicable limit)
- [ ] Total parameters per event ≤ 25
- [ ] Correct data types used (number, string, boolean)
- [ ] Currency uses ISO codes (not symbols)
- [ ] No PII included in parameters
- [ ] Parameters visible in DebugView
- [ ] Custom parameters registered as custom dimensions (if needed)
- [ ] Scope correctly assigned (event/user/item)
- [ ] Documentation created for custom parameters
## Advanced Parameter Patterns
### Conditional Parameters
```javascript
// Only include parameter if value exists
const eventParams = {
'event_category': 'engagement'
};
if (couponCode) {
eventParams.coupon = couponCode;
}
if (userTier) {
eventParams.user_tier = userTier;
}
gtag('event', 'purchase', eventParams);
```
### Dynamic Parameter Values
```javascript
// Calculate parameter values dynamically
gtag('event', 'video_complete', {
'video_id': videoId,
'video_duration': Math.round(duration),
'completion_time': Date.now(),
'engagement_rate': Math.round((watchedTime / totalTime) * 100)
});
```
### Merging Parameter Objects
```javascript
// Combine multiple parameter sources
const baseParams = {
'event_category': 'ecommerce',
'currency': 'USD'
};
const productParams = {
'product_id': 'SKU_123',
'product_name': 'Widget',
'price': 29.99
};
gtag('event', 'view_item', {
...baseParams,
...productParams
});
```
## Parameter Debugging
### Using DebugView
1. Enable debug mode (Google Analytics Debugger extension)
2. Navigate to Admin → DebugView
3. Trigger event
4. Click event in left panel
5. Inspect parameters in right panel
**What to Check:**
- All expected parameters present
- Parameter names correct (case-sensitive)
- Parameter values correct type and format
- No truncation of values
- Parameters within limits (≤25)
### Common DebugView Issues
| What You See | Problem | Solution |
|-------------|---------|----------|
| Parameter missing | Not sent in event | Check event code |
| Parameter value wrong | Incorrect data source | Verify variable/value |
| Parameter truncated | Exceeds character limit | Shorten value |
| Too many parameters | >25 sent | Reduce parameter count |
| Parameter not in reports | Not registered as dimension | Register in Admin |
## Additional Resources
- Official GA4 Event Parameters: https://support.google.com/analytics/answer/9267735
- Custom Dimensions Guide: https://support.google.com/analytics/answer/10075209
- Items Array Reference: https://developers.google.com/analytics/devguides/collection/ga4/ecommerce

View File

@@ -0,0 +1,781 @@
# Event Types Complete Reference
## Overview
GA4 uses four distinct event categories, each serving a specific purpose in the measurement architecture. Understanding these categories is essential for implementing comprehensive tracking.
## Event Category 1: Automatically Collected Events
### Definition
Events that fire automatically when GA4 tracking code is installed, requiring no additional configuration.
### Core Automatic Events
#### session_start
**Trigger:** User session begins
**Platform:** Web and App
**Parameters (automatic):**
- `page_location` - Current page URL
- `page_referrer` - Previous page URL
- `ga_session_id` - Session identifier
- `ga_session_number` - Session count for user
**Use Case:** Session tracking, session-based metrics
---
#### first_visit
**Trigger:** User's first visit to website or app
**Platform:** Web and App
**Parameters (automatic):**
- All standard page parameters
- `first_visit_time` - Timestamp of first visit
**Use Case:** New user acquisition tracking, user lifecycle analysis
---
#### user_engagement
**Trigger:** App in foreground OR webpage in focus for 1+ second
**Platform:** Web and App
**Parameters (automatic):**
- `engagement_time_msec` - Time engaged in milliseconds
**Use Case:** Engagement metrics, active time tracking
**Important:** This is how GA4 measures "engaged sessions"
---
#### page_view (when enhanced measurement enabled)
**Trigger:** Page loads
**Platform:** Web only
**Parameters (automatic):**
- `page_location` - Full page URL
- `page_referrer` - Previous page URL
- `page_title` - Page title from `<title>` tag
- `engagement_time_msec` - Time on page
**Use Case:** Page tracking, content analysis
**Note:** Also part of Enhanced Measurement but listed here for completeness
---
### App-Only Automatic Events
#### first_open
**Trigger:** App launched after installation
**Platform:** App only
**Parameters (automatic):**
- `previous_app_version` - Version before update (if applicable)
**Use Case:** App install tracking, version migration analysis
---
## Event Category 2: Enhanced Measurement Events
### Definition
Automatically tracked interactions that can be toggled on/off in GA4 Admin settings (Data Streams → Web Stream → Enhanced measurement).
### Configuration Location
Admin → Data Collection and Modification → Data Streams → [Select Web Stream] → Enhanced measurement (gear icon)
### Enhanced Measurement Events
#### page_view
**Trigger:** Page loads OR history state changes (SPA navigation)
**Toggle:** On/Off
**Parameters:**
- `page_location` - Current URL
- `page_referrer` - Previous URL
- `page_title` - Page title
- `engagement_time_msec` - Time engaged
**Use Case:** Page tracking for both traditional and single-page applications
---
#### scroll
**Trigger:** User scrolls to 90% of page vertical depth
**Toggle:** On/Off
**Parameters:**
- `engagement_time_msec` - Time engaged before scroll
**Limitation:** Only 90% depth tracked (not customizable in enhanced measurement)
**Custom Implementation:** For multiple thresholds (25%, 50%, 75%, 90%), implement custom scroll tracking via GTM
---
#### click (Outbound Links)
**Trigger:** Click on link leading to different domain
**Toggle:** On/Off
**Parameters:**
- `link_classes` - CSS classes on link element
- `link_domain` - Destination domain
- `link_id` - Element ID
- `link_url` - Full destination URL
- `outbound` - true (identifies as outbound click)
**Use Case:** External link tracking, content engagement analysis
---
#### file_download
**Trigger:** Click on link to common file extensions
**Toggle:** On/Off
**Tracked Extensions:**
- pdf, xlsx, docx, txt, rtf, csv, xls, ppt, pptx
- 7z, pkg, rar, gz, zip, avi, mov, mp4, mpeg, wmv, midi, mp3, wav, wma
**Parameters:**
- `file_extension` - File type (.pdf, .xlsx, etc.)
- `file_name` - Name of downloaded file
- `link_classes` - CSS classes
- `link_id` - Element ID
- `link_text` - Link text
- `link_url` - Download URL
**Use Case:** Content download tracking, resource engagement
---
#### view_search_results
**Trigger:** URL query parameter detected indicating site search
**Toggle:** On/Off (with configuration)
**Configuration:** Specify search query parameter name (default: q, s, search, query)
**Parameters:**
- `search_term` - User's search query
- `unique_search_term` - First occurrence flag
**Use Case:** Site search analysis, content discoverability
---
#### video_start
**Trigger:** YouTube embedded video starts playing
**Toggle:** On/Off (Video engagement setting)
**Requirements:** YouTube video with JS API enabled
**Parameters:**
- `video_title` - YouTube video title
- `video_url` - YouTube video URL
- `video_duration` - Total video length (seconds)
- `video_current_time` - Playback position
- `video_provider` - youtube.com
- `visible` - true/false (viewport visibility)
**Use Case:** Video engagement tracking
---
#### video_progress
**Trigger:** Video reaches 10%, 25%, 50%, 75% completion
**Toggle:** On/Off (Video engagement setting)
**Parameters:**
- `video_title`
- `video_url`
- `video_duration`
- `video_current_time`
- `video_percent` - Milestone reached (10, 25, 50, 75)
- `video_provider` - youtube.com
- `visible` - Viewport visibility
**Use Case:** Video completion funnel analysis
---
#### video_complete
**Trigger:** Video playback reaches 100%
**Toggle:** On/Off (Video engagement setting)
**Parameters:**
- `video_title`
- `video_url`
- `video_duration`
- `video_current_time`
- `video_provider`
- `visible`
**Use Case:** Video completion tracking
---
#### form_start
**Trigger:** User first interacts with form in session
**Toggle:** On/Off (Form interactions setting)
**Parameters:**
- `form_id` - HTML form ID attribute
- `form_name` - HTML form name attribute
- `form_destination` - Form action URL
**Use Case:** Form engagement tracking, conversion funnel
**Limitation:** Fires once per session (not per form submission)
---
#### form_submit
**Trigger:** Form submitted
**Toggle:** On/Off (Form interactions setting)
**Parameters:**
- `form_id`
- `form_name`
- `form_destination`
- `form_submit_text` - Submit button text
**Use Case:** Form conversion tracking, lead generation
---
## Event Category 3: Recommended Events
### Definition
Google-defined event names with standardized parameter structures. Using these ensures compatibility with GA4 features, Google Ads integration, and industry benchmarking.
### Why Use Recommended Events
**Benefits:**
- Enable standard reports (Ecommerce reports, Purchase funnel)
- Required for conversion modeling
- Compatible with Google Ads
- Audience building support
- Industry benchmarking
### Engagement Recommended Events
#### login
**When to Fire:** User successfully authenticates
**Required Parameters:** None
**Recommended Parameters:**
- `method` - Authentication method (email, google, facebook, phone)
**Implementation Example:**
```javascript
gtag('event', 'login', {
'method': 'email'
});
```
---
#### sign_up
**When to Fire:** New user account created
**Required Parameters:** None
**Recommended Parameters:**
- `method` - Registration method (email, google, facebook)
**Implementation Example:**
```javascript
gtag('event', 'sign_up', {
'method': 'google'
});
```
---
#### search
**When to Fire:** User performs site search
**Required Parameters:** None
**Recommended Parameters:**
- `search_term` - User's search query
**Implementation Example:**
```javascript
gtag('event', 'search', {
'search_term': 'blue widgets'
});
```
---
#### select_content
**When to Fire:** User selects content item
**Required Parameters:** None
**Recommended Parameters:**
- `content_type` - Type of content (article, video, product)
- `item_id` - Content identifier
**Implementation Example:**
```javascript
gtag('event', 'select_content', {
'content_type': 'article',
'item_id': 'A123'
});
```
---
### Monetization Recommended Events
#### view_item
**When to Fire:** Product page viewed
**Required Parameters:**
- `items` - Array with at least `item_id` OR `item_name`
**Recommended Parameters:**
- `value` - Item value
- `currency` - ISO currency code (USD, EUR, GBP)
**Implementation Example:**
```javascript
gtag('event', 'view_item', {
'items': [
{
'item_id': 'SKU_123',
'item_name': 'Blue T-Shirt',
'item_category': 'Apparel',
'price': 29.99,
'quantity': 1
}
],
'value': 29.99,
'currency': 'USD'
});
```
---
#### add_to_cart
**When to Fire:** Item added to shopping cart
**Required Parameters:**
- `items` - Array of product objects
**Recommended Parameters:**
- `value` - Cart value
- `currency` - ISO currency code
**Implementation Example:**
```javascript
gtag('event', 'add_to_cart', {
'items': [
{
'item_id': 'SKU_123',
'item_name': 'Blue T-Shirt',
'price': 29.99,
'quantity': 1
}
],
'value': 29.99,
'currency': 'USD'
});
```
---
#### remove_from_cart
**When to Fire:** Item removed from cart
**Required Parameters:**
- `items` - Array with removed product
**Recommended Parameters:**
- `value` - Value of removed items
- `currency` - ISO currency code
---
#### view_cart
**When to Fire:** Shopping cart viewed
**Required Parameters:**
- `items` - Array of cart contents
**Recommended Parameters:**
- `value` - Total cart value
- `currency` - ISO currency code
---
#### begin_checkout
**When to Fire:** Checkout process initiated
**Required Parameters:**
- `items` - Array of products in cart
- `value` - Total transaction value
- `currency` - ISO currency code
**Recommended Parameters:**
- `coupon` - Coupon code applied
**Implementation Example:**
```javascript
gtag('event', 'begin_checkout', {
'items': [
{
'item_id': 'SKU_123',
'item_name': 'Blue T-Shirt',
'price': 29.99,
'quantity': 2
}
],
'value': 59.98,
'currency': 'USD',
'coupon': 'SUMMER10'
});
```
---
#### add_payment_info
**When to Fire:** Payment information entered
**Required Parameters:** None
**Recommended Parameters:**
- `payment_type` - Payment method (credit_card, paypal, gift_card)
- `items` - Array of products
- `value` - Transaction value
- `currency` - ISO currency code
---
#### add_shipping_info
**When to Fire:** Shipping method selected
**Required Parameters:** None
**Recommended Parameters:**
- `shipping_tier` - Shipping option (ground, overnight, express)
- `value` - Transaction value
- `currency` - ISO currency code
- `items` - Array of products
---
#### purchase
**When to Fire:** Purchase completed (transaction finalized)
**Required Parameters:**
- `transaction_id` - Unique transaction identifier
- `value` - Total revenue
- `currency` - ISO currency code
**Recommended Parameters:**
- `tax` - Tax amount
- `shipping` - Shipping cost
- `items` - Array of purchased products
- `coupon` - Coupon code
- `affiliation` - Store/affiliate name
**Implementation Example:**
```javascript
gtag('event', 'purchase', {
'transaction_id': 'TXN_12345',
'affiliation': 'Google Merchandise Store',
'value': 142.52,
'currency': 'USD',
'tax': 10.00,
'shipping': 5.00,
'coupon': 'SUMMER_FUN',
'items': [
{
'item_id': 'SKU_12345',
'item_name': 'Stan and Friends Tee',
'affiliation': 'Google Merchandise Store',
'coupon': 'SUMMER_FUN',
'discount': 2.22,
'index': 0,
'item_brand': 'Google',
'item_category': 'Apparel',
'item_category2': 'Adult',
'item_category3': 'Shirts',
'item_variant': 'green',
'price': 10.01,
'quantity': 3
}
]
});
```
**CRITICAL:** Mark as Key Event in GA4 Admin for conversion tracking
---
#### refund
**When to Fire:** Purchase refunded
**Required Parameters:**
- `transaction_id` - Original transaction ID
**Recommended Parameters:**
- `value` - Refund amount
- `currency` - ISO currency code
- `items` - Array of refunded items
---
### Other Recommended Events
#### generate_lead
**When to Fire:** Lead generated (form submission, contact request)
**Parameters:**
- `value` - Estimated lead value
- `currency` - ISO currency code
---
#### view_promotion
**When to Fire:** Promotion/banner displayed
**Parameters:**
- `promotion_id` - Promotion identifier
- `promotion_name` - Promotion name
- `items` - Featured products (optional)
---
#### select_promotion
**When to Fire:** User clicks promotion
**Parameters:**
- `promotion_id`
- `promotion_name`
- `items` - Featured products
---
## Event Category 4: Custom Events
### Definition
Business-specific events created for unique tracking requirements not covered by recommended events.
### When to Create Custom Events
Create custom events when:
- No recommended event fits your use case
- Tracking unique business processes
- Measuring proprietary features
- Tracking non-standard user interactions
### Custom Event Examples by Industry
#### SaaS / Software
```javascript
// Feature usage
gtag('event', 'feature_activated', {
'feature_name': 'advanced_analytics',
'user_tier': 'enterprise',
'trial_status': 'active'
});
// Product tour
gtag('event', 'product_tour_completed', {
'tour_name': 'onboarding_v2',
'completion_time_seconds': 180,
'steps_completed': 7
});
```
#### Education / E-Learning
```javascript
// Course enrollment
gtag('event', 'course_enrollment', {
'course_id': 'GA4_101',
'course_name': 'GA4 Fundamentals',
'instructor': 'John Doe',
'price': 99.99,
'currency': 'USD',
'level': 'beginner'
});
// Lesson completion
gtag('event', 'lesson_completed', {
'course_id': 'GA4_101',
'lesson_id': 'lesson_3',
'lesson_title': 'Event Tracking',
'time_spent_minutes': 15
});
```
#### Media / Content
```javascript
// Article engagement
gtag('event', 'article_read_complete', {
'article_id': 'A123',
'article_title': 'GA4 Guide',
'category': 'analytics',
'author': 'Jane Smith',
'word_count': 2500,
'time_to_read_minutes': 10
});
// Content sharing
gtag('event', 'content_shared', {
'content_type': 'article',
'content_id': 'A123',
'share_method': 'twitter',
'share_location': 'article_footer'
});
```
#### Finance / Banking
```javascript
// Account actions
gtag('event', 'account_created', {
'account_type': 'checking',
'method': 'online',
'branch_location': 'none'
});
// Calculator usage
gtag('event', 'loan_calculator_used', {
'calculator_type': 'mortgage',
'loan_amount': 250000,
'loan_term_years': 30,
'interest_rate': 3.5
});
```
### Custom Event Best Practices
**DO:**
- Use descriptive, action-oriented names
- Follow snake_case naming convention
- Keep names under 40 characters
- Include relevant context in parameters
- Document all custom events
- Test in DebugView before production
**DON'T:**
- Use generic names (event1, custom_event, data)
- Exceed 500 unique event names per property
- Send PII (personally identifiable information)
- Create custom events when recommended events exist
- Use spaces or special characters in names
- Forget to register parameters as custom dimensions
### Custom Event Planning Template
```
Event Name: [action]_[object]_[context]
Purpose: [Business goal]
When to Fire: [User action trigger]
Parameters:
- parameter_1: [description] (scope: event/user/item)
- parameter_2: [description] (scope: event/user/item)
Expected Volume: [events per day/week]
Custom Dimensions Needed: [Yes/No]
Key Event: [Yes/No]
```
---
## Event Category Comparison
| Category | Configuration Required | Code Required | Customizable | Use Case |
|----------|----------------------|---------------|--------------|----------|
| **Automatic** | No | No | No | Core session tracking |
| **Enhanced Measurement** | Toggle on/off | No | Limited | Common web interactions |
| **Recommended** | No | Yes | Parameters only | Standard business events |
| **Custom** | No | Yes | Fully | Unique business needs |
---
## Event Implementation Checklist
For each event implementation:
- [ ] Event name follows snake_case convention
- [ ] Event name is under 40 characters
- [ ] Using recommended event if available
- [ ] All required parameters included
- [ ] Parameter names are under 40 characters
- [ ] Parameter values under 100 characters (or applicable limit)
- [ ] Maximum 25 parameters per event
- [ ] Parameters have correct scope (event/user/item)
- [ ] Tested in DebugView
- [ ] Custom parameters registered as custom dimensions (if needed)
- [ ] Event marked as Key Event if conversion (if applicable)
- [ ] Documentation created for custom events
---
## Additional Resources
- Official GA4 Events Documentation: https://support.google.com/analytics/answer/9322688
- Recommended Events Reference: https://support.google.com/analytics/answer/9267735
- Enhanced Measurement: https://support.google.com/analytics/answer/9216061

View File

@@ -0,0 +1,716 @@
# Parameter Scopes Complete Guide
## Overview
GA4 uses three distinct scopes that determine how parameters are applied and analyzed: Event scope, User scope, and Item scope. Understanding scopes is critical for proper data collection and reporting.
## What is Scope?
**Definition:** Scope determines what data the parameter applies to and how long it persists.
**Three Scopes:**
1. **Event Scope** - Applies to single event occurrence
2. **User Scope** - Applies to all events from that user
3. **Item Scope** - Applies to products in ecommerce events
## Event Scope (Event-Scoped Parameters)
### Definition
Event-scoped parameters apply only to the specific event they're sent with. They describe what happened in that particular interaction.
### Characteristics
**Lifespan:** Single event only
**Persistence:** Does not carry over to other events
**Use For:** Event-specific details and context
### Common Use Cases
**User Actions:**
- Button clicks (which button, where)
- Form submissions (which form, form type)
- Video interactions (video title, duration, quality)
- Link clicks (link URL, link text, destination)
**Content:**
- Page information (current page, previous page)
- Search queries (search term)
- Filter selections (category, price range)
**Engagement:**
- Scroll depth (percentage)
- Time spent (duration)
- Completion status (percent complete)
### Event-Scoped Examples
#### Example 1: Button Click
```javascript
gtag('event', 'button_click', {
'button_name': 'Subscribe Now', // Event-scoped
'button_location': 'header', // Event-scoped
'button_id': 'btn_subscribe_01', // Event-scoped
'target_page': '/pricing' // Event-scoped
});
```
**Why Event-Scoped:**
- Only applies to this specific button click
- Different button clicks will have different values
- Describes this particular interaction
#### Example 2: Form Submission
```javascript
gtag('event', 'form_submit', {
'form_id': 'contact-form-v2', // Event-scoped
'form_name': 'Contact Us', // Event-scoped
'form_type': 'lead_generation', // Event-scoped
'form_destination': '/thank-you', // Event-scoped
'fields_completed': 5 // Event-scoped
});
```
**Why Event-Scoped:**
- Specific to this form submission
- Next form submission may have different form_id, form_name
- Describes details of this event only
#### Example 3: Video Engagement
```javascript
gtag('event', 'video_complete', {
'video_id': 'VID_123', // Event-scoped
'video_title': 'GA4 Tutorial', // Event-scoped
'video_duration': 1200, // Event-scoped (seconds)
'video_quality': 'hd', // Event-scoped
'completion_percent': 100, // Event-scoped
'watch_time_seconds': 1150 // Event-scoped
});
```
**Why Event-Scoped:**
- Describes this specific video watch event
- Each video_complete event has different video details
- Time-specific data for this viewing
### Registering Event-Scoped Custom Dimensions
**Process:**
1. **Send Parameter in Event:**
```javascript
gtag('event', 'custom_event', {
'custom_parameter': 'value' // Event-scoped
});
```
2. **Navigate to GA4 Admin:**
Admin → Data Display → Custom Definitions
3. **Create Custom Dimension:**
- **Dimension Name:** "Custom Parameter Name"
- **Scope:** **Event** ← Select Event
- **Event Parameter:** "custom_parameter"
- Description: What this parameter tracks
- Click Save
4. **Wait 24-48 hours for data population**
### Event Scope Limits
**Standard GA4:**
- 50 event-scoped custom dimensions per property
**GA4 360:**
- 125 event-scoped custom dimensions per property
---
## User Scope (User-Scoped Parameters / User Properties)
### Definition
User-scoped parameters (user properties) apply to all events from a specific user. They describe attributes of the user that persist across sessions.
### Characteristics
**Lifespan:** All user events until changed or cleared
**Persistence:** Carries over to all subsequent events from that user
**Use For:** User attributes, demographics, membership status, preferences
### Common Use Cases
**User Attributes:**
- Subscription tier (free, pro, enterprise)
- Customer segment (new, returning, vip)
- Account type (individual, business, enterprise)
- Membership status (trial, active, expired)
**User Behavior:**
- Customer lifetime value
- Years as customer
- Purchase frequency
- Engagement level
**User Preferences:**
- Preferred language
- Communication preferences
- Theme preference (light/dark)
- Notification settings
### User-Scoped Examples
#### Example 1: User Subscription Tier
```javascript
// Set once after login or tier change
gtag('set', {
'subscription_tier': 'premium', // User-scoped
'account_type': 'business', // User-scoped
'years_customer': 3 // User-scoped
});
// Now ALL subsequent events include these properties
gtag('event', 'page_view'); // Includes subscription_tier
gtag('event', 'button_click'); // Includes subscription_tier
gtag('event', 'purchase'); // Includes subscription_tier
```
**Why User-Scoped:**
- Applies to this user across all interactions
- Persists across multiple events and sessions
- Describes who the user is, not what they did
#### Example 2: Customer Segmentation
```javascript
gtag('set', {
'customer_segment': 'high_value', // User-scoped
'customer_lifetime_value': 5000, // User-scoped
'first_purchase_date': '2023-01-15', // User-scoped
'preferred_category': 'electronics' // User-scoped
});
```
**Why User-Scoped:**
- Attributes of the user that don't change per event
- Used for segmentation across all user actions
- Describes user characteristics
#### Example 3: User Preferences
```javascript
gtag('set', {
'preferred_language': 'en', // User-scoped
'theme_preference': 'dark', // User-scoped
'email_opt_in': true, // User-scoped
'notification_enabled': true // User-scoped
});
```
**Why User-Scoped:**
- Settings that apply to all user interactions
- Persist across sessions
- Help understand user behavior patterns
### User ID (Special User Property)
**Implementation:**
```javascript
// After user login
gtag('set', {
'user_id': 'user_12345' // Special user-scoped identifier
});
// On logout - MUST set to null
gtag('set', {
'user_id': null // NOT empty string ""
});
```
**Purpose:**
- Cross-device tracking
- Cross-session tracking
- User journey analysis
**Requirements:**
- Must be unique per user
- Must be persistent (same across devices/sessions)
- Cannot be PII (no email addresses, names)
- Must clear on logout (set to null)
### Registering User-Scoped Custom Dimensions
**Process:**
1. **Send User Property:**
```javascript
gtag('set', {
'custom_user_property': 'value' // User-scoped
});
```
2. **Navigate to GA4 Admin:**
Admin → Data Display → Custom Definitions
3. **Create Custom Dimension:**
- **Dimension Name:** "Custom User Property Name"
- **Scope:** **User** ← Select User
- **User Property:** "custom_user_property"
- Description: What this property represents
- Click Save
4. **Wait 24-48 hours for data population**
### User Scope Limits
**Standard GA4:**
- 25 user-scoped custom dimensions per property
**GA4 360:**
- 100 user-scoped custom dimensions per property
### User Scope Best Practices
**DO:**
- Set user properties after user identification (login, registration)
- Use for attributes that rarely change
- Clear user_id on logout (set to null)
- Use consistent values (always "premium", not "Premium" or "PREMIUM")
**DON'T:**
- Send PII (personally identifiable information)
- Use for event-specific data
- Change user properties frequently (not event-by-event)
- Exceed property limits (plan carefully)
---
## Item Scope (Item-Scoped Parameters)
### Definition
Item-scoped parameters apply to individual products in ecommerce events. They describe product-specific attributes.
### Characteristics
**Lifespan:** That transaction/ecommerce event only
**Persistence:** Applies to items in items array
**Use For:** Product-level details in ecommerce tracking
### Common Use Cases
**Product Attributes:**
- Product color, size, variant
- Product category, subcategory
- Product brand, manufacturer
- Product SKU, UPC
**Product Details:**
- Supplier/vendor information
- Warehouse location
- Stock status
- Product rating/reviews
**Product Pricing:**
- Individual price
- Discount applied
- Coupon used
- Margin/cost
### Item-Scoped Examples
#### Example 1: Product Purchase with Item Details
```javascript
gtag('event', 'purchase', {
'transaction_id': 'TXN_12345',
'value': 142.52,
'currency': 'USD',
'items': [
{
'item_id': 'SKU_123',
'item_name': 'Blue T-Shirt',
// Standard item parameters
'price': 29.99,
'quantity': 2,
'item_category': 'Apparel',
'item_brand': 'Brand A',
// Item-scoped custom parameters
'item_color': 'blue', // Item-scoped
'item_size': 'large', // Item-scoped
'supplier': 'Vendor_XYZ', // Item-scoped
'warehouse_location': 'US-WEST' // Item-scoped
},
{
'item_id': 'SKU_124',
'item_name': 'Red Shoes',
'price': 82.54,
'quantity': 1,
// Different item-scoped values for this product
'item_color': 'red', // Item-scoped
'item_size': '10', // Item-scoped
'supplier': 'Vendor_ABC', // Item-scoped
'warehouse_location': 'US-EAST' // Item-scoped
}
]
});
```
**Why Item-Scoped:**
- Each product has different color, size, supplier
- Attributes specific to individual items in cart
- Enables product-level analysis
#### Example 2: Custom Product Attributes
```javascript
gtag('event', 'add_to_cart', {
'currency': 'USD',
'value': 199.99,
'items': [
{
'item_id': 'LAPTOP_001',
'item_name': 'Gaming Laptop',
'price': 199.99,
'quantity': 1,
// Custom item-scoped parameters
'processor': 'Intel i7', // Item-scoped
'ram_gb': 16, // Item-scoped
'storage_type': 'SSD', // Item-scoped
'screen_size_inches': 15.6, // Item-scoped
'condition': 'new', // Item-scoped
'warranty_years': 2 // Item-scoped
}
]
});
```
**Why Item-Scoped:**
- Product specifications unique to this item
- Enables filtering/analysis by product attributes
- Helps understand what drives purchases
### Registering Item-Scoped Custom Dimensions
**Process:**
1. **Send Item Parameter in Items Array:**
```javascript
gtag('event', 'purchase', {
'items': [
{
'item_id': 'SKU_123',
'item_name': 'Product',
'custom_item_param': 'value' // Item-scoped
}
]
});
```
2. **Navigate to GA4 Admin:**
Admin → Data Display → Custom Definitions
3. **Create Custom Dimension:**
- **Dimension Name:** "Custom Item Attribute"
- **Scope:** **Item** ← Select Item
- **Event Parameter:** "custom_item_param"
- Description: What item attribute this tracks
- Click Save
4. **Wait 24-48 hours for data population**
### Item Scope Limits
**Standard GA4:**
- 10 item-scoped custom dimensions per property
- Maximum 27 items per event
**GA4 360:**
- 25 item-scoped custom dimensions per property
- Maximum 27 items per event
### Item Scope Best Practices
**DO:**
- Use for product-specific attributes
- Include in all ecommerce events (view_item, add_to_cart, purchase)
- Be consistent with parameter names across items
- Use for analysis/filtering products
**DON'T:**
- Exceed 27 items per event
- Use for user-level data (use user scope instead)
- Use for event-level data (use event scope instead)
- Forget to register item parameters as item-scoped dimensions
---
## Scope Comparison Table
| Aspect | Event Scope | User Scope | Item Scope |
|--------|------------|------------|------------|
| **Applies To** | Single event | All user events | Products in items array |
| **Lifespan** | One event | All sessions | One transaction |
| **Persistence** | No | Yes (until changed) | No |
| **Use Case** | Event details | User attributes | Product details |
| **Examples** | button_name, form_id | subscription_tier, user_type | item_color, item_size |
| **Max Dimensions (Standard)** | 50 | 25 | 10 |
| **Max Dimensions (GA4 360)** | 125 | 100 | 25 |
| **Set Method** | gtag('event', ...) | gtag('set', ...) | items array |
---
## Choosing the Right Scope
### Decision Framework
**Ask these questions:**
1. **Does this data describe the USER?**
- Examples: subscription_tier, customer_segment, years_customer
- **Scope:** User
- **Why:** Attribute of who the user is
2. **Does this data describe the EVENT/ACTION?**
- Examples: button_name, form_id, video_title
- **Scope:** Event
- **Why:** Specific to this interaction
3. **Does this data describe a PRODUCT?**
- Examples: item_color, item_size, supplier
- **Scope:** Item
- **Why:** Product-level detail in ecommerce
### Scope Selection Examples
#### Example 1: Form Tracking
```javascript
gtag('event', 'form_submit', {
// Event-scoped (describes THIS form submission)
'form_id': 'contact-form',
'form_type': 'lead_generation',
'form_location': 'footer',
// User-scoped (describes WHO submitted)
'user_tier': 'premium', // Set via gtag('set')
'account_age_days': 365 // Set via gtag('set')
});
```
#### Example 2: Ecommerce Purchase
```javascript
gtag('event', 'purchase', {
// Event-scoped (describes THIS transaction)
'transaction_id': 'TXN_123',
'value': 99.99,
'currency': 'USD',
'payment_method': 'credit_card',
// User-scoped (WHO made purchase) - set separately
// gtag('set', {'customer_lifetime_value': 5000})
// Item-scoped (WHAT was purchased)
'items': [
{
'item_id': 'SKU_123',
'item_color': 'blue', // Item-scoped
'item_size': 'large' // Item-scoped
}
]
});
```
#### Example 3: Video Tracking
```javascript
// User property (set once)
gtag('set', {
'user_subscription': 'premium' // User-scoped
});
// Video event
gtag('event', 'video_complete', {
// Event-scoped (describes THIS video watch)
'video_id': 'VID_123',
'video_title': 'GA4 Tutorial',
'video_duration': 1200,
'completion_percent': 100
});
```
---
## Common Scope Mistakes
### Mistake 1: Using Event Scope for User Attributes
```javascript
// ❌ WRONG - subscription_tier sent as event parameter
gtag('event', 'page_view', {
'subscription_tier': 'premium' // Will only apply to this event
});
// ✅ CORRECT - subscription_tier as user property
gtag('set', {
'subscription_tier': 'premium' // Applies to all events
});
```
### Mistake 2: Using User Scope for Event Details
```javascript
// ❌ WRONG - button_name as user property
gtag('set', {
'button_name': 'Subscribe' // Will apply to ALL events (incorrect)
});
// ✅ CORRECT - button_name as event parameter
gtag('event', 'button_click', {
'button_name': 'Subscribe' // Only applies to this click
});
```
### Mistake 3: Not Using Item Scope for Products
```javascript
// ❌ WRONG - product color as event parameter
gtag('event', 'purchase', {
'product_color': 'blue' // Can't handle multiple products
});
// ✅ CORRECT - product color in items array
gtag('event', 'purchase', {
'items': [
{
'item_id': 'SKU_123',
'item_color': 'blue' // Item-scoped, handles multiple products
}
]
});
```
### Mistake 4: Changing Scope After Registration
**Problem:** Cannot change scope after custom dimension is registered
```
Created dimension with Event scope
Realize it should be User scope
Cannot change scope
Must create NEW dimension
```
**Solution:** Plan scopes carefully before registering dimensions
---
## Scope Planning Checklist
Before implementing parameters:
- [ ] Identify all parameters to collect
- [ ] Determine scope for each parameter (event/user/item)
- [ ] Verify scope choice with decision framework
- [ ] Plan custom dimension registrations
- [ ] Check against scope limits (50 event, 25 user, 10 item)
- [ ] Document parameter scope decisions
- [ ] Test in DebugView before production
- [ ] Register dimensions with correct scope
- [ ] Verify data in reports after 24-48 hours
---
## Advanced Scope Patterns
### Pattern 1: Combining Scopes for Rich Context
```javascript
// 1. Set user properties (User scope)
gtag('set', {
'user_tier': 'enterprise',
'customer_segment': 'high_value'
});
// 2. Fire event with event parameters (Event scope)
gtag('event', 'purchase', {
'payment_method': 'invoice', // Event scope
'purchase_channel': 'phone', // Event scope
'items': [
{
'item_id': 'SKU_123',
'item_color': 'blue', // Item scope
'supplier': 'Vendor_A' // Item scope
}
]
});
// Result: Event has all three scopes of context
```
### Pattern 2: Dynamic User Property Updates
```javascript
// Update user property based on action
function updateUserEngagement(action) {
const engagementLevels = {
'page_view': 'low',
'form_submit': 'medium',
'purchase': 'high'
};
gtag('set', {
'engagement_level': engagementLevels[action]
});
}
// Call when engagement level changes
updateUserEngagement('purchase');
```
### Pattern 3: Item Scope with Custom Calculations
```javascript
gtag('event', 'purchase', {
'items': [
{
'item_id': 'SKU_123',
'price': 100,
'quantity': 2,
// Calculated item-scoped parameters
'profit_margin': calculateMargin(100, 60), // 40%
'stock_status': getStockStatus('SKU_123'), // 'in_stock'
'popularity_rank': getRank('SKU_123') // 5
}
]
});
```
---
## Additional Resources
- Official GA4 Scopes Documentation: https://support.google.com/analytics/answer/11396839
- Custom Dimensions Guide: https://support.google.com/analytics/answer/10075209
- User Properties: https://support.google.com/analytics/answer/9355671