Receber por email
← Voltar para o catálogo

google-analytics-4

Use this skill whenever the user installs, configures, or debugs Google Analytics 4, or mentions gtag.js, GTM, conversion tracking, e-commerce events, or a cookie/consent banner tied to analytics. Covers installation, event tracking, user properties, e-commerce, Consent Mode v2 for EU/UK visitors, SPA pageview tracking, and BigQuery export. Skip for other analytics products (Plausible, Mixpanel, P

24estrelas
Atualizado há 5 meses

Ver no GitHub ↗ Licença: Apache-2.0

Como adicionar

/plugin marketplace add ziniman/ai-instruct

O comando exato pode variar conforme o repositório. Confira o README no GitHub.

Para o autor da skill

Cole no README do seu repo

Mostra que sua skill está catalogada na Skillteca, gera backlink e tráfego rastreável.

[![Skillteca](https://www.skillteca.com.br/api/badge/google-analytics-4/svg)](https://www.skillteca.com.br/skills/google-analytics-4)

Skills relacionadas

Ver todas de Desenvolvimento →

Alerta por categoria

Receba novas skills de Desenvolvimento toda segunda

1 email curto, só com as skills novas de Desenvolvimento. 4 minutos de leitura, sem spam, cancela com 1 clique.

Você confirma o email no primeiro envio. Sem spam. Cancela com 1 clique.

Ler descrição completa

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](#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](#single-page-apps) section automatically

Q: Do you need to track purchases or sales? Default: no - skip [E-commerce Tracking](#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](#common-pitfalls)).

Contents

  1. [Installation](#installation)
  2. [Basic Configuration](#basic-configuration)
  3. [Critical First-Time Setup](#critical-first-time-setup)
  4. [Common Pitfalls](#common-pitfalls)
  5. [Event Tracking](#event-tracking)
  6. [Enhanced Measurement](#enhanced-measurement)
  7. [User Properties & Custom Dimensions](#user-properties--custom-dimensions)
  8. [E-commerce Tracking](#e-commerce-tracking)
  9. [Consent Mode v2](#consent-mode-v2)
  10. [Single-Page Apps](#single-page-apps)
  11. [Debugging](#debugging)
  12. [Validation & Testing](#validation--testing)
  13. [Advanced: BigQuery Export & Sampling](#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](#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

  1. Set the filter name (e.g. "Internal - Office")
  2. Add your office and home IP addresses
  3. 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: true does 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.
  • purchase event double-fires without a unique transaction_id. GA4 deduplicates purchase events by transaction_id. Always pass a unique ID per transaction; without it, page refreshes on the confirmation page
Compartilhar X LinkedIn