analytics and events ga4



Google Analytics 4 (GA4) uses an event-based data model. This guide will teach you how to set up events, track user interactions, and configure analytics for comprehensive website measurement.
Understanding GA4 Events
Event-Based Model:
GA4 tracks everything as events:
- Page views
- Button clicks
- Form submissions
- Video plays
- File downloads
- Custom interactions
Event Structure:
Event Name
↓
Event Parameters
- Parameter 1: Value
- Parameter 2: Value
- etc.
Setting Up GA4
Step 1: Create GA4 Property
Process:
- Go to analytics.google.com
- Admin → Create Property
- Choose GA4
- Complete setup
- Get Measurement ID
Step 2: Install GA4 Tag
Google Tag Manager:
- Create GA4 Configuration tag
- Add Measurement ID
- Set trigger: All Pages
- Publish container
Direct Installation:
<!-- 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>
Next.js Implementation:
// app/layout.js
import Script from 'next/script';
export default function RootLayout({ children }) {
return (
<html>
<head>
<Script
src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"
strategy="afterInteractive"
/>
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
`}
</Script>
</head>
<body>{children}</body>
</html>
);
}
Automatic Events
GA4 Tracks Automatically:
1. page_view:
- Triggered on page load
- Includes page data
- No setup needed
2. scroll:
- 90% scroll depth
- Automatic tracking
- Can configure threshold
3. click:
- Outbound link clicks
- File downloads
- Can configure
4. view_search_results:
- Site search
- Automatic if configured
5. video_start, video_progress, video_complete:
- YouTube embeds
- Automatic tracking
Enhanced Measurement
Enable Enhanced Measurement:
In GA4:
- Admin → Data Streams
- Click stream
- Toggle Enhanced Measurement
- Configure events
Events Included:
- Scrolls
- Outbound clicks
- Site search
- Video engagement
- File downloads
Configuration:
gtag('config', 'G-XXXXXXXXXX', {
// Enable enhanced measurement
send_page_view: true,
// Configure scroll tracking
scroll_depth_threshold: [25, 50, 75, 90],
// Configure file downloads
file_downloads: true,
// Configure outbound links
outbound_links: true
});
Custom Events
Setting Up Custom Events:
1. Button Click Event:
// Track button click
document.getElementById('cta-button').addEventListener('click', () => {
gtag('event', 'button_click', {
'button_name': 'Get Started',
'button_location': 'Hero Section',
'page_path': window.location.pathname
});
});
2. Form Submission Event:
document.getElementById('contact-form').addEventListener('submit', (e) => {
gtag('event', 'form_submit', {
'form_name': 'Contact Form',
'form_location': 'Contact Page',
'form_id': 'contact-form'
});
});
3. Video Play Event:
const video = document.getElementById('video');
video.addEventListener('play', () => {
gtag('event', 'video_play', {
'video_title': 'Product Demo',
'video_duration': video.duration,
'video_current_time': video.currentTime
});
});
4. Download Event:
document.querySelectorAll('a[download]').forEach(link => {
link.addEventListener('click', () => {
gtag('event', 'file_download', {
'file_name': link.download,
'file_extension': link.href.split('.').pop(),
'link_url': link.href
});
});
});
E-commerce Events
Purchase Event:
gtag('event', 'purchase', {
'transaction_id': 'T12345',
'value': 99.99,
'currency': 'USD',
'items': [
{
'item_id': 'SKU123',
'item_name': 'Product Name',
'category': 'Category',
'quantity': 1,
'price': 99.99
}
]
});
Add to Cart Event:
gtag('event', 'add_to_cart', {
'currency': 'USD',
'value': 99.99,
'items': [{
'item_id': 'SKU123',
'item_name': 'Product Name',
'category': 'Category',
'quantity': 1,
'price': 99.99
}]
});
Begin Checkout Event:
gtag('event', 'begin_checkout', {
'currency': 'USD',
'value': 199.98,
'items': [/* items array */]
});
Conversion Events
Marking Events as Conversions:
In GA4:
- Admin → Events
- Find event
- Toggle "Mark as conversion"
- Save
Programmatically:
gtag('event', 'purchase', {
'transaction_id': 'T12345',
'value': 99.99,
'currency': 'USD'
// Automatically marked as conversion if configured
});
Common Conversion Events:
- purchase
- sign_up
- generate_lead
- add_to_cart
- begin_checkout
- subscribe
- complete_registration
Event Parameters
Standard Parameters:
Common Parameters:
value: Numeric valuecurrency: Currency codeitems: Array of itemspage_title: Page titlepage_location: Page URLpage_path: Page path
Custom Parameters:
gtag('event', 'custom_event', {
'custom_parameter_1': 'value1',
'custom_parameter_2': 'value2',
'custom_number': 123
});
User Properties
Setting User Properties:
gtag('set', 'user_properties', {
'user_type': 'premium',
'subscription_status': 'active',
'account_age_days': 365
});
Debugging Events
DebugView:
Enable:
- Install Google Analytics Debugger extension
- Or add debug_mode parameter
- View events in real-time
Debug Mode:
gtag('config', 'G-XXXXXXXXXX', {
'debug_mode': true
});
Testing Events:
Browser Console:
// Check if events are firing
console.log('Event sent:', eventName, parameters);
GA4 DebugView:
- Real-time event monitoring
- See events as they fire
- Verify parameters
- Check for errors
Best Practices
1. Consistent Naming
Conventions:
- Use snake_case
- Be descriptive
- Keep consistent
- Document events
Examples:
button_clickform_submitvideo_playfile_download
2. Meaningful Parameters
Guidelines:
- Include context
- Use standard parameters
- Add custom when needed
- Keep it relevant
3. Test Before Launch
Testing:
- Use DebugView
- Verify all events
- Check parameters
- Test on different pages
4. Document Events
Documentation:
- Event names
- Parameters
- Triggers
- Purpose
Common Events Setup
1. Contact Form:
document.getElementById('contact-form').addEventListener('submit', (e) => {
gtag('event', 'generate_lead', {
'form_name': 'Contact Form',
'form_location': window.location.pathname,
'value': 0
});
});
2. Newsletter Signup:
document.getElementById('newsletter-form').addEventListener('submit', (e) => {
gtag('event', 'sign_up', {
'method': 'newsletter',
'value': 0
});
});
3. Button Clicks:
document.querySelectorAll('.cta-button').forEach(button => {
button.addEventListener('click', () => {
gtag('event', 'button_click', {
'button_text': button.textContent,
'button_location': button.closest('section').id,
'page_path': window.location.pathname
});
});
});
Advanced Tracking
1. Scroll Depth:
let maxScroll = 0;
window.addEventListener('scroll', () => {
const scrollPercent = Math.round(
(window.scrollY / (document.documentElement.scrollHeight - window.innerHeight)) * 100
);
if (scrollPercent > maxScroll) {
maxScroll = scrollPercent;
// Track milestones
if ([25, 50, 75, 90].includes(scrollPercent)) {
gtag('event', 'scroll', {
'scroll_depth': scrollPercent
});
}
}
});
2. Time on Page:
let startTime = Date.now();
window.addEventListener('beforeunload', () => {
const timeOnPage = Math.round((Date.now() - startTime) / 1000);
gtag('event', 'time_on_page', {
'time_seconds': timeOnPage,
'page_path': window.location.pathname
});
});
3. Error Tracking:
window.addEventListener('error', (e) => {
gtag('event', 'exception', {
'description': e.message,
'fatal': false,
'error_url': window.location.href
});
});
Reporting and Analysis
Key Reports:
1. Events Report:
- All events
- Event counts
- Parameters
- Trends
2. Conversions Report:
- Conversion events
- Conversion rates
- Revenue
- Attribution
3. Engagement Report:
- User engagement
- Session quality
- Active users
- Retention
Implementation Checklist
- [ ] GA4 property created
- [ ] Measurement ID obtained
- [ ] GA4 tag installed
- [ ] Enhanced measurement enabled
- [ ] Custom events configured
- [ ] Conversion events marked
- [ ] E-commerce tracking (if applicable)
- [ ] Testing completed
- [ ] DebugView verified
- [ ] Documentation created
Next Steps
- Set Up GA4: Create property and install tag
- Enable Enhanced Measurement: Automatic tracking
- Add Custom Events: Track important interactions
- Mark Conversions: Identify key events
- Test Thoroughly: Verify all tracking
- Monitor Performance: Review reports regularly
Thanks for reading the blog. If you want more help, do contact us at https://sdx.vision