Google Analytics 4 Implementation Guide
Applies to: Any website or web app | Updated: February 2026
A practical guide for implementing Google Analytics 4 (GA4) - covering installation, critical first-time setup, event tracking, e-commerce, consent, and advanced topics. Written for AI coding assistants: skip sections that don't apply to the user's setup.
Note: Universal Analytics (UA / GA3) was fully sunset in 2024. GA4 is the only current Google Analytics product.
Section 0: Before You Start
Answer these questions before writing any code. They determine which sections apply.
Q: Are any of your visitors in Europe (EU/EEA) or the UK? Default: no - if yes, Consent Mode v2 setup is required (see Consent Mode v2)
Q: Do you run Google Ads (search, display, YouTube, or Shopping)? Default: no - if yes, ad consent signals matter for conversion tracking and which events you mark as conversions
Q: Is your site a single-page app (React, Vue, Angular, Next.js, etc.) where the URL changes without a full page reload?
Default: check the project for package.json, next.config.*, vite.config.*, angular.json, or nuxt.config.* - if found, assume SPA and apply the Single-Page Apps section automatically
Q: Do you need to track purchases or sales? Default: no - skip E-commerce Tracking if no
Q: Do you already have a GA4 property, or is this a fresh start? Default: fresh start - if fresh start, create a property at analytics.google.com before writing any code
Q: Do you use Google Tag Manager, or add the tracking code directly? Default: direct gtag.js - recommend GTM only if the user has a marketing team managing multiple tags
AI assistant: Use these answers to skip irrelevant sections. Do not implement Consent Mode unless the user confirms EU/EEA/UK users. Do not implement e-commerce unless confirmed. If a SPA framework is detected in the project, automatically apply the SPA page_view section. Do not add
anonymize_ip- it is a no-op in GA4 (see Common Pitfalls).
Contents
- Installation
- Basic Configuration
- Critical First-Time Setup
- Common Pitfalls
- Event Tracking
- Enhanced Measurement
- User Properties & Custom Dimensions
- E-commerce Tracking
- Consent Mode v2
- Single-Page Apps
- Debugging
- Validation & Testing
- Advanced: BigQuery Export & Sampling
Installation
Option A: gtag.js (direct)
Add to <head> on every page. Replace G-XXXXXXXXXX with your Measurement ID (found in GA4 > Admin > Data Streams):
<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>
Option B: Google Tag Manager
GTM lets non-developers add and update tags without code changes. Add to <head> and immediately after <body>:
<!-- In <head> -->
<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-XXXXXXX');
</script>
<!-- First thing in <body> (fallback for no-JS environments) -->
<noscript>
<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe>
</noscript>
gtag.js vs GTM: Use gtag.js for simple setups or full code control. Use GTM when a marketing or analytics team needs to add tags independently, or when you manage more than two or three tags across different vendors.
Basic Configuration
Pass options as the third argument to gtag('config', ...):
gtag('config', 'G-XXXXXXXXXX', {
// Disable automatic page_view - set to false when firing it manually (e.g. SPAs)
send_page_view: false,
// Cookie domain - 'auto' works for most cases
cookie_domain: 'yourdomain.com',
// Cookie expiry in seconds (default: 63072000 = 2 years)
cookie_expires: 63072000,
});
Do not add anonymize_ip - it is silently ignored in GA4 (see Common Pitfalls).
Critical First-Time Setup
Complete these steps immediately after installing GA4, before any events are tracked in production. Some settings cannot be applied retroactively.
1. Set Data Retention to 14 Months
GA4 defaults to 2-month event data retention. After 2 months, event-level data is permanently deleted and cannot be recovered. Change this immediately.
Path: GA4 > Admin (gear icon) > Data Settings > Data Retention > Event data retention > 14 months > Save
This does not affect aggregated data in standard reports - it affects Explorations and any query that touches raw event data.
2. Set Up an Internal Traffic Filter
Without this filter, your own visits (dev, QA, team) pollute production data permanently. GA4 does not retroactively remove filtered data.
Path: GA4 > Admin > Data Filters > Create filter > Internal Traffic
- Set the filter name (e.g. "Internal - Office")
- Add your office and home IP addresses
- Set filter state to Active
This sets traffic_type=internal on matching hits and excludes them from reports.
3. Mark Key Events as Conversions
GA4 has no Goals. Conversions are events you promote manually. Without this step, conversions do not appear in the Conversions report or pass signals to Google Ads.
Path: GA4 > Admin > Events > find the event > toggle Mark as conversion
Events to mark:
purchase(e-commerce)generate_lead(lead gen forms)- Any other event representing a meaningful business outcome
If you run Google Ads, the events marked as conversions here are what Ads campaigns optimize against. Mark the wrong events and your campaigns optimize against the wrong signal.
4. Register Custom Dimensions
Custom event parameters are collected by GA4 but are invisible in all reports until registered. This step applies to any parameter you send beyond GA4's built-in ones.
Path: GA4 > Admin > Custom definitions > Custom dimensions > Create custom dimension
- Scope: Event (for parameters sent on individual events) or User (for user properties)
- Dimension name: human-readable label
- Event parameter: exact parameter name as used in your code (e.g.
button_label)
GA4 allows up to 50 event-scoped and 25 user-scoped custom dimensions on the free tier. Register only what you actively use in reports.
Common Pitfalls
Short list of mistakes that silently break GA4 implementations:
anonymize_ip: truedoes nothing in GA4. IP anonymization is always on in GA4 and cannot be disabled - it is a Universal Analytics config key that GA4 silently ignores. Remove it if present. Do not add it to new implementations.- Custom event parameters are invisible until registered. Parameters arrive in GA4 but do not appear in Explorations or standard reports until you register them as Custom Dimensions (Admin > Custom definitions). No error is shown.
- Data retention defaults to 2 months. Change it to 14 months immediately. Data already deleted cannot be recovered.
purchaseevent double-fires without a uniquetransaction_id. GA4 deduplicates purchase events bytransaction_id. Always pass a unique ID per transaction; without it, page refreshes on the confirmation page