Google Analytics Event Tracking
Overview
Google Analytics 4 (GA4) is built on an event-based data model, a fundamental shift from Universal Analytics' session-based approach. In GA4, every user interaction is captured as an event, whether it's a page view, button click, video play, or purchase. This flexible model allows you to measure virtually any user behavior and build sophisticated analyses around how people interact with your website or app.
Unlike Universal Analytics where events were optional add-ons to pageview tracking, GA4 treats everything as an event. This means you get richer data by default and more flexibility in how you structure your measurement strategy.
Event Model
How GA4 Events Work
Every event in GA4 consists of:
- Event name: A descriptive identifier (e.g.,
page_view,purchase,button_click) - Event parameters: Additional details about the event (e.g.,
page_location,currency,value) - User properties: Attributes that describe the user (e.g.,
age,gender,user_id) - Timestamp: Automatically captured when the event fires
Events can have up to 25 parameters, and each parameter can be a string, number, or array. Parameters provide context that helps you understand what happened during the event.
Event Limitations
- Event name: Maximum 40 characters, must start with a letter
- Parameter name: Maximum 40 characters
- Parameter value: Maximum 100 characters for string values
- Unique events: 500 distinct event names per property
- Custom parameters: 25 parameters per event
Standard Events
GA4 includes several automatically collected and recommended events. These are optimized for reporting and don't count against your custom event quota.
Automatically Collected Events
These events are captured without any additional code:
first_visit: First time a user visits your sitesession_start: Beginning of a user sessionpage_view: User views a page (web only)screen_view: User views a screen (app only)user_engagement: Fires when user is actively engagedscroll: User scrolls to bottom (90%) of a page
Enhanced Measurement Events
Enable these in the GA4 interface without code changes:
click: Outbound link clicksview_search_results: Site search performedvideo_start,video_progress,video_complete: Video engagementfile_download: Downloads of common file types (.pdf, .xlsx, .docx, etc.)form_start,form_submit: Form interactions
Recommended Events
Google provides predefined event names for common actions. Using these ensures better integration with GA4 reports:
General Events:
login: User signs insign_up: User creates accountsearch: User performs searchshare: User shares contentgenerate_lead: Lead form submission
Content & Engagement:
select_content: User selects contentview_item: User views item detailsview_item_list: User views list of items
Custom Events
Creating Custom Events
Custom events let you track interactions specific to your business. You can create them via:
1. gtag.js (Direct Implementation)
// Basic custom event
gtag('event', 'button_click', {
'button_name': 'cta_homepage',
'section': 'hero'
});
// Event with value
gtag('event', 'newsletter_signup', {
'method': 'popup',
'value': 10
});
2. Google Tag Manager
Create a Custom Event trigger and GA4 Event tag:
- Trigger: Custom Event with event name (e.g.,
buttonClick) - Tag: GA4 Event with Event Name and parameters
- Parameters can pull from Data Layer variables
// Push to dataLayer
dataLayer.push({
'event': 'buttonClick',
'buttonName': 'cta_homepage',
'buttonLocation': 'hero'
});
3. Measurement Protocol (Server-Side)
POST https://www.google-analytics.com/mp/collect?
measurement_id=G-XXXXXXXXXX&api_secret=SECRET
{
"client_id": "client_id_here",
"events": [{
"name": "custom_event",
"params": {
"parameter1": "value1",
"parameter2": "value2"
}
}]
}
Event Naming Best Practices
- Use lowercase with underscores:
button_click, notButtonClickorbutton-click - Be descriptive but concise:
download_whitepapervsdwn_wp - Group related events with prefixes:
video_start,video_pause,video_complete - Avoid special characters and spaces
Ecommerce Events
GA4 has a complete ecommerce event schema for tracking the customer journey from product discovery to purchase.
Core Ecommerce Events
Discovery & Browsing:
// View item list (category page, search results)
gtag('event', 'view_item_list', {
item_list_id: 'related_products',
item_list_name: 'Related Products',
items: [
{
item_id: 'SKU_12345',
item_name: 'Blue T-Shirt',
price: 29.99,
item_category: 'Apparel',
quantity: 1
}
]
});
// View item details
gtag('event', 'view_item', {
currency: 'USD',
value: 29.99,
items: [{
item_id: 'SKU_12345',
item_name: 'Blue T-Shirt',
price: 29.99,
item_category: 'Apparel'
}]
});
Cart Actions:
// Add to cart
gtag('event', 'add_to_cart', {
currency: 'USD',
value: 29.99,
items: [{
item_id: 'SKU_12345',
item_name: 'Blue T-Shirt',
price: 29.99,
quantity: 1
}]
});
// Remove from cart
gtag('event', 'remove_from_cart', {
currency: 'USD',
value: 29.99,
items: [{ /* item details */ }]
});
Checkout Process:
// Begin checkout
gtag('event', 'begin_checkout', {
currency: 'USD',
value: 79.97,
items: [
{ /* item 1 */ },
{ /* item 2 */ }
]
});
// Add payment info
gtag('event', 'add_payment_info', {
currency: 'USD',
value: 79.97,
payment_type: 'Credit Card',
items: [{ /* items */ }]
});
// Add shipping info
gtag('event', 'add_shipping_info', {
currency: 'USD',
value: 79.97,
shipping_tier: 'Standard',
items: [{ /* items */ }]
});
Purchase:
gtag('event', 'purchase', {
transaction_id: 'T_12345',
value: 79.97,
tax: 6.40,
shipping: 5.00,
currency: 'USD',
coupon: 'SUMMER_SALE',
items: [{
item_id: 'SKU_12345',
item_name: 'Blue T-Shirt',
price: 29.99,
quantity: 1,
item_category: 'Apparel',
item_variant: 'Blue',
item_brand: 'MyBrand'
}]
});
Refunds:
gtag('event', 'refund', {
transaction_id: 'T_12345',
value: 29.99,
currency: 'USD',
items: [{
item_id: 'SKU_12345',
quantity: 1
}]
});
User Properties
User properties describe segments of your user base. They persist across sessions and help you analyze behavior by user attributes.
Setting User Properties
// Set user properties
gtag('set', 'user_properties', {
'user_type': 'premium',
'account_age': '6_months',
'favorite_category': 'electronics',
'lifetime_value_tier': 'high'
});
Default User Properties
GA4 automatically collects:
- Age, Gender, Interests (when Google signals enabled)
- Device category, browser, OS
- Geographic location (city, country)
- Language
Custom User Properties
You can create up to 25 custom user properties. Common examples:
subscription_status: free, trial, premiumuser_role: admin, editor, viewersignup_date: cohort analysispreferred_language: localization insights
Event Parameters
Parameters add context to events. GA4 supports built-in parameters and custom parameters.
Standard Parameters
These work out-of-the-box in GA4 reports:
currency: ISO 4217 currency code (USD, EUR, etc.)value: Numeric value of the eventtransaction_id: Unique identifier for purchasesitems: Array of item objects for ecommercesearch_term: Query used in searchcontent_type: Type of contentitem_id: Product/content identifier
Custom Parameters
gtag('event', 'video_engagement', {
'video_title': 'Product Demo 2024',
'video_duration': 180,
'video_percent_watched': 75,
'video_provider': 'youtube'
});
Registering Custom Dimensions & Metrics
To use custom parameters in standard reports:
- Go to Admin > Custom Definitions
- Click Create custom dimension or Create custom metric
- Enter dimension/metric name
- Select scope (Event, User, or Item)
- Enter parameter name (must match event parameter)
Example:
- Dimension name: Video Title
- Scope: Event
- Event parameter:
video_title
Implementation Methods
1. Google Tag Manager (Recommended)
Pros:
- No code deployments needed for changes
- Version control and testing
- Easier collaboration between marketing and dev
- Built-in debugging tools
Setup:
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');</script>
2. gtag.js (Direct Implementation)
Pros:
- Lighter weight
- Direct control
- Faster page loads (fewer redirects)
Setup:
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>
3. Firebase SDK (Mobile Apps)
iOS (Swift):
Analytics.logEvent("level_complete", parameters: [
"level_name": "Beach World",
"character": "Mario",
"success": true
])
Android (Kotlin):
firebaseAnalytics.logEvent("level_complete") {
param("level_name", "Beach World")
param("character", "Mario")
param("success", true)
}
4. Measurement Protocol (Server-Side)
For tracking server-side events, offline conversions, or CRM integrations:
import requests
def send_ga4_event(client_id, event_name, params):
url = "https://www.google-analytics.com/mp/collect"
payload = {
"client_id": client_id,
"events": [{
"name": event_name,
"params": params
}]
}
requests.post(
url,
params={
"measurement_id": "G-XXXXXXXXXX",
"api_secret": "your_api_secret"
},
json=payload
)
Debugging & Validation
1. DebugView
Real-time event debugging in GA4:
- Enable debug mode:
// gtag.js
gtag('config', 'G-XXXXXXXXXX', {
'debug_mode': true
});
// GTM - add this to dataLayer
dataLayer.push({'debug_mode': true});
- Navigate to Admin > DebugView
- Perform actions on your site
- See events appear in real-time with full parameter details
2. Google Tag Assistant
Browser extension for Chrome:
- Validates GA4 implementation
- Shows events firing in real-time
- Identifies configuration errors
- Tests before deployment
3. GTM Preview Mode
For Google Tag Manager implementations:
- Click Preview in GTM workspace
- Enter your website URL
- See which tags fire on each interaction
- Debug variable values and trigger conditions
4. Chrome DevTools
Monitor network requests:
1. Open DevTools (F12)
2. Go to Network tab
3. Filter by "collect" or "gtm"
4. Trigger events on your site
5. Inspect request payload
Look for:
https://www.google-analytics.com/g/collect(gtag.js)https://www.google-analytics.com/j/collect(gtm.js)
5. Realtime Report
Check Reports > Realtime to see:
- Events in the last 30 minutes
- Which pages are active
- Traffic sources
- Conversions
Not as detailed as DebugView but useful for production validation.
Best Practices
Event Naming & Structure
✅ Do:
- Use snake_case for event names
- Be consistent across your property
- Use Google's recommended events when applicable
- Document your event taxonomy
- Limit to 500 unique event names
❌ Don't:
- Use spaces or special characters
- Create redundant events (e.g.,
button_click_homepageandhomepage_button_click) - Include dynamic values in event names
- Use overly generic names like
clickorevent
Parameter Usage
✅ Do:
- Put variable data in parameters, not event names
- Register important custom parameters as custom dimensions
- Use standard parameter names when possible
- Include
valueandcurrencyfor conversion events - Keep parameter values under 100 characters
❌ Don't:
- Create parameters you won't use in analysis
- Send PII (personally identifiable information)
- Exceed 25 parameters per event
- Use inconsistent parameter naming
Conversion Tracking
- Mark key events as conversions: Admin > Events > Toggle "Mark as conversion"
- Include value when possible: Helps calculate ROI
- Use consistent transaction_ids: Prevents duplicate purchases
- Test before launch: Use DebugView to validate
Privacy & Compliance
✅ Do:
- Implement consent mode for GDPR/CCPA
- Hash PII before sending (if absolutely necessary)
- Configure data retention settings appropriately
- Document what data you collect
- Use IP anonymization where required
❌ Don't:
- Send email addresses, phone numbers, names in parameters
- Ignore consent requirements
- Collect data without user knowledge
- Assume default settings are compliant
Performance Optimization
- Load GA4 asynchronously
- Batch events when possible (Measurement Protocol)
- Avoid sending events on every scroll/mousemove
- Use GTM's built-in variables instead of custom JavaScript when possible
- Implement error handling for tracking code
Testing & Quality Assurance
- Development environment: Test with debug mode enabled
- Staging environment: Validate full user journeys
- Production monitoring: Set up alerts for tracking failures
- Regular audits: Monthly check of event volume and data quality
- Documentation: Maintain a measurement plan
Data Quality
- Implement filters to exclude internal traffic (Admin > Data Filters)
- Create test properties for development
- Use referral exclusions to prevent session breaks
- Monitor event count reports for anomalies
- Set up custom alerts for tracking issues
Reporting & Analysis
- Create custom explorations for deep dives
- Use Audiences for retargeting
- Connect to BigQuery for SQL analysis
- Build custom reports for stakeholders
- Link to Google Ads for campaign optimization
Additional Resources: