digital-marketing7 min read

Web Analytics Tutorial: Learn Data Tracking from Scratch (2026)

Web Analytics Tutorial: Learn Data Tracking from Scratch (2026)

Published:  |  Category: Digital Marketing  |  Reading time: ~15 min
Web Analytics Tutorial: Learn Data Tracking from Scratch (2026)

I spent my first two years in marketing looking at dashboards every morning and feeling productive. Then I realized I was staring at page views without knowing what they meant. Web analytics is not about collecting data — it is about asking the right questions and finding answers. How do users actually move through your site? Why do they leave? Which channels deliver customers that stick? This tutorial covers Google Analytics 4, the analytics mindset, and the practical techniques for turning raw numbers into decisions that improve your business.

Google Analytics 4: Key Concepts

Google Analytics 4 (GA4) is the current generation of Google's analytics platform. Unlike Universal Analytics (which tracked sessions and page views), GA4 is event-based. Everything — a page view, a click, a scroll, a purchase — is an event. This model is more flexible and future-proof, especially for cross-platform tracking (web + app). The reporting interface is different from what most people are used to, with a focus on user-centric metrics rather than session-centric ones.

Key concepts include: users (unique visitors), events (interactions), parameters (additional data attached to events), and user properties (attributes like language or logged-in status). The default events include page_view, scroll, click, and session_start. You can create custom events for anything specific to your business — video completion, form submission, subscription start. GA4 uses predictive metrics like purchase probability and churn probability based on machine learning.

// GA4 event tracking: custom events
gtag('config', 'G-MEASUREMENT_ID');

gtag('event', 'newsletter_signup', {
  'source': 'blog_post',
  'post_title': 'SEO Guide 2026'
});

gtag('event', 'video_progress', {
  'video_title': 'Tutorial Intro',
  'percent_watched': 50
});

Setting Up GA4 and Event Tracking

Setting up GA4 is straightforward. Create a Google Analytics 4 property in your Google Analytics account, then add the measurement ID to your website via Google Tag Manager, a plugin (WordPress, Shopify), or directly in your site's head tag. The basic setup automatically captures page views, scrolls, outbound clicks, site search, and video engagement for embedded YouTube videos. You might need to enable enhanced measurement in the Admin panel to get some of these automatically.

For custom tracking, you will need to either use Google Tag Manager (recommended for non-developers) or add gtag() calls to your site's JavaScript. Define your key events — what actions matter to your business? A purchase, a lead form submission, a demo request, a free trial start. Each key event should have a corresponding tracking call. Test everything with GA4's DebugView or the Chrome extension Tag Assistant before deploying to production.



Understanding Key Metrics and Dimensions

GA4 organizes metrics into engagement (sessions, engaged sessions, engagement rate, average engagement time), acquisition (users by first touch channel, traffic source, campaign), monetization (purchases, revenue, average purchase revenue), and retention (new vs. returning users, cohort analysis). The engagement rate — percentage of sessions that lasted longer than 10 seconds or had a conversion event — is a better quality indicator than simple page views.

Dimensions are attributes that describe your data: page path, country, device category, source/medium, campaign name. The power of GA4 comes from slicing metrics by dimensions. For example, "What is the engagement rate on mobile vs. desktop?" or "Which marketing channel brings users with the highest average engagement time?" Learning to ask comparative questions is the skill that separates data lookers from data analysts.

// GA4 Data API: query engagement metrics by source
const {BetaAnalyticsDataClient} = require('@google-analytics/data');

const analyticsClient = new BetaAnalyticsDataClient();

async function getTopSources() {
  const [response] = await analyticsClient.runReport({
    property: 'properties/MEASUREMENT_ID',
    dateRanges: [{startDate: '30daysAgo', endDate: 'today'}],
    dimensions: [{name: 'sessionSource'}],
    metrics: [{name: 'engagedSessions'}, {name: 'sessions'}]
  });
  response.rows.forEach(row => {
    const source = row.dimensionValues[0].value;
    const engaged = row.metricValues[0].value;
    const total = row.metricValues[1].value;
    console.log(${source}: / engaged);
  });
}

Conversion Tracking and Goal Configuration

A conversion in GA4 is any event you mark as important. Go to Admin > Events and toggle the switch on events you want to count as conversions. Common conversion events include purchase, sign_up, login, and generate_lead. E-commerce businesses should set up the Enhanced Ecommerce plugin with dedicated events for add_to_cart, begin_checkout, add_shipping_info, add_payment_info, and purchase.

Attribution modeling determines how credit for a conversion is assigned across touchpoints. GA4 offers several models: last click (default), first click, linear, time decay, and position-based. Data-driven attribution uses Google's machine learning to distribute credit based on which channels actually influenced the conversion. Switch from last-click to data-driven attribution once you have enough data — it typically reveals that upper-funnel channels like organic search and social are more valuable than the last-click model suggests.

// GA4 e-commerce purchase event
gtag('event', 'purchase', {
  transaction_id: 'TXN_12345',
  value: 149.99,
  currency: 'USD',
  items: [
    { item_id: 'SKU_001', item_name: 'Running Shoes', price: 99.99, quantity: 1 },
    { item_id: 'SKU_002', item_name: 'Socks Pack', price: 50.00, quantity: 1 }
  ]
});

Segmentation and Cohort Analysis

Segments let you isolate subsets of your data for analysis. GA4 offers user segments (based on user-level conditions like "users who purchased"), session segments (based on session-level conditions like "sessions from paid traffic"), and event segments (based on specific event parameters). Create segments for high-value users (top 10% by revenue), new users vs. returning, mobile users, or users from a specific campaign.

Cohort analysis groups users by the date of their first visit and tracks their behavior over subsequent periods. For example, you might create a weekly cohort of users who signed up in June and track how many return in July, August, and September. This reveals retention patterns that overall averages hide. If June's cohort retains better than July's, something changed — maybe your onboarding improved or a traffic source quality shifted. Cohort analysis is one of the most underused features in GA4.

# GA4 cohort analysis data structure
cohorts = [
    {"week": "Week 1", "new_users": 1000, "retention_w1": 100, "retention_w2": 80, "retention_w3": 65},
    {"week": "Week 2", "new_users": 1100, "retention_w1": 105, "retention_w2": 85, "retention_w3": 70},
    {"week": "Week 3", "new_users": 950, "retention_w1": 90, "retention_w2": 72, "retention_w3": 58}
]

for c in cohorts:
    r1 = round(c["retention_w1"] / c["new_users"] * 100, 1)
    print(f"{c['week']}: {c['new_users']} users -> {r1}% retained week 1")

Building Actionable Dashboards

A good dashboard answers specific questions at a glance. It does not show every available metric. Start with your business objectives and work backward. If your goal is e-commerce revenue, build a dashboard with: revenue (today vs. same day last week), conversion rate, average order value, traffic by source, and top-selling products. If your goal is lead generation: leads, cost per lead, lead-to-opportunity rate, and traffic-to-lead conversion rate by source.

Use GA4's Explore section to build custom reports. The Free Form report is a pivot table you can configure with any dimensions and metrics. The Funnel Exploration report visualizes how users drop off between steps (e.g., product page -> cart -> checkout -> purchase). The Path Exploration report shows the sequences of pages and events users go through before converting. Share automated reports via email weekly to keep your team informed without pulling data manually.

// Dashboard data aggregation endpoint (Node.js)
app.get('/api/dashboard', async (req, res) => {
  const [sessions, revenue, topPages] = await Promise.all([
    getMetric('sessions', 'today', 'today'),
    getMetric('totalRevenue', 'today', 'today'),
    getTopContent('pageTitle', 'screenPageViews', 5)
  ]);
  
  res.json({
    date: new Date().toISOString().split('T')[0],
    sessions: sessions,
    revenue: revenue,
    topContent: topPages
  });
});

Frequently Asked Questions

What is the difference between GA4 and Universal Analytics?

GA4 is event-based while Universal Analytics was session-based. GA4 tracks users across devices and platforms, uses machine learning for predictive metrics, and offers more flexible reporting. Universal Analytics stopped processing new data on July 1, 2024, so everyone has needed to migrate.

Do I need a cookie banner if I use GA4?

Yes, in most cases. GDPR in Europe, CCPA in California, and similar laws worldwide require you to get user consent before setting tracking cookies. GA4 offers consent mode, which adjusts tracking behavior based on user consent choices. Always work with a legal professional to ensure compliance.

What is the most important web analytics metric?

It depends on your business model. For e-commerce, conversion rate and average order value. For SaaS, activation rate and monthly recurring revenue. For content sites, engagement rate and pages per session. The universal answer is: the metric that most directly measures progress toward your business goal.

How do I know if my data is accurate?

Cross-check GA4 data with your actual business records. Compare reported revenue to your payment processor's records. Use DebugView to verify events fire correctly. Check for spam traffic (often from bot farms or referral spam) and filter it out. No analytics data is 100% accurate, but it should be directionally correct.

Originally published on Ayodhyyya. Last updated June 1, 2026.