Skip to content

Monitoring Site Traffic with GA4

Publishing a documentation site is only the first step — understanding how users interact with your docs is what enables continuous improvement. Google Analytics 4 (GA4) is Google’s latest analytics platform, featuring an event-driven tracking model. It’s free, powerful, and privacy-conscious. This section walks you through registering, integrating, interpreting data, and making data-driven decisions with GA4.

Q: What is GA4 and how does it differ from Universal Analytics?

Section titled “Q: What is GA4 and how does it differ from Universal Analytics?”

A: GA4 (Google Analytics 4) replaced Universal Analytics (UA) in 2023. Key differences:

Aspect Universal Analytics (UA) GA4
Tracking Model Session-based Event-based
Data Streams Web only Web + App unified streams
Cross-device Limited Native (via Google Signals)
Privacy Cookie-dependent Cookieless modeling + Consent Mode
Reports Classic views Event-centric reports
Predictions None AI-powered purchase/churn probability
Free Tier Sampling limits More generous, free BigQuery export

All new Google Analytics properties are GA4 by default.

A: Follow these steps:

  1. Sign in to Google Analytics: Visit analytics.google.com and sign in with your Google account

  2. Create a property:

    • Click the Admin gear icon (bottom-left)
    • Select “Create” → “Property”
    • Enter a property name (e.g., “ESP32 IoT Tutorial Docs”)
    • Choose your timezone and currency
    • Click “Next” to complete creation
  3. Get your Measurement ID:

    • After creation, go to “Data Streams”
    • Click your “Web” data stream
    • You’ll see a G-XXXXXXXXXX Measurement ID — this is what you integrate into your site

[!TIP] Store your Measurement ID as an environment variable (e.g., PUBLIC_GA_ID) rather than hardcoding it. This lets you use different IDs for different environments (dev/production), preventing test traffic from polluting production stats.

Q: How do I integrate GA4 into my Starlight documentation site?

Section titled “Q: How do I integrate GA4 into my Starlight documentation site?”

A: Inject the gtag script via Starlight’s head configuration in astro.config.mjs:

const gaId = process.env.PUBLIC_GA_ID || 'G-XXXXXXXXXX';
export default defineConfig({
site: 'https://docs.yourcompany.com',
integrations: [
starlight({
title: 'My Docs',
head: gaId
? [
{
tag: 'script',
attrs: {
async: true,
src: `https://www.googletagmanager.com/gtag/js?id=${gaId}`,
},
},
{
tag: 'script',
content: `window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${gaId}');`,
},
]
: [],
}),
],
});

Code breakdown:

  • Conditional injection: gaId ? [...] : [] ensures no script is injected when no ID is set (e.g., local development)
  • Async loading: async: true doesn’t block page rendering
  • gtag('config', ...): Automatically tracks page views (page_view events)

After deployment, you should see real-time data in GA4 within 5-30 minutes.

Q: How do I configure GA4 environment variables in Vercel?

Section titled “Q: How do I configure GA4 environment variables in Vercel?”

A: In the Vercel dashboard:

  1. Go to your project → Settings → Environment Variables
  2. Add the variable:
    • Name: PUBLIC_GA_ID
    • Value: G-M648KX24EK (replace with your Measurement ID)
    • Environments: Select Production only
  3. Redeploy to apply the environment variable

[!NOTE] Environment variables prefixed with PUBLIC_ are exposed to the client in Astro — this is necessary for the gtag script. Never put sensitive information (API keys, secrets) in PUBLIC_ variables.

Q: Which GA4 reports are most valuable for documentation sites?

Section titled “Q: Which GA4 reports are most valuable for documentation sites?”

A: Focus on these key reports:

1. Realtime Report

  • Location: GA4 sidebar → Reports → Realtime
  • Use case: Check if users are browsing immediately after publishing new content
  • Key metrics: Active users now, popular pages, user geography

2. Pages and Screens

  • Location: Reports → Engagement → Pages and screens
  • Use case: Understand which documentation pages get the most traffic
  • Key metrics:
Metric Meaning Action
Views Total times a page was viewed Identify popular and neglected content
Active users Unique users who viewed the page Measure actual content reach
Average engagement time Time users actively spent on page Long = valuable; Short = needs improvement
Bounce rate % of users who left after one page High bounce = landing page needs work

3. Traffic Acquisition

  • Location: Reports → Acquisition → Traffic acquisition
  • Use case: Understand where users come from
  • Common channels:
    • Organic Search: From Google/Bing (measures SEO effectiveness)
    • Direct: Typed URL directly (measures brand awareness)
    • Referral: From links on other sites (measures backlinks)
    • Organic Social: From social media (measures social reach)

4. Retention

  • Location: Reports → Retention
  • Use case: Measure whether users come back (long-term quality indicator)
Section titled “Q: How do I see which specific doc pages are most popular?”

A: In the Pages and Screens report, filter by path:

  1. Go to Reports → Engagement → Pages and screens
  2. Select “Page path and screen class” as the dimension
  3. You’ll see data like:
Page Path Views Users Avg. Engagement
/introduction/ 1,234 890 3m 12s
/esp32-development-basics/01/ 987 654 5m 45s
/mqtt-protocol/03/ 876 543 4m 22s
/zh/introduction/ 654 432 2m 56s

How to use this data:

  • High views + long engagement: These are “core content” — prioritize maintenance and updates
  • High views + short engagement: Users arrive but don’t read deeply — check if content is too complex or poorly structured
  • Low views: Consider better internal linking or SEO optimization

Q: How do I track search usage on my documentation site?

Section titled “Q: How do I track search usage on my documentation site?”

A: Pagefind searches aren’t tracked by GA4 by default, but you can add custom event tracking:

Create a custom script (e.g., public/analytics.js):

// Track Pagefind search events
document.addEventListener('DOMContentLoaded', () => {
const searchInput = document.querySelector('.pagefind-ui__search-input');
if (searchInput && typeof gtag !== 'undefined') {
let debounce;
searchInput.addEventListener('input', (e) => {
clearTimeout(debounce);
debounce = setTimeout(() => {
const query = e.target.value;
if (query.length >= 2) {
gtag('event', 'search', {
search_term: query,
});
}
}, 500);
});
}
});

Then include it in the head configuration:

head: [
// ... gtag scripts ...
{
tag: 'script',
attrs: { src: '/analytics.js', defer: true },
},
]

After setup, check GA4 → Reports → Engagement → Events for the “search” event. Search terms reveal what users are looking for — invaluable for improving documentation structure and content.

Q: How do I set up custom events to track documentation interactions?

Section titled “Q: How do I set up custom events to track documentation interactions?”

A: GA4’s event-driven model lets you track any user behavior. Common scenarios:

Track code block copies:

document.addEventListener('click', (e) => {
const copyBtn = e.target.closest('button[aria-label*="Copy"]');
if (copyBtn && typeof gtag !== 'undefined') {
const codeBlock = copyBtn.closest('starlight-code-block') || copyBtn.closest('pre');
const lang = codeBlock?.getAttribute('data-language') || 'unknown';
gtag('event', 'code_copy', {
language: lang,
});
}
});

Track language switching:

document.querySelectorAll('[data-astro-cid]').forEach((el) => {
el.addEventListener('click', () => {
const href = el.getAttribute('href');
if (href?.startsWith('/zh/') && typeof gtag !== 'undefined') {
gtag('event', 'language_switch', {
target_language: 'zh-CN',
});
}
});
});

View custom event data in GA4 → Admin → Custom events or Explore.

Q: How do I set up conversion events for my docs site?

Section titled “Q: How do I set up conversion events for my docs site?”

A: For documentation sites, these behaviors make good conversion events:

Event Name Trigger Significance
doc_completed User scrolls to bottom of long doc Measures content completion rate
code_copy User copies a code block Measures code example usefulness
external_link_click User clicks external link (e.g., GitHub) Measures documentation guidance effectiveness
search User performs site search Measures search feature usage

Setup steps:

  1. GA4 → Admin → Events → Create event
  2. Enter event name and matching conditions
  3. Mark the event as a conversion in the “Conversions” section

Q: How do I exclude my team’s visits from analytics?

Section titled “Q: How do I exclude my team’s visits from analytics?”

A: Frequent visits from your development team will pollute analytics data. Exclude them:

  1. By IP address:

    • GA4 → Admin → Data streams → Select your Web stream
    • Click “Configure tag settings” → “Internal traffic”
    • Define IP address ranges for internal traffic
    • Activate the exclusion in “Data filters”
  2. By cookie (more flexible):

    • Add a condition to your gtag config:
    if (!document.cookie.includes('no_analytics=true')) {
    gtag('config', 'G-XXXXXXXXXX');
    }
    • Team members run document.cookie = "no_analytics=true" in the browser console to opt out

A:

Report Type Delay
Realtime Seconds
Standard reports (pages, traffic, etc.) 24-48 hours
Explore reports 24-48 hours
BigQuery export ~24 hours

If you just deployed, check the Realtime report first to confirm gtag is working, then view full data the next day.

Q: How do I optimize documentation based on GA4 data?

Section titled “Q: How do I optimize documentation based on GA4 data?”

A: Follow a data-driven content optimization cycle:

Observe data → Identify issues → Optimize content → Verify results

Action guide:

Data Signal Possible Cause Optimization Action
High views but high bounce rate Content too complex or poorly structured Add TOC, break into steps, add examples
Declining views over time SEO ranking dropped or content outdated Update content, add keywords, optimize titles
Search queries concentrated on a topic Missing related content in docs Create a dedicated topic page
One language version has far fewer views Poor translation quality or incomplete Complete translations, improve translation quality
Many code copies but no downstream conversions Code examples may have errors Verify code example correctness

After integrating GA4, verify with these steps:

  1. Local verification: Run npm run dev, open browser DevTools → Network, search for gtag to confirm the script loaded
  2. GA DebugView: In GA4 → Admin → DebugView, install the Google Analytics Debugger Chrome extension to see events fire in real-time
  3. Realtime report: After deploying to production, open GA4 Realtime report and confirm active users appear within 5 minutes
  4. Event verification: Trigger search, code copy, etc. on the page and check GA4 DebugView for corresponding events

After mastering GA4 monitoring, explore further:

  • Link GA4 with Google Search Console to analyze search keywords driving traffic
  • Export raw data to BigQuery for deep analysis
  • Set up GA4 custom alerts for automatic notifications on traffic anomalies

Building a commercial IoT product?

We provide ESP32 ODM design-to-manufacturing services. From prototype to production — the team behind this tutorial can build it with you.

💡 Mention tutorial.imagrove.com in your Alibaba chat with us — get 10% off your custom project quote.

Talk to us →

First published attutorial.imagrove.com/building-doc-sites/10-monitoring-site-traffic-with-ga4/Please credit Imagrove and link back to this page when quoting or republishing.

Questions or issues with this tutorial?

Sign in with GitHub to leave a comment. If a step fails for you, tell us — we verify it and update the tutorial.