Monitoring Site Traffic with GA4
Monitoring Site Traffic with GA4
Section titled “Monitoring Site Traffic with GA4”Overview
Section titled “Overview”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.
Q: How do I create a GA4 property?
Section titled “Q: How do I create a GA4 property?”A: Follow these steps:
-
Sign in to Google Analytics: Visit analytics.google.com and sign in with your Google account
-
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
-
Get your Measurement ID:
- After creation, go to “Data Streams”
- Click your “Web” data stream
- You’ll see a
G-XXXXXXXXXXMeasurement 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: truedoesn’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:
- Go to your project → Settings → Environment Variables
- Add the variable:
- Name:
PUBLIC_GA_ID - Value:
G-M648KX24EK(replace with your Measurement ID) - Environments: Select Production only
- Name:
- 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) inPUBLIC_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)
Q: How do I see which specific doc pages are most popular?
Section titled “Q: How do I see which specific doc pages are most popular?”A: In the Pages and Screens report, filter by path:
- Go to Reports → Engagement → Pages and screens
- Select “Page path and screen class” as the dimension
- 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 56sHow 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 eventsdocument.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:
- GA4 → Admin → Events → Create event
- Enter event name and matching conditions
- 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:
-
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”
-
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
Q: How long before I see data in GA4?
Section titled “Q: How long before I see data in GA4?”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 resultsAction 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 |
Verification
Section titled “Verification”After integrating GA4, verify with these steps:
- Local verification: Run
npm run dev, open browser DevTools → Network, search forgtagto confirm the script loaded - GA DebugView: In GA4 → Admin → DebugView, install the Google Analytics Debugger Chrome extension to see events fire in real-time
- Realtime report: After deploying to production, open GA4 Realtime report and confirm active users appear within 5 minutes
- Event verification: Trigger search, code copy, etc. on the page and check GA4 DebugView for corresponding events
Next Steps
Section titled “Next Steps”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
We provide ESP32 ODM design-to-manufacturing services. From prototype to production — the team behind this tutorial can build it with you.
Talk to us →