IntermediateAgent Skill

Analytics Tracking

Create a GA4 ecommerce tracking plan that connects business actions to clear events and parameters. Give your assistant the customer journey, existing analytics setup and conversion definitions; this Skill helps document what to track, review naming and data quality, and prepare checks for consent, duplicate events and the final implementation.

Views
0
Copies
0
Favorites
0
Editorial Score
80/100
01

What this Skill does

Tracking becomes unreliable when similar actions have different names or an event is counted before the intended business action is complete. This Skill defines an event taxonomy and uses a local plan generator to connect customer actions with parameters and validation requirements.

Use it before a tracking implementation or when auditing an existing GA4/GTM setup. Supply sample event payloads and known conversion rules where possible. The package does not grant account access or publish a GTM container; the live behavior must be tested after implementation.

02

What makes it different

01

Approach and advantage

The event taxonomy makes names, parameters and conversion definitions explicit. A generated tracking plan gives developers a concrete specification and gives operators a reference for interpreting reports after the events are collected.

02

What you can use it for

Validation includes consent behavior, duplicate events and attribution-related checks. Keep those checks separate from writing the plan, then inspect actual payloads and live behavior so a complete specification does not hide an incomplete implementation.

03

Before you install

Inputs to prepare

Journey, analytics stack, existing events, conversion definitions, consent setup, and sample event payloads.

Agent and runtime

Use a Skill-capable agent with file access. Python 3 is required for the bundled Python helpers; inspect their sample schemas before supplying data.

Scope to confirm

The package does not grant analytics access or publish a GTM container. Live events, consent behavior, deduplication, and attribution require separate testing.

04

Install and get started

Copy this request into Codex or Claude Code. The assistant downloads the original repository at the specified commit, installs the complete files and checks required dependencies.

  1. Open Codex or Claude Code with local file and terminal access.
  2. Copy the request below into the app you are using. The assistant will select that app’s installation directory.
  3. Check the returned path and file checks. Start a new session if needed, then ask the assistant to use the installed Skill.
Install analytics-tracking in the app I am using and carry out the file installation, not just explain it. Original repository: https://github.com/alirezarezvani/claude-skills.git Commit: 6d2f02ea077eead1bee5411a31bcc6db5a11a70c Skill folder: marketing-skill/skills/analytics-tracking 1. Download this exact source into a new directory. Read SKILL.md and its setup references before running any bundled scripts. Do not substitute another author’s package. 2. For Codex, use ~/.agents/skills/analytics-tracking; for Claude Code, use ~/.claude/skills/analytics-tracking. Install only for my current app. Install the complete Skill folder, including scripts, references, assets and bundled notices. Keep any root license with the installed folder. Check all destination folders first; if any already exist, report differences before replacing them. 3. Compare the source and installed file lists and hashes. Inspect documented runtimes, dependencies and required connections. Configure only the local dependencies needed for this Skill; use an isolated environment when appropriate. Ask me to complete any account login locally, without putting credentials in chat. 4. Report the source commit, actual installation path, file-check results and any remaining runtime setup. Explain how to invoke analytics-tracking in this app. Check discovery separately from file copying; start a new session if needed. Do not run production tasks or claim a successful business outcome from installation alone.
05

Original Skill.md

This is the unchanged source SKILL.md for the reviewed version. Install the complete package to retain referenced scripts, assets, and instructions. Starter prompts below are EcomAgentTools examples.

---
name: "analytics-tracking"
description: "Set up, audit, and debug analytics tracking implementation — GA4, Google Tag Manager, event taxonomy, conversion tracking, and data quality. Use when building a tracking plan from scratch, auditing existing analytics for gaps or errors, debugging missing events, or setting up GTM. Trigger keywords: GA4 setup, Google Tag Manager, GTM, event tracking, analytics implementation, conversion tracking, tracking plan, event taxonomy, custom dimensions, UTM tracking, analytics audit, missing events, tracking broken. NOT for analyzing marketing campaign data — use campaign-analytics for that. NOT for BI dashboards — use product-analytics for in-product event analysis."
license: MIT
metadata:
  version: 1.0.0
  author: Alireza Rezvani
  category: marketing
  updated: 2026-03-06
---

# Analytics Tracking

You are an expert in analytics implementation. Your goal is to make sure every meaningful action in the customer journey is captured accurately, consistently, and in a way that can actually be used for decisions — not just for the sake of having data.

Bad tracking is worse than no tracking. Duplicate events, missing parameters, unconsented data, and broken conversions lead to decisions made on bad data. This skill is about building it right the first time, or finding what's broken and fixing it.

## Before Starting

**Check for context first:**
If `.claude/product-marketing-context.md` exists, read it before asking questions. Use that context and only ask for what's missing.

Gather this context:

### 1. Current State
- Do you have GA4 and/or GTM already set up? If so, what's broken or missing?
- What's your tech stack? (React SPA, Next.js, WordPress, custom, etc.)
- Do you have a consent management platform (CMP)? Which one?
- What events are you currently tracking (if any)?

### 2. Business Context
- What are your primary conversion actions? (signup, purchase, lead form, free trial start)
- What are your key micro-conversions? (pricing page view, feature discovery, demo request)
- Do you run paid campaigns? (Google Ads, Meta, LinkedIn — affects conversion tracking needs)

### 3. Goals
- Building from scratch, auditing existing, or debugging a specific issue?
- Do you need cross-domain tracking? Multiple properties or subdomains?
- Server-side tagging requirement? (GDPR-sensitive markets, performance concerns)

## How This Skill Works

### Mode 1: Set Up From Scratch
No analytics in place — we'll build the tracking plan, implement GA4 and GTM, define the event taxonomy, and configure key events.

Start from the generator, then customize:

```bash
python3 scripts/tracking_plan_generator.py            # embedded sample → full tracking plan
python3 scripts/tracking_plan_generator.py plan.json  # your funnel definition
python3 scripts/tracking_plan_generator.py --json     # parseable JSON for pipelines
```

Its output (event taxonomy + parameters + GA4/GTM config checklist) is the working draft for the Event Taxonomy Design section below — review every generated event name against the naming convention before implementing.

### Mode 2: Audit Existing Tracking
Tracking exists but you don't trust the data, coverage is incomplete, or you're adding new goals. We'll audit what's there, gap-fill, and clean up.

### Mode 3: Debug Tracking Issues
Specific events are missing, conversion numbers don't add up, or GTM preview shows events firing but GA4 isn't recording them. Structured debugging workflow.

---

## Event Taxonomy Design

Get this right before touching GA4 or GTM. Retrofitting taxonomy is painful.

### Naming Convention

**Format:** `object_action` (snake_case, verb at the end)

| ✅ Good | ❌ Bad |
|--------|--------|
| `form_submit` | `submitForm`, `FormSubmitted`, `form-submit` |
| `plan_selected` | `clickPricingPlan`, `selected_plan`, `PlanClick` |
| `video_started` | `videoPlay`, `StartVideo`, `VideoStart` |
| `checkout_completed` | `purchase`, `buy_complete`, `checkoutDone` |

**Rules:**
- Always `noun_verb` not `verb_noun`
- Lowercase + underscores only — no camelCase, no hyphens
- Be specific enough to be unambiguous, not so verbose it's a sentence
- Consistent tense: `_started`, `_completed`, `_failed` (not mix of past/present)

### Standard Parameters

Every event should include these where applicable:

| Parameter | Type | Example | Purpose |
|-----------|------|---------|---------|
| `page_location` | string | `https://app.co/pricing` | Auto-captured by GA4 |
| `page_title` | string | `Pricing - Acme` | Auto-captured by GA4 |
| `user_id` | string | `usr_abc123` | Link to your CRM/DB |
| `plan_name` | string | `Professional` | Segment by plan |
| `value` | number | `99` | Revenue/order value |
| `currency` | string | `USD` | Required with value |
| `content_group` | string | `onboarding` | Group pages/flows |
| `method` | string | `google_oauth` | How (signup method, etc.) |

### Event Taxonomy for SaaS

**Core funnel events:**
```
visitor_arrived         (page view — automatic in GA4)
signup_started          (user clicked "Sign up")
signup_completed        (account created successfully)
trial_started           (free trial began)
onboarding_step_completed (param: step_name, step_number)
feature_activated       (param: feature_name)
plan_selected           (param: plan_name, billing_period)
checkout_started        (param: value, currency, plan_name)
checkout_completed      (param: value, currency, transaction_id)
subscription_cancelled  (param: cancel_reason, plan_name)
```

**Micro-conversion events:**
```
pricing_viewed
demo_requested          (param: source)
form_submitted          (param: form_name, form_location)
content_downloaded      (param: content_name, content_type)
video_started           (param: video_title)
video_completed         (param: video_title, percent_watched)
chat_opened
help_article_viewed     (param: article_name)
```

See [references/event-taxonomy-guide.md](references/event-taxonomy-guide.md) for the full taxonomy catalog with custom dimension recommendations.

---

## GA4 Setup

### Data Stream Configuration

1. **Create property** in GA4 → Admin → Properties → Create
2. **Add web data stream** with your domain
3. **Enhanced Measurement** — enable all, then review:
   - ✅ Page views (keep)
   - ✅ Scrolls (keep)
   - ✅ Outbound clicks (keep)
   - ✅ Site search (keep if you have search)
   - ⚠️ Video engagement (disable if you'll track videos manually — avoid duplicates)
   - ⚠️ File downloads (disable if you'll track these in GTM for better parameters)
4. **Configure domains** — add all subdomains used in your funnel

### Custom Events in GA4

For any event not auto-collected, create it in GTM (preferred) or via gtag directly:

**Via gtag:**
```javascript
gtag('event', 'signup_completed', {
  method: 'email',
  user_id: 'usr_abc123',
  plan_name: "trial"
});
```

**Via GTM data layer (preferred — see GTM section):**
```javascript
window.dataLayer.push({
  event: 'signup_completed',
  signup_method: 'email',
  user_id: 'usr_abc123'
});
```

### Key Events Configuration

Mark these events as key events in GA4 → Admin → Key events (GA4 renamed "Conversions" to "Key events" in March 2024 — "conversions" now refers only to Google Ads conversion actions):
- `signup_completed`
- `checkout_completed`
- `demo_requested`
- `trial_started` (if separate from signup)

**Rules:**
- Max 30 key events per property — curate, don't mark everything
- Key events are retroactive in GA4 — turning one on applies to 6 months of history
- Don't mark micro-conversions as key events unless you're also optimizing ad campaigns for them

---

## Google Tag Manager Setup

### Container Structure

```
GTM Container
├── Tags
│   ├── GA4 Configuration (fires on all pages)
│   ├── GA4 Event — [event_name] (one tag per event)
│   ├── Google Ads Conversion (per conversion action)
│   └── Meta Pixel (if running Meta ads)
├── Triggers
│   ├── All Pages
│   ├── DOM Ready
│   ├── Data Layer Event — [event_name]
│   └── Custom Element Click — [selector]
└── Variables
    ├── Data Layer Variables (dlv — for each dL key)
    ├── Constant — GA4 Measurement ID
    └── JavaScript Variables (computed values)
```

### Tag Patterns for SaaS

**Pattern 1: Data Layer Push (most reliable)**

Your app pushes to dataLayer → GTM picks it up → sends to GA4.

```javascript
// In your app code (on event):
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
  event: 'signup_completed',
  signup_method: 'email',
  user_id: userId,
  plan_name: "trial"
});
```

```
GTM Tag: GA4 Event
  Event Name: {{DLV - event}} OR hardcode "signup_completed"
  Parameters:
    signup_method: {{DLV - signup_method}}
    user_id: {{DLV - user_id}}
    plan_name: "dlv-plan-name"
Trigger: Custom Event - "signup_completed"
```

**Pattern 2: CSS Selector Click**

For events triggered by UI elements without app-level hooks.

```
GTM Trigger:
  Type: Click - All Elements
  Conditions: Click Element matches CSS selector [data-track="demo-cta"]
  
GTM Tag: GA4 Event
  Event Name: demo_requested
  Parameters:
    page_location: {{Page URL}}
```

See [references/gtm-patterns.md](references/gtm-patterns.md) for full configuration templates.

---

## Conversion Tracking: Platform-Specific

### Google Ads

1. Create conversion action in Google Ads → Tools → Conversions
2. Import GA4 conversions (recommended — single source of truth) OR use the Google Ads tag
3. Set attribution model: **Data-driven** (if >50 conversions/month), otherwise **Last click**
4. Conversion window: 30 days for lead gen, 90 days for high-consideration purchases

### Meta (Facebook/Instagram) Pixel

1. Install Meta Pixel base code via GTM
2. Standard events: `PageView`, `Lead`, `CompleteRegistration`, `Purchase`
3. Conversions API (CAPI) strongly recommended — client-side pixel loses ~30% of conversions due to ad blockers and iOS
4. CAPI requires server-side implementation (Meta's docs or GTM server-side)

---

## Cross-Platform Tracking

### UTM Strategy

Enforce strict UTM conventions or your channel data becomes noise.

| Parameter | Convention | Example |
|-----------|-----------|---------|
| `utm_source` | Platform name (lowercase) | `google`, `linkedin`, `newsletter` |
| `utm_medium` | Traffic type | `cpc`, `email`, `social`, `organic` |
| `utm_campaign` | Campaign ID or name | `q1-trial-push`, `brand-awareness` |
| `utm_content` | Ad/creative variant | `hero-cta-blue`, `text-link` |
| `utm_term` | Paid keyword | `saas-analytics` |

**Rule:** Never tag organic or direct traffic with UTMs. UTMs override GA4's automatic source/medium attribution.

### Attribution Windows

| Platform | Default Window | Recommended for SaaS |
|---------|---------------|---------------------|
| GA4 | 30 days | 30-90 days depending on sales cycle |
| Google Ads | 30 days | 30 days (trial), 90 days (enterprise) |
| Meta | 7-day click, 1-day view | 7-day click only |
| LinkedIn | 30 days | 30 days |

### Cross-Domain Tracking

For funnels that cross domains (e.g., `acme.com` → `app.acme.com`):

1. In GA4 → Admin → Data Streams → Configure tag settings → List unwanted referrals → Add both domains
2. In GTM → GA4 Configuration tag → Cross-domain measurement → Add both domains
3. Test: visit domain A, click link to domain B, check GA4 DebugView — session should not restart

---

## Data Quality

### Deduplication

**Events firing twice?** Common causes:
- GTM tag + hardcoded gtag both firing
- Enhanced Measurement + custom GTM tag for same event
- SPA router firing pageview on every route change AND GTM page view tag

Fix: Audit GTM Preview for double-fires. Check Network tab in DevTools for duplicate hits.

### Bot Filtering

GA4 filters known bots automatically. For internal traffic:
1. GA4 → Admin → Data Filters → Internal Traffic
2. Add your office IPs and developer IPs
3. Enable filter (starts as testing mode — activate it)

### Consent Management Impact

Under GDPR/ePrivacy, analytics may require consent. Plan for this:

| Consent Mode setting | Impact |
|---------------------|--------|
| **No consent mode** | Visitors who decline cookies → zero data |
| **Basic consent mode** | Visitors who decline → zero data |
| **Advanced consent mode** | Visitors who decline → modeled data (GA4 estimates using consented users) |

**Recommendation:** Implement Advanced Consent Mode via GTM. Requires CMP integration (Cookiebot, OneTrust, Usercentrics, etc.).

Expected consent rate by region: 60-75% EU, 85-95% US.

---

## Proactive Triggers

Surface these without being asked:

- **Events firing on every page load** → Symptom of misconfigured trigger. Flag: duplicate data inflation.
- **No user_id being passed** → You can't connect analytics to your CRM or understand cohorts. Flag for fix.
- **Conversions not matching GA4 vs Ads** → Attribution window mismatch or pixel duplication. Flag for audit.
- **No consent mode configured in EU markets** → Legal exposure and underreported data. Flag immediately.
- **All pages showing as "/(not set)" or generic paths** → SPA routing not handled. GA4 is recording wrong pages.
- **UTM source showing as "direct" for paid campaigns** → UTMs missing or being stripped. Traffic attribution is broken.

---

## Output Artifacts

| When you ask for... | You get... |
|--------------------|-----------|
| "Build a tracking plan" | Event taxonomy table (events + parameters + triggers), GA4 configuration checklist, GTM container structure |
| "Audit my tracking" | Gap analysis vs. standard SaaS funnel, data quality scorecard (0-100), prioritized fix list |
| "Set up GTM" | Tag/trigger/variable configuration for each event, container setup checklist |
| "Debug missing events" | Structured debugging steps using GTM Preview + GA4 DebugView + Network tab |
| "Set up conversion tracking" | Conversion action configuration for GA4 + Google Ads + Meta |
| "Generate tracking plan" | Run `python3 scripts/tracking_plan_generator.py [plan.json] [--json]` — event taxonomy + GA4/GTM checklist |

---

## Communication

All output follows the structured communication standard:
- **Bottom line first** — what's broken or what needs building before methodology
- **What + Why + How** — every finding has all three
- **Actions have owners and deadlines** — no vague "consider implementing"
- **Confidence tagging** — 🟢 verified / 🟡 estimated / 🔴 assumed

---

## Related Skills

- **campaign-analytics**: Use for analyzing marketing performance and channel ROI. NOT for implementation — use this skill for tracking setup.
- **ab-test-setup**: Use when designing experiments. NOT for event tracking setup (though this skill's events feed A/B tests).
- **analytics-tracking** (this skill): covers setup only. For dashboards and reporting, use campaign-analytics.
- **seo-audit**: Use for technical SEO. NOT for analytics tracking (though both use GA4 data).
- **gdpr-dsgvo-expert**: Use for GDPR compliance posture. This skill covers consent mode implementation; that skill covers the full compliance framework.
06

Get started

Starter prompts for the main use cases—copy and use them directly.

01

Draft purchase and funnel event specifications

Draft purchase and funnel event specifications Use for: Draft purchase and funnel event specifications. Prepare: Journey, analytics stack, existing events, conversion definitions, consent setup, and sample event payloads.

Show prompt and variablesHide prompt and variables
Use the installed analytics-tracking Skill. Task: Draft purchase and funnel event specifications. Inputs: [INPUT]. Constraints: [CONSTRAINTS]. Check missing information first. Produce a reviewable result with evidence, assumptions, and next steps. The package does not grant analytics access or publish a GTM container. Live events, consent behavior, deduplication, and attribution require separate testing.

Replace these variables

[INPUT]
Journey, analytics stack, existing events, conversion definitions, consent setup, and sample event payloads.
[CONSTRAINTS]
Scope, allowed actions, output format, and review requirements.
02

Audit missing parameters and duplicate events

Audit missing parameters and duplicate events Use for: Audit missing parameters and duplicate events. Prepare: Journey, analytics stack, existing events, conversion definitions, consent setup, and sample event payloads.

Show prompt and variablesHide prompt and variables
Use the installed analytics-tracking Skill. Task: Audit missing parameters and duplicate events. Inputs: [INPUT]. Constraints: [CONSTRAINTS]. Check missing information first. Produce a reviewable result with evidence, assumptions, and next steps. The package does not grant analytics access or publish a GTM container. Live events, consent behavior, deduplication, and attribution require separate testing.

Replace these variables

[INPUT]
Journey, analytics stack, existing events, conversion definitions, consent setup, and sample event payloads.
[CONSTRAINTS]
Scope, allowed actions, output format, and review requirements.
03

Build consent-aware tracking validation steps

Build consent-aware tracking validation steps Use for: Build consent-aware tracking validation steps. Prepare: Journey, analytics stack, existing events, conversion definitions, consent setup, and sample event payloads.

Show prompt and variablesHide prompt and variables
Use the installed analytics-tracking Skill. Task: Build consent-aware tracking validation steps. Inputs: [INPUT]. Constraints: [CONSTRAINTS]. Check missing information first. Produce a reviewable result with evidence, assumptions, and next steps. The package does not grant analytics access or publish a GTM container. Live events, consent behavior, deduplication, and attribution require separate testing.

Replace these variables

[INPUT]
Journey, analytics stack, existing events, conversion definitions, consent setup, and sample event payloads.
[CONSTRAINTS]
Scope, allowed actions, output format, and review requirements.
07

Worked example: Turn ecommerce event requirements into a GA4/GTM plan

Synthetic event requirements and configuration problems include duplicate page views, repeated purchases on refresh, missing currency and consent defaults. The merchant needs a field-level implementation plan.

Steps and prompt

  1. Prepare the attached business materials, preserving amounts, units, dates and metric definitions.
  2. Create an ecommerce measurement plan for the supplied purchase journey and business goals. Map actual customer actions to GA4 events, define parameters, successful triggers, transaction deduplication and consent handling, and specify GTM tags and variables. Give implementation acceptance checks for the developer and analyst.
  3. Submit the exact prompt below. Read the primary deliverable on the right and download all deliverables for the team handoff.

Case input files: business-inputs.zip

Use the analytics-tracking Skill.

Create an ecommerce measurement plan for the supplied purchase journey and business goals. Map actual customer actions to GA4 events, define parameters, successful triggers, transaction deduplication and consent handling, and specify GTM tags and variables. Give implementation acceptance checks for the developer and analyst.

The attached business materials are:
- inputs/brief.json
- inputs/context.json

Deliver a complete result.md report that the operations team can read, plus any finished files needed for this task. Keep supporting calculations and evidence with the deliverables. Write the report in English; use the requested target language for customer-facing copy. The business datasets are fictional examples unless the brief explicitly names a live public website.

What the run produced

The primary file produced by this prompt is shown below in its original language.

HarborMug ecommerce measurement plan

Build a consent-gated GA4 funnel from product view through confirmed paid order. Use one router-owned page-view implementation, application success callbacks for commerce events, USD on all monetary events, and stable transaction IDs. A guest who declines optional consent must generate zero analytics or advertising requests. The operational order system remains the source of truth for all sales and refunds.

This plan uses synthetic supplied business data and configuration observations; no storefront integration, GA4 account, GTM container, CMP implementation, or measured business improvement has been verified.

Decisions and scope

The supplied journey is /products/harbormug → /cart → /checkout in a React SPA on a single US storefront. The core business decision is where consenting shoppers leave the journey and whether successful paid orders are measured accurately. USD is the proposed currency based on the supplied US storefront; the implementation owner must confirm it against the order system before release. Shipping and payment step events below are conditional because separate steps are not specified.

The brief lists Google Ads and Meta, but the context explicitly excludes paid-channel activation and purchase optimization. Therefore this delivery specifies GA4 measurement only: no Ads imports, conversion linker, Meta pixel, CAPI, remarketing audiences, or enhanced conversions. Purchase is a GA4 key event for measurement, with no ad-platform activation. No cross-domain or server-side analytics is planned. Guest user_id omission is intentional; do not create an identifier or require login for measurement.

Evidence confidence: verified in supplied materials means documented input, not observed telemetry; proposed means implementation design; unconfirmed means a release dependency. The supplied dual page-view sources, thank-you load trigger, missing currency and unset consent default are documented design risks, not findings from a live audit.

Business questions and reporting definitions

DecisionMeasurementInterpretation
Does product interest turn into cart intent?Consented sessions with view_item then add_to_cart / consented sessions with view_itemSame-session ordered funnel; successful additions, not clicks
Does the cart lead to checkout?Sessions with view_cart then begin_checkout / sessions with view_cartA cart drawer or skipped cart route may bypass this step; keep a separate direct-to-checkout segment
Does checkout result in payment?Sessions with begin_checkout then purchase / sessions with begin_checkoutPayment failures and exits are not paid orders; cross-session purchases also appear in an open funnel
Are sales and amounts trustworthy?Distinct paid transaction IDs, purchased item quantities, merchandise purchase revenueReconcile to eligible order records on identical date, currency and revenue basis
Has money actually been returned?Confirmed refunded merchandise and quantities by original transactionReturn requests and refund approvals are not refunds

Use a closed, same-session product → add → checkout → purchase funnel for the main journey. Use an open funnel alongside it for direct checkout and returning shoppers. Do not divide raw event counts to estimate shopper conversion: repeated actions and quantities differ. Pick and record the property reporting timezone with operations before launch, and use it for ledger reconciliation.

For orientation only, supplied prior/current totals are 100/120 orders and 4,000/4,800 sessions. Orders per session are 2.5% in both periods; gross average order value is $24 in both. Orders, sessions and gross sales each rise 20%; these examples do not show improved conversion. Gross sales less supplied refunds are $2,280 and $2,736. Refund amounts are 5% of gross in each period, not a refunded-order rate. These are supplied all-business totals, not a consented GA4 funnel or evidence of tracking performance. Calculations are in supporting/calculations.json.

Customer action → event contract

Use Google's recommended ecommerce names, including view_item, begin_checkout and purchase, to populate ecommerce reporting. These intentionally supersede the Skill generator's generic names product_viewed, checkout_started and checkout_completed; do not send aliases alongside them. The generated search event is excluded because no search surface is supplied. Google ecommerce guide

All rows require analytics consent granted at the time of the action and immediately before dispatch. Commerce rows use currency, value, and items unless stated otherwise.

Customer actionGA4 eventSuccessful trigger and counting rule
Views a rendered routepage_viewInitial render or completed navigation, once per navigation; not rerenders
Sees the HarborMug productview_itemProduct fetch succeeds and product content renders, once per product per navigation
Adds mugsadd_to_cartCart mutation succeeds; quantity/value describe only the increment
Removes mugsremove_from_cartCart mutation succeeds; quantity/value describe only the decrement
Views cartview_cartCart snapshot renders on /cart, once per navigation; full current cart
Enters valid checkoutbegin_checkoutNonempty cart accepted and checkout ready, once per checkout attempt, including direct valid entry
Saves shipping selection, if a separate step existsadd_shipping_infoValid selection persisted; once per distinct saved selection per attempt; add shipping_tier
Supplies an accepted payment method, if a separate step existsadd_payment_infoCheckout service accepts method; once per distinct accepted method per attempt; add payment_type
Completes paymentpurchaseTrusted order endpoint confirms paid/captured state; add transaction_id, shipping, tax; one logical event per order
Receives an actual refund, future workflowrefundProvider confirms refund executed; original transaction ID and refunded items/value; inactive at launch

An attempt begins when the checkout service creates or resumes a checkout token; resuming the same token is the same attempt. A new service token after expiry or a deliberate new checkout is a new attempt. Tokens remain internal and are never sent to GA4. Failed validation, failed cart requests, pending payment and authorization without capture produce no success event. Do not infer abandonment by sending a purchase failure on every exit.

The complete portable contract is event-contract.csv; consent-granted example payloads for every event are in data-layer-examples.json. Neither is evidence of actual actions. No new customer-facing copy is needed.

Parameter dictionary and financial basis

FieldType and ruleSource
currencyString, uppercase ISO currency; proposed USD; required with every monetary valueValidated cart/order currency
valueNumber in major currency units; sum of discounted unit price × quantity; excludes tax and shippingAccepted cart mutation/snapshot or paid order lines
itemsArray of item objects; required, nonempty except an empty view_cartProduct/cart/order API
item_idString HM-BLUE-001; stable SKUProduct catalog
item_nameString Insulated stainless steel mug 500mlProduct catalog
priceNumber, actual unit merchandise price after discounts; current list price 24Accepted line item
quantityPositive integer for nonempty lines; additions/removals use positive changed quantityAccepted line item
transaction_idImmutable unique opaque order reference; nonempty, no personal data; purchase/refund onlyOrder system, never URL or random browser ID
shipping, taxNonnegative numbers for purchase; actual charged amounts, explicit zero only when genuinely zeroPaid order totals
shipping_tierControlled string such as standard; optional step onlySaved checkout selection
payment_typeControlled generic method such as card; no financial instrument dataAccepted checkout method
page_locationSanitized absolute current URLRouter state
page_titleNonpersonal current route title, ready before eventRoute metadata
page_referrerSanitized previous committed route; first entry uses sanitized external referrer if availableRouter navigation state

Use actual paid amounts, never the brief's $24 hint as a constant purchase value. For one mug without discounts: merchandise value=24, shipping 5, and tax from the order API; total charged is 29 + tax. Two mugs give value=48, shipping 5; three give value=72, shipping 0 because the free-shipping threshold is $50. Do not confuse the merchant's $4 shipping cost with the $5 customer shipping charge. The example payload's zero tax is a test scenario, not a tax assumption. If discounts are introduced, confirm threshold and discount-allocation rules with operations before implementation. Recommended event parameter definitions

Clear ecommerce with dataLayer.push({ecommerce:null}) before each commerce push to prevent old order fields merging into cart events. Supply a complete fresh ecommerce object, and explicitly reset irrelevant optional fields. Keep route fields fresh on every event; send sanitized page fields on commerce hits as well. Reject malformed purchase payloads instead of sending partial revenue. Log a minimal reason in first-party operational diagnostics without personal or payment data.

SPA page views and attribution

Choose the application router as the only page-view source. Set the Google tag's send_page_view=false on every initialization and disable Enhanced Measurement history-based page views. Remove all GTM History Change page-view triggers and hardcoded analytics sends. The router emits after the committed route, data and title are ready, including the initial route. Deduplicate by a navigation token kept internal; React Strict Mode, state updates and fragment changes without new content must not create another navigation. Back/forward to a rendered route is a new view. Google manual page-view guidance

On delayed consent grant, emit one current route view and current visible product/cart snapshot only. Do not replay prior routes or past mutations. Use the prior committed route as virtual referrer; never use checkout tokens or order references as page URLs or titles. Preserve approved nonpersonal external campaign parameters on the current landing URL through tag initialization when consent permits. Do not persist prior browsing or campaign history while consent is denied.

For future campaign hygiene, normalize the supplied example to ?utm_source=google&utm_medium=cpc&utm_campaign=mug-launch. Keep approved campaign names lowercase and nonpersonal. Do not add UTMs to internal product/cart/checkout links or invent source values for direct traffic. Allowlist campaign parameters in the URL sanitizer; strip email, addresses, tokens, sensitive fragments and arbitrary query values. No account linking or paid-channel activation is part of this delivery.

Consent handling: basic mode, fail closed

Use basic consent mode rather than the generator's advanced-mode default. Default analytics_storage, ad_storage, ad_user_data, and ad_personalization to denied before any measurement tag can run. Defaults also deny optional functionality and personalization storage; strictly necessary security and cart functions are separate from analytics. Use a CMP template with GTM's consent APIs (setDefaultConsentState and updateConsentState), on Consent Initialization. A plain data-layer object containing consent strings is not an API update. Google consent implementation guide

The CMP must update consent before emitting a separate analytics_ready orchestration event. The Google tag loads only after analytics consent is granted; every GA4 event has both an explicit current-consent trigger condition and an additional analytics_storage consent requirement. Default-denied flags alone are insufficient to enforce zero requests: Google's advanced behavior can send cookieless pings. Basic mode blocks Google measurement tags before consent. Basic versus advanced consent behavior

StateRequired behavior
Unknown, CMP unavailable, or decline allNo GA4 library, collect hit, analytics cookie, dedup browser storage or advertising request; no queue for later replay
Analytics granted onlyInitialize Google tag once; send current view and future eligible events; all advertising flags remain denied
Optional marketing acceptedStill no ad tags; only configured analytics may run, according to analytics choice
Analytics revokedUpdate API immediately, block future tags, discard unsent events, clear analytics cookies and analytics-only guards according to their configured domains/paths; retain only necessary CMP preference
Later re-grantResume current view and future actions; never backfill payment or browsing that occurred while denied

Check consent in the application before constructing analytics payloads and again in GTM. Serialize CMP transitions and dispatch so an event queued before revocation cannot escape afterward. Necessary order records and consent preferences are not an alternate analytics route. Do not send the declined guest's order through Measurement Protocol or any other analytics channel. The plan deliberately accepts incomplete GA4 coverage.

Transaction deduplication and delivery limits

The paid order endpoint supplies one stable transaction ID per order. The callback must validate payment status, ID, currency, items and totals. Never fire purchase from a thank-you route mount, refresh, click, payment attempt ID or browser-generated random ID. Repeated captures belonging to the same business order do not create new purchases; a genuinely separate order has a new ID.

After consent, use an in-memory single-flight lock plus an analytics-consented browser guard per transaction to stop duplicate callbacks, rerenders and reloads. Cross-tab/reopened-device protection must use an atomic first-party order-system claim keyed by transaction ID. The claim records only order measurement eligibility/handoff status, and must not send anything to GA4 or run for denied users. This is an order API requirement, not server-side tagging. If that endpoint cannot support the claim, document the residual cross-device duplication risk and do not treat local storage as sufficient.

Dispatch only after a successful claim, set the local handoff guard, and retain the same ID throughout. GA4's purchase deduplication is an additional defense; it does not justify repeated sends or protect every possible multi-user case. Never use a blank ID or reuse one ID for different orders. Google transaction-ID deduplication

The claim and GTM handoff cannot guarantee GA4 delivery. A blocked request or closed tab after claim can leave an eligible order unmeasured. Record it as delivery-unconfirmed in operational reconciliation, not as a proven GA4 receipt. A GTM callback is not a receipt either. Do not automatically replay on page load or introduce a server analytics fallback. Any later retry design needs an explicit delivery policy, current consent and the original ID. Prioritize zero duplicate logical purchases in controlled acceptance tests and transparent reporting of missing deliveries.

Returns and refunds

The supplied return was requested 14 calendar days after delivery and is unopened, within the stated 30-day window. Eligibility does not establish approval or payment. The recorded refund requires merchant approval and has not been paid: emit no refund event and deduct no amount for this individual return yet. The supplied weekly refund totals are separate aggregate examples.

Keep refund instrumentation inactive until there is a confirmed-refund source and consent-aware delivery route. A future refund sends the original transaction ID, actual refunded merchandise value and quantities, and only any tax/shipping actually refunded. Never send negative purchase events. Guard future partial refunds by an internal unique refund-operation reference; do not assume purchase transaction-ID deduplication handles multiple legitimate partial refunds. Browser-only measurement will miss refunds executed away from the shopper's session, so the refund ledger remains authoritative.

GTM build specification

This is a build specification, not an importable or deployed container. Use a separate test property/container environment before production; no real measurement identifiers are included.

TagTriggerConfiguration
CMP - Defaults and updatesConsent Initialization — All Pages; CMP change callbackAudited CMP template using consent APIs; defaults before measurement, then readiness orchestration
Google tag - GA4Custom Event analytics_ready, only when analytics grantedMeasurement destination constant; send_page_view=false; once per document; no all-pages load
GA4 - page_viewCustom Event exact page_view, analytics granted and initialization completeFixed event name; sanitized location/title/referrer variables
GA4 - EVENT for each of the eight active commerce rowsExact Custom Event with matching fixed event name; analytics granted and initialization completeOne tag per event; parameters from that row; optional step tags disabled if no such step exists
GA4 - refundNone at launchDisabled until confirmed-refund workflow passes acceptance

The eight active commerce rows are view_item, add_to_cart, remove_from_cart, view_cart, begin_checkout, add_shipping_info, add_payment_info, and purchase. Readiness initializes the Google tag before the app emits current-view events. Hold only post-grant events briefly while initialization completes; discard on revoke. The app must not send a second gtag implementation beside GTM.

VariableGTM type / exact sourceUse
CON - GA4 destinationConstant set during account creationGoogle tag and all GA4 event tags
DLV - currency/value/itemsThree Version 2 variables: ecommerce.currency, ecommerce.value, ecommerce.itemsCommerce tags
DLV - transaction_id/shipping/taxThree Version 2 variables under ecommerce with corresponding keyPurchase; refund only when applicable
DLV - shipping_tier/payment_typeTwo Version 2 variables under ecommerceCorresponding optional step only
DLV - page_location/page_title/page_referrerThree Version 2 variables at root, already sanitizedAll event tags
JS - analytics allowedBoolean from current CMP state, default falseExplicit trigger gate; never trust a stale data-layer value
JS - analytics initializedBoolean set only after Google tag initializationDispatch ordering gate
CON - debug modeBoolean true in test environment; absent in productiondebug_mode on test events only

Map value to DLV - value, items to DLV - items, and each other named parameter to its same-named variable. Configure ecommerce parameters explicitly; do not also turn on a second automatic ecommerce mapping that duplicates them. No click, generic form submit, DOM-ready or all-pages purchase trigger is allowed.

GA4 configuration and acceptance

Create one web stream for the storefront, confirm currency and reporting timezone, and configure one Google tag destination. Keep Google signals, advertising personalization and account links inactive for this scope. Use built-in ecommerce dimensions and metrics; do not register SKU, value, transaction ID or guest user_id as custom dimensions. No custom dimension is required for the core plan. If analysts need shipping_tier or payment_type and the required report does not expose them, register event-scoped definitions before testing those reports. Use a proposed two-month event-data retention setting, subject to the merchant's retention policy. Keep internal/developer traffic filters in testing until verified; use a separate test property to avoid permanent exclusion mistakes.

Use purchase as the sole commerce key event and count once per event so distinct orders in one session count separately. No funnel micro-event or pending return is a key event. Treat the key-event setup as prospective; do not promise historical backfill.

acceptance-checks.csv contains 16 executable test scenarios with explicit pass criteria and developer/analyst ownership. None has been run against a storefront. Required release gates are:

  1. Implementation owner, before staging handoff: implement consent-first dispatch, one router source, successful cart/checkout callbacks and paid-order validation; confirm currency, tax fields, checkout attempts and shared order claim.
  2. Developer, before analyst handoff: pass D01–D11, including decline all, delayed consent, revocation, Strict Mode, failed mutations, pending payments, reloads, two tabs, distinct orders, malformed payloads, shipping thresholds and the unapproved return.
  3. Analyst role, before launch approval: pass A01–A05. Inspect application payload → GTM Preview variables/tag firing → network event payload → GA4 DebugView → processed reports. Count event payloads rather than HTTP requests because collection can batch events. Zero duplicates and correct financial values are mandatory for controlled eligible orders.
  4. Operations owner, at release review: review the test evidence and reconcile eligible paid orders by transaction ID. Keep all-order totals, denied orders, consented expected orders, observed GA4 orders and delivery-unconfirmed orders separate. Do not expect GA4 to equal every store order.
  5. Analyst role, after the first complete reporting day and processing delay: recheck processed ecommerce reports, route attribution and operational reconciliation; investigate discrepancies by consent, blocking, timing, ID, filters and value basis before changing tags. Pause measurement if consent leakage or duplicate purchases occur, correct in staging, then repeat affected checks.

Evidence to retain for release: sanitized payload examples, GTM tag/consent traces, sanitized network event counts, DebugView observations, processed report counts and a synthetic transaction reconciliation table. Do not attach raw URLs, cookies, customer records or credentials. Troubleshoot from app to reports; adding another tag to fix a reporting delay risks duplicates.

Completed deliverables and remaining dependency

The finished plan includes event-contract.csv, data-layer-examples.json, acceptance-checks.csv, and supporting calculation, generator-review and verification evidence. It is ready for implementation. Live acceptance remains dependent on creating the planned GA4/GTM/CMP setup and wiring the order API; the supplied example domain and configuration cannot establish tag firing or delivery. Until the confirmed refund route exists, measure refunds in the operational ledger only.

Merchant business data is synthetic. Website observations, when present, come from the public URLs listed in the report.

08

Risks and operating notes

Known limits

The package does not grant analytics access or publish a GTM container. Live events, consent behavior, deduplication, and attribution require separate testing.

Evidence and review

Source and package files reviewed: GitHub 6d2f02ea077e. This is a static review, not an installation or business-outcome test.

Before acting on the result

Use authorized inputs and keep secrets out of prompts. Review customer-facing claims, calculations, code changes, and any proposed external action before applying them.

Frequently asked questions

What does it do, and what is the advantage?

Plan and audit GA4/GTM events, conversion definitions, consent, and data quality. An event-taxonomy workflow and local tracking-plan generator connect business actions to parameters and validation.

How do I install it and start?

Choose the method for your agent and install the complete package, not just the displayed SKILL.md. Journey, analytics stack, existing events, conversion definitions, consent setup, and sample event payloads. Start a new agent session and explicitly ask to use analytics-tracking. Try one use case below with a small sample and review the output.

Which situations is it useful for?

Draft purchase and funnel event specifications; Audit missing parameters and duplicate events; Build consent-aware tracking validation steps

What limitations should I know?

The package does not grant analytics access or publish a GTM container. Live events, consent behavior, deduplication, and attribution require separate testing.

What was checked for this page?

Source and package files reviewed: GitHub 6d2f02ea077e. This is a static review, not an installation or business-outcome test.

No reviews yet.

Leave a review

Rate every dimension, then share your real experience.

Task effectiveness
Setup and ease of use
Reliability and guardrails
Documentation clarity
Time to first useful result
Author / maintainer

Alireza Rezvani

Source and package files reviewed: GitHub 6d2f02ea077e. This is a static review, not an installation or business-outcome test.