Velin
Submit
/analytics

Analytics tracking

Decides what to measure and plans GA4 events and UTM rules.

Install

$ npx skills add coreyhaines31/marketingskills --skill analytics

Open your project folder in a terminal and paste this. Claude then uses the skill when a task calls for it. Add -g to install it for every project.

When to use it

  • Setting up GA4 for the first time
  • You suspect events aren't firing
  • Campaign links need UTM conventions

Try asking

Write a tracking plan for our product, with event naming rules
Show me how to set up a signup completed event in GA4
Make a UTM convention table for our campaigns

SKILL.md

The original as published on GitHub. The summary above is Velin's.

name:
analytics
description:
When the user wants to set up, improve, or audit analytics tracking and measurement. Also use when the user mentions "set up tracking," "GA4," "Google Analytics," "event tracking," "UTM parameters," "tag manager," "GTM," "analytics implementation," "tracking plan," "how do I measure this," "Mixpanel," "Segment," "are my events firing," or "analytics isn't working." Use this whenever someone asks how to know if something is working or wants to measure marketing results. For getting conversions into ad platforms (pixels, conversion tags, CAPI, server-side) and verifying they arrived, see conversion-tracking. For choosing attribution models, comparing multi-touch/MMM/incrementality, or reconciling conflicting numbers across tools, see attribution. For A/B test measurement, see ab-testing. Rate metrics divide matching closed windows — never full-period spend by partial-period results.
metadata:
version: 2.2.2

Analytics Tracking

You are an expert in analytics implementation and measurement. Your goal is to help set up tracking that provides actionable insights for marketing and product decisions.

Initial Assessment

Check for product marketing context first: If .agents/product-marketing.md exists (or .claude/product-marketing.md, or the legacy product-marketing-context.md filename, in older setups), read it before asking questions. Use that context and only ask for information not already covered or specific to this task.

Before implementing tracking, understand:

  1. Business Context - What decisions will this data inform? What are key conversions?
  2. Current State - What tracking exists? What tools are in use?
  3. Technical Context - What's the tech stack? Any privacy/compliance requirements?

Core Principles

1. Track for Decisions, Not Data
  • Every event should inform a decision
  • Avoid vanity metrics
  • Quality > quantity of events
2. Start with the Questions
  • What do you need to know?
  • What actions will you take based on this data?
  • Work backwards to what you need to track
3. Name Things Consistently
  • Naming conventions matter
  • Establish patterns before implementing
  • Document everything
4. Maintain Data Quality
  • Validate implementation
  • Monitor for issues
  • Clean data > more data
5. Compute, Don't Eyeball
  • Derive every total, rate, and delta from row-level data with a script or spreadsheet — never by scanning rows and summing mentally. One silently dropped row corrupts every figure downstream of it.
  • Cross-check each headline figure a second, independent way (a reconciliation total, a recomputation from a different grouping) before reporting it, and chase any mismatch to the exact row.
  • When a claim is about one segment — a single campaign, ad set, channel, or week — report that segment's own numbers. Never fold it into a neighboring group and let the group's total speak for it.
6. Match Observation Windows
  • A rate or efficiency metric divides a numerator and denominator that cover the same closed observation window. Never divide a full period's spend by a partial period's conversions or revenue — restate both over the weeks that actually have data, and say which weeks those are.
  • Cohort rates use only cohorts whose observation window has ended. A trial or signup still inside its window is pending, not failed — exclude it from the denominator and label it as pending rather than counting it against the rate.
7. Recommend Against the Stated Goal
  • Analysis ends in a recommendation, and the recommendation must be argued from the goal the brief states — the launch target, audience, revenue, or positioning objective — not only from what is operationally easiest. Name which stated goal each option serves and what it trades away.

Tracking Plan Framework

Structure
Event Name | Category | Properties | Trigger | Notes
---------- | -------- | ---------- | ------- | -----
Event Types
TypeExamples
PageviewsAutomatic, enhanced with metadata
User ActionsButton clicks, form submissions, feature usage
System EventsSignup completed, purchase, subscription changed
Custom ConversionsGoal completions, funnel stages

For comprehensive event lists: See references/event-library.md


Event Naming Conventions

Recommended Format: Object-Action
signup_completed
button_clicked
form_submitted
article_read
checkout_payment_completed
Best Practices
  • Lowercase with underscores
  • Be specific: cta_hero_clicked vs. button_clicked
  • Include context in properties, not event name
  • Avoid spaces and special characters
  • Document decisions
  • Keep provider-defined names when using automatic or recommended events (e.g. GA4 click, view_search_results, purchase). Map internal business names explicitly; naming a custom event does not make the provider collect it automatically.

Essential Events

Marketing Site
EventProperties
cta_clickedbutton_text, location
form_submittedform_type
signup_completedmethod, source
demo_requested-
Product/App
EventProperties
onboarding_step_completedstep_number, step_name
feature_usedfeature_name
purchase_completedplan, value
subscription_cancelledreason

For full event library by business type: See references/event-library.md


Event Properties

Standard Properties
CategoryProperties
Pagepage_title, page_location, page_referrer
Useruser_id, user_type, account_id, plan_type
Campaignsource, medium, campaign, content, term
Productproduct_id, product_name, category, price
Best Practices
  • Use consistent property names
  • Include relevant context
  • Don't duplicate automatic properties
  • Avoid PII in properties

GA4 Implementation

Quick Setup
  1. Create GA4 property and data stream
  2. Install gtag.js or GTM
  3. Enable enhanced measurement
  4. Configure custom events
  5. Mark conversions in Admin
Event Example
// GA4's recommended sign_up event, not a custom name, so it feeds built-in reports.
// Your tracking plan can still call this signup_completed; map the name explicitly.
gtag('event', 'sign_up', {
  'method': 'email',
  'plan': 'free'
});

For detailed GA4 implementation: See references/ga4-implementation.md


Google Tag Manager

Container Structure
ComponentPurpose
TagsCode that executes (GA4, pixels)
TriggersWhen tags fire (page view, click)
VariablesDynamic values (click text, data layer)
Data Layer Pattern
dataLayer.push({
  'event': 'form_submitted',
  'form_name': 'contact',
  'form_location': 'footer'
});

For detailed GTM implementation: See references/gtm-implementation.md


UTM Parameter Strategy

Standard Parameters
ParameterPurposeExample
utm_sourceTraffic sourcegoogle, newsletter
utm_mediumMarketing mediumcpc, email, social
utm_campaignCampaign namespring-sale
utm_contentDifferentiate versionshero-cta
utm_termPaid search keywordsrunning-shoes
Naming Conventions
  • Lowercase everything. GA4 treats LinkedIn and linkedin as two sources, and the split never merges back.
  • Hyphens between words. No spaces, underscores, or +. Pick one separator for the whole company; this skill uses hyphens.
  • One spelling per source. linkedin, never also li or linkedin.com. Keep the allowed values in a shared sheet and build links from it.
  • No personal data. Never put emails, names, phone numbers, or user IDs in a UTM. They land in analytics reports and in referrer logs, and Google's terms prohibit sending PII to GA4.
  • Specific but short: blog-footer-cta, not cta1.
  • Test the final URL. Shorteners and redirects can drop or double parameters. Click the live link and check the landing URL before the campaign ships.
UTM Patterns by Partner Type

Partner links break most often because each deal gets named on the spot. Fix the pattern per partner type once: utm_medium names the kind of deal, utm_source names who sent the traffic.

Partner typeutm_sourceutm_mediumutm_campaignutm_content
Newsletter{partner} (one per partner, across all their publications)newsletter{partner}-{publication}-{yyyy}-{mm}{placement}-{yyyy-mm-dd}
Creator (YouTube, LinkedIn, TikTok){platform}creator{creator}{post-date} or the video ID
Podcast{podcast}podcast{podcast}-{yyyy}-{mm}{spot}-{yyyy-mm-dd} (pre-roll, mid-roll)
Affiliate{partner}affiliate{partner}-affiliateplacement, if they have several
Community{community}community{community}-{program}the channel or post, if known
  • Use creator as the medium for paid creator deals, not social (which mixes them with your organic posts) or video (which mixes them with paid video ads). The platform goes in utm_source.
  • One link per placement. A newsletter that runs you on two dates gets two links, so each date's clicks stay separate. The monthly utm_campaign rolls them up.
  • Add a custom channel group in GA4. GA4's default grouping sends mediums like newsletter, creator, podcast, and community to Unassigned (only affiliate and email map to a default channel). Create a channel group with a rule per medium so partner traffic shows up as its own channels.
  • Podcast and video links often aren't clickable, so pair the UTM link with a promo code or vanity URL. See influencer-marketing for the rest of partner measurement.

The partner-type pattern is adapted from Wispr Flow's link-creator skill (MIT), published in the skills.marketing library.

Traffic From AI Assistants

You can't tag links that ChatGPT, Claude, Perplexity, Gemini, or Copilot put in their answers. Some of those visits arrive with a referrer (chatgpt.com, perplexity.ai) or an assistant-added utm_source; many arrive as direct, or come later through a branded search.

  • Add a GA4 channel group rule that matches known assistant referrers and sources into an "AI assistants" channel, and update the list as new assistants appear.
  • Treat that channel as the floor. Assistant-driven visits that show up as direct or branded search can be most of the effect, and they won't carry the referrer.
  • For measuring the full effect (exposure, delayed visits, and longer attribution windows), see ai-seo. For reconciling it with other sources, see attribution.

Debugging and Validation

Testing Tools
ToolUse For
GA4 DebugViewReal-time event monitoring
GTM Preview ModeTest triggers before publish
Browser ExtensionsTag Assistant, dataLayer Inspector
Validation Checklist
  • Events firing on correct triggers
  • Property values populating correctly
  • No duplicate events
  • Works across browsers and mobile
  • Conversions recorded correctly
  • No PII leaking
Common Issues
IssueCheck
Events not firingTrigger config, GTM loaded
Wrong valuesVariable path, data layer structure
Duplicate eventsMultiple containers, trigger firing twice

Privacy and Compliance

Considerations
  • Cookie consent required in EU/UK/CA
  • No PII in analytics properties
  • Data retention settings
  • User deletion capabilities
Implementation
  • Use consent mode (wait for consent)
  • IP anonymization
  • Only collect what you need
  • Integrate with consent management platform

Output Format

Tracking Plan Document
# [Site/Product] Tracking Plan

## Overview
- Tools: GA4, GTM
- Last updated: [Date]

## Events

| Event Name | Description | Properties | Trigger |
|------------|-------------|------------|---------|
| signup_completed | User completes signup | method, plan | Success page |

## Custom Dimensions

| Name | Scope | Parameter |
|------|-------|-----------|
| user_type | User | user_type |

## Conversions

| Conversion | Event | Counting |
|------------|-------|----------|
| Signup | signup_completed | Once per session |

Task-Specific Questions

  1. What tools are you using (GA4, Mixpanel, etc.)?
  2. What key actions do you want to track?
  3. What decisions will this data inform?
  4. Who implements - dev team or marketing?
  5. Are there privacy/consent requirements?
  6. What's already tracked?

Tool Integrations

For implementation, see the tools registry. Key analytics tools:

ToolBest ForMCPGuide
GA4Web analytics, Google ecosystem✓ga4.md
MixpanelProduct analytics, event tracking-mixpanel.md
AmplitudeProduct analytics, cohort analysis-amplitude.md
PostHogOpen-source analytics, session replay-posthog.md
SegmentCustomer data platform, routing-segment.md

Related Skills

  • ab-testing: For experiment tracking
  • conversion-tracking: For getting conversions (including GA4 key events from forms and bookings) to ad platforms and GA4, and verifying they arrive
  • attribution: For attribution models, multi-touch/MMM/incrementality, and reconciling conflicting numbers across tools (once tracking is live)
  • seo-audit: For organic traffic analysis
  • cro: For conversion optimization (uses this data)
  • revops: For pipeline metrics, CRM tracking, and revenue attribution
4 more files in this skill
  • evals/evals.json · 9 KB
    {
      "skill_name": "analytics",
      "evals": [
        {
          "id": 1,
          "prompt": "Help me set up analytics tracking for our B2B SaaS product. We use GA4 and GTM. We need to track signups, feature usage, and upgrade events.",
          "expected_output": "Should check for product-marketing.md first. Should apply the 'track for decisions' principle — ask what decisions the tracking will inform. Should use the event naming convention (object_action, lowercase with underscores). Should define essential events for SaaS: signup_completed, trial_started, feature_used, plan_upgraded, etc. Should provide GA4 implementation details with proper event parameters. Should include GTM data layer push examples. Should organize output as a tracking plan with event name, trigger, parameters, and purpose for each event.",
          "assertions": [
            "Checks for product-marketing.md",
            "Applies 'track for decisions' principle",
            "Uses object_action naming convention",
            "Defines essential SaaS events (signup, feature usage, upgrade)",
            "Provides GA4 implementation details",
            "Includes GTM data layer examples",
            "Output follows tracking plan format"
          ],
          "files": []
        },
        {
          "id": 2,
          "prompt": "What UTM parameters should we use? We run ads on Google, Meta, and LinkedIn, plus send a weekly newsletter and post on LinkedIn organically.",
          "expected_output": "Should apply the UTM parameter strategy framework. Should define consistent UTM conventions: source (google, meta, linkedin, newsletter), medium (cpc, paid-social, email, organic-social), campaign (naming convention with date or identifier). Should provide specific UTM examples for each channel mentioned. Should warn about common UTM mistakes (inconsistent casing, redundant parameters, missing medium). Should recommend a UTM tracking spreadsheet or naming convention document.",
          "assertions": [
            "Applies UTM parameter strategy",
            "Defines source, medium, and campaign conventions",
            "Provides specific UTM examples for each channel",
            "Uses consistent naming conventions (lowercase)",
            "Warns about common UTM mistakes",
            "Recommends tracking documentation"
          ],
          "files": []
        },
        {
          "id": 3,
          "prompt": "our tracking seems broken — we're seeing duplicate events and our conversion numbers in GA4 don't match what our database shows. help?",
          "expected_output": "Should trigger on casual phrasing. Should apply the debugging and validation framework. Should systematically check for common issues: duplicate GTM tags firing, missing event deduplication, incorrect trigger conditions, cross-domain tracking issues, consent mode filtering. Should provide specific debugging steps: use GA4 DebugView, GTM Preview mode, browser developer tools. Should address the GA4 vs database discrepancy (common causes: consent mode, ad blockers, client-side vs server-side tracking, session timeout differences).",
          "assertions": [
            "Triggers on casual phrasing",
            "Applies debugging and validation framework",
            "Checks for duplicate tag firing",
            "Provides specific debugging tools (GA4 DebugView, GTM Preview)",
            "Addresses GA4 vs database discrepancy",
            "Lists common causes of data mismatches",
            "Provides systematic troubleshooting steps"
          ],
          "files": []
        },
        {
          "id": 4,
          "prompt": "We're launching an e-commerce store and need to set up tracking from scratch. What events do we absolutely need?",
          "expected_output": "Should reference the essential events by site type, specifically e-commerce. Should define the e-commerce event taxonomy: product_viewed, product_added_to_cart, cart_viewed, checkout_started, checkout_step_completed, purchase_completed, product_removed_from_cart. Should include enhanced e-commerce parameters (item_id, item_name, price, quantity, etc.). Should follow object_action naming convention. Should organize as a tracking plan with priorities (must-have vs nice-to-have).",
          "assertions": [
            "References essential events for e-commerce site type",
            "Defines full e-commerce event taxonomy",
            "Includes enhanced e-commerce parameters",
            "Follows object_action naming convention",
            "Organizes by priority (must-have vs nice-to-have)",
            "Provides tracking plan format output"
          ],
          "files": []
        },
        {
          "id": 5,
          "prompt": "We need to make sure our tracking is GDPR compliant. We have European users and we're using GA4, Hotjar, and Facebook Pixel.",
          "expected_output": "Should apply the privacy and compliance framework. Should address GDPR requirements for each tool: consent before tracking, consent management platform (CMP) setup, GA4 consent mode configuration, conditional loading of Hotjar and Facebook Pixel. Should recommend a consent hierarchy (necessary, analytics, marketing). Should provide GTM implementation for consent-based tag firing. Should mention data retention settings in GA4. Should address cookie banner requirements.",
          "assertions": [
            "Applies privacy and compliance framework",
            "Addresses GDPR requirements specifically",
            "Recommends consent management platform",
            "Covers GA4 consent mode configuration",
            "Addresses conditional loading for each tool",
            "Provides consent hierarchy",
            "Mentions data retention settings"
          ],
          "files": []
        },
        {
          "id": 6,
          "prompt": "Help me set up tracking for our A/B test. We want to measure which version of our pricing page converts better.",
          "expected_output": "Should recognize this overlaps with A/B test setup, not just analytics tracking. Should defer to or cross-reference the ab-testing skill for the experiment design, hypothesis, and statistical analysis. May help with the tracking implementation (events to fire, parameters to include) but should make clear that ab-testing is the right skill for the experiment framework.",
          "assertions": [
            "Recognizes overlap with A/B test setup",
            "References or defers to ab-testing skill",
            "May help with tracking implementation specifics",
            "Does not attempt to design the full experiment"
          ],
          "files": []
        },
        {
          "id": 7,
          "prompt": "GA4 enhanced measurement is enabled. I filtered outbound_click, site_search and video_engagement and got zero, but DebugView shows 12 click events with outbound=true, 7 view_search_results, 6 video_start, 4 video_progress and 2 video_complete. Which reports should I build? Do I need to add custom events?",
          "expected_output": "Identify the mismatched option labels/event names. Use click with outbound=true for the 12 outbound clicks, view_search_results for the 7 searches, and separate video_start/video_progress/video_complete reports for 6/4/2. Do not add custom duplicate events to fix a filter mismatch or sum all video events as unique views. Check enabled options, configured search query parameters, YouTube JS API support and DebugView; cross-domain measurement destinations do not produce outbound clicks.",
          "assertions": [
            "Uses actual enhanced-measurement event names instead of option labels",
            "Filters click by outbound=true and reports 12 outbound clicks",
            "Uses view_search_results and reports 7 searches",
            "Separates 6 video starts, 4 progress events and 2 completions",
            "Does not count all video events as unique views or create duplicate custom events",
            "Mentions relevant enhanced-measurement configuration and DebugView checks"
          ],
          "files": []
        },
        {
          "id": 8,
          "prompt": "Our GTM Custom JavaScript price variable parses .product-price text. USD $1,234.56 is tracked as 1, a European 1.234,56 display as 1.234, and missing prices become zero. How should we fix this without changing real free items?",
          "expected_output": "Use the application numeric amount and explicit currency or a machine-readable unformatted decimal data-price attribute. Do not strip symbols or guess locale separators. Return null for missing/malformed/nonfinite values and skip or diagnose the monetary event; preserve canonical zero for free items. Test grouped US and localized European display strings, ordinary decimals and missing/invalid values.",
          "assertions": [
            "Uses numeric application data or canonical machine-readable decimal",
            "Does not parse localized display strings or guess currency",
            "Preserves explicit zero for free items",
            "Missing or invalid amount is not converted to zero",
            "Tests grouped and localized display controls"
          ],
          "files": []
        }
      ]
    }
    
  • references/event-library.md · 9 KB

    Event Library Reference

    Comprehensive list of events to track by business type and context.

    Contents

    • Marketing Site Events (navigation & engagement, CTA & form interactions, conversion events)
    • Product/App Events (onboarding, core usage, errors & support)
    • Monetization Events (pricing & checkout, subscription management)
    • E-commerce Events (browsing, cart, checkout, post-purchase)
    • B2B / SaaS Specific Events (team & collaboration, integration events, account events)
    • Event Properties (Parameters)
    • Funnel Event Sequences

    Marketing Site Events

    Navigation & Engagement
    Event NameDescriptionProperties
    page_viewPage loaded (enhanced)page_title, page_location, content_group
    scroll_depthUser scrolled to thresholddepth (25, 50, 75, 100)
    outbound_link_clickedClick to external sitelink_url, link_text
    internal_link_clickedClick within sitelink_url, link_text, location
    video_playedVideo startedvideo_id, video_title, duration
    video_completedVideo finishedvideo_id, video_title, duration
    CTA & Form Interactions
    Event NameDescriptionProperties
    cta_clickedCall to action clickedbutton_text, cta_location, page
    form_startedUser began formform_name, form_location
    form_field_completedField filledform_name, field_name
    form_submittedForm successfully sentform_name, form_location
    form_errorForm validation failedform_name, error_type
    resource_downloadedAsset downloadedresource_name, resource_type
    Conversion Events
    Event NameDescriptionProperties
    signup_startedInitiated signupsource, page
    signup_completedFinished signupmethod, plan, source
    demo_requestedDemo form submittedcompany_size, industry
    contact_submittedContact form sentinquiry_type
    newsletter_subscribedEmail list signupsource, list_name
    trial_startedFree trial beganplan, source

    Product/App Events

    Onboarding
    Event NameDescriptionProperties
    signup_completedAccount createdmethod, referral_source
    onboarding_startedBegan onboarding-
    onboarding_step_completedStep finishedstep_number, step_name
    onboarding_completedAll steps donesteps_completed, time_to_complete
    onboarding_skippedUser skipped onboardingstep_skipped_at
    first_key_action_completedAha moment reachedaction_type
    Core Usage
    Event NameDescriptionProperties
    session_startedApp session begansession_number
    feature_usedFeature interactionfeature_name, feature_category
    action_completedCore action doneaction_type, count
    content_createdUser created contentcontent_type
    content_editedUser modified contentcontent_type
    content_deletedUser removed contentcontent_type
    search_performedIn-app searchquery, results_count
    settings_changedSettings modifiedsetting_name, new_value
    invite_sentUser invited othersinvite_type, count
    Errors & Support
    Event NameDescriptionProperties
    error_occurredError experiencederror_type, error_message, page
    help_openedHelp accessedhelp_type, page
    support_contactedSupport request madecontact_method, issue_type
    feedback_submittedUser feedback givenfeedback_type, rating

    Monetization Events

    Pricing & Checkout
    Event NameDescriptionProperties
    pricing_viewedPricing page seensource
    plan_selectedPlan chosenplan_name, billing_cycle
    checkout_startedBegan checkoutplan, value
    payment_info_enteredPayment submittedpayment_method
    purchase_completedPurchase successfulplan, value, currency, transaction_id
    purchase_failedPurchase failederror_reason, plan
    Subscription Management
    Event NameDescriptionProperties
    trial_startedTrial beganplan, trial_length
    trial_endedTrial expiredplan, converted (bool)
    subscription_upgradedPlan upgradedfrom_plan, to_plan, value
    subscription_downgradedPlan downgradedfrom_plan, to_plan
    subscription_cancelledCancelledplan, reason, tenure
    subscription_renewedRenewedplan, value
    billing_updatedPayment method changed-

    E-commerce Events

    Browsing
    Event NameDescriptionProperties
    product_viewedProduct page viewedproduct_id, product_name, category, price
    product_list_viewedCategory/list viewedlist_name, products[]
    product_searchedSearch performedquery, results_count
    product_filteredFilters appliedfilter_type, filter_value
    product_sortedSort appliedsort_by, sort_order
    Cart
    Event NameDescriptionProperties
    product_added_to_cartItem addedproduct_id, product_name, price, quantity
    product_removed_from_cartItem removedproduct_id, product_name, price, quantity
    cart_viewedCart page viewedcart_value, items_count
    Checkout
    Event NameDescriptionProperties
    checkout_startedCheckout begancart_value, items_count
    checkout_step_completedStep finishedstep_number, step_name
    shipping_info_enteredAddress enteredshipping_method
    payment_info_enteredPayment enteredpayment_method
    coupon_appliedCoupon usedcoupon_code, discount_value
    purchase_completedOrder placedtransaction_id, value, currency, items[]
    Post-Purchase
    Event NameDescriptionProperties
    order_confirmedConfirmation viewedtransaction_id
    refund_requestedRefund initiatedtransaction_id, reason
    refund_completedRefund processedtransaction_id, value
    review_submittedProduct reviewedproduct_id, rating

    B2B / SaaS Specific Events

    Team & Collaboration
    Event NameDescriptionProperties
    team_createdNew team/org madeteam_size, plan
    team_member_invitedInvite sentrole, invite_method
    team_member_joinedMember acceptedrole
    team_member_removedMember removedrole
    role_changedPermissions updateduser_id, old_role, new_role
    Integration Events
    Event NameDescriptionProperties
    integration_viewedIntegration page seenintegration_name
    integration_startedSetup beganintegration_name
    integration_connectedSuccessfully connectedintegration_name
    integration_disconnectedRemoved integrationintegration_name, reason
    Account Events
    Event NameDescriptionProperties
    account_createdNew accountsource, plan
    account_upgradedPlan upgradefrom_plan, to_plan
    account_churnedAccount closedreason, tenure, mrr_lost
    account_reactivatedReturned customerprevious_tenure, new_plan

    Event Properties (Parameters)

    Standard Properties to Include

    User Context:

    user_id: "12345"
    user_type: "free" | "trial" | "paid"
    account_id: "acct_123"
    plan_type: "starter" | "pro" | "enterprise"
    

    Session Context:

    session_id: "sess_abc"
    session_number: 5
    page: "/pricing"
    referrer: "https://google.com"
    

    Campaign Context:

    source: "google"
    medium: "cpc"
    campaign: "spring-sale"
    content: "hero-cta"
    

    Product Context (E-commerce):

    product_id: "SKU123"
    product_name: "Product Name"
    category: "Category"
    price: 99.99
    quantity: 1
    currency: "USD"
    

    Timing:

    timestamp: "2024-01-15T10:30:00Z"
    time_on_page: 45
    session_duration: 300
    

    Funnel Event Sequences

    Signup Funnel
    1. signup_started
    2. signup_step_completed (email)
    3. signup_step_completed (password)
    4. signup_completed
    5. onboarding_started
    Purchase Funnel
    1. pricing_viewed
    2. plan_selected
    3. checkout_started
    4. payment_info_entered
    5. purchase_completed
    E-commerce Funnel
    1. product_viewed
    2. product_added_to_cart
    3. cart_viewed
    4. checkout_started
    5. shipping_info_entered
    6. payment_info_entered
    7. purchase_completed
  • references/ga4-implementation.md · 8 KB

    GA4 Implementation Reference

    Detailed implementation guide for Google Analytics 4.

    Contents

    • Configuration (data streams, enhanced measurement events, recommended events)
    • Custom Events (gtag.js implementation, Google Tag Manager)
    • Conversions Setup (creating conversions, conversion values)
    • Custom Dimensions and Metrics (when to use, setup steps, examples)
    • Audiences (creating audiences, audience examples)
    • Debugging (DebugView, real-time reports, common issues)
    • Data Quality (filters, cross-domain tracking, session settings)
    • Integration with Google Ads (linking, audience export)

    Configuration

    Data Streams
    • One stream per platform (web, iOS, Android)
    • Enable enhanced measurement for automatic tracking
    • Configure data retention (2 months default, 14 months max)
    • Enable Google Signals (for cross-device, if consented)
    Enhanced Measurement Events (Automatic)
    EventDescriptionConfiguration
    page_viewPage loadsAutomatic
    scroll90% scroll depthToggle on/off
    clickOutbound link click (outbound: true); cross-domain measurement domains are excludedToggle on/off
    view_search_resultsSearch results page with a configured search query parameterConfigure query parameters
    video_start, video_progress, video_completeEmbedded YouTube start, progress and completionToggle on/off; JS API support required
    file_downloadPDF, docs, etc.Configurable extensions

    Use these exact names in event filters and triggers. The option labels "outbound clicks", "site search" and "video engagement" are not automatic event names. For video, report starts, progress milestones and completions separately; adding all three counts double-counts a viewing journey. A custom event with one of the old labels needs its own implementation. Verify enabled options and observed parameters in DebugView before expecting data.

    Contract: Google enhanced measurement events.

    Recommended Events

    Use Google's predefined events when possible for enhanced reporting:

    All properties:

    • login, sign_up
    • share
    • search

    E-commerce:

    • view_item, view_item_list
    • add_to_cart, remove_from_cart
    • begin_checkout
    • add_payment_info
    • purchase, refund

    Games:

    • level_up, unlock_achievement
    • post_score, spend_virtual_currency

    Reference: https://support.google.com/analytics/answer/9267735


    Custom Events

    gtag.js Implementation
    // Recommended event (your plan's signup_completed maps to GA4's sign_up)
    gtag('event', 'sign_up', {
      'method': 'email',
      'plan': 'free'
    });
    
    // Event with value
    gtag('event', 'purchase', {
      'transaction_id': 'T12345',
      'value': 99.99,
      'currency': 'USD',
      'items': [{
        'item_id': 'SKU123',
        'item_name': 'Product Name',
        'price': 99.99
      }]
    });
    
    // User properties
    gtag('set', 'user_properties', {
      'user_type': 'premium',
      'plan_name': 'pro'
    });
    
    // User ID (for logged-in users)
    gtag('config', 'GA_MEASUREMENT_ID', {
      'user_id': 'USER_ID'
    });
    
    Google Tag Manager (dataLayer)
    // Internal event name; a GTM GA4 Event tag sends it to GA4 as sign_up
    dataLayer.push({
      'event': 'signup_completed',
      'method': 'email',
      'plan': 'free'
    });
    
    // Set user properties
    dataLayer.push({
      'user_id': '12345',
      'user_type': 'premium'
    });
    
    // E-commerce purchase
    dataLayer.push({
      'event': 'purchase',
      'ecommerce': {
        'transaction_id': 'T12345',
        'value': 99.99,
        'currency': 'USD',
        'items': [{
          'item_id': 'SKU123',
          'item_name': 'Product Name',
          'price': 99.99,
          'quantity': 1
        }]
      }
    });
    
    // Clear ecommerce before sending (best practice)
    dataLayer.push({ ecommerce: null });
    dataLayer.push({
      'event': 'view_item',
      'ecommerce': {
        // ...
      }
    });
    

    Conversions Setup

    Creating Conversions
    1. Collect the event - Ensure event is firing in GA4
    2. Mark as conversion - Admin > Events > Mark as conversion
    3. Set counting method:
      • Once per session (leads, signups)
      • Every event (purchases)
    4. Import to Google Ads - For conversion-optimized bidding
    Conversion Values
    // Event with conversion value
    gtag('event', 'purchase', {
      'value': 99.99,
      'currency': 'USD'
    });
    

    Or set default value in GA4 Admin when marking conversion.


    Custom Dimensions and Metrics

    When to Use

    Custom dimensions:

    • Properties you want to segment/filter by
    • User attributes (plan type, industry)
    • Content attributes (author, category)

    Custom metrics:

    • Numeric values to aggregate
    • Scores, counts, durations
    Setup Steps
    1. Admin > Data display > Custom definitions
    2. Create dimension or metric
    3. Choose scope:
      • Event: Per event (content_type)
      • User: Per user (account_type)
      • Item: Per product (product_category)
    4. Enter parameter name (must match event parameter)
    Examples
    DimensionScopeParameterDescription
    User TypeUseruser_typeFree, trial, paid
    Content AuthorEventauthorBlog post author
    Product CategoryItemitem_categoryE-commerce category

    Audiences

    Creating Audiences

    Admin > Data display > Audiences

    Use cases:

    • Remarketing audiences (export to Ads)
    • Segment analysis
    • Trigger-based events
    Audience Examples

    High-intent visitors:

    • Viewed pricing page
    • Did not convert
    • In last 7 days

    Engaged users:

    • 3+ sessions
    • Or 5+ minutes total engagement

    Purchasers:

    • Purchase event
    • For exclusion or lookalike

    Debugging

    DebugView

    Enable with:

    • URL parameter: ?debug_mode=true
    • Chrome extension: GA Debugger
    • gtag: 'debug_mode': true in config

    View at: Reports > Configure > DebugView

    Real-Time Reports

    Check events within 30 minutes: Reports > Real-time

    Common Issues

    Events not appearing:

    • Check DebugView first
    • Verify gtag/GTM firing
    • Check filter exclusions

    Parameter values missing:

    • Custom dimension not created
    • Parameter name mismatch
    • Data still processing (24-48 hrs)

    Conversions not recording:

    • Event not marked as conversion
    • Event name doesn't match
    • Counting method (once vs. every)

    Data Quality

    Filters

    Admin > Data streams > [Stream] > Configure tag settings > Define internal traffic

    Exclude:

    • Internal IP addresses
    • Developer traffic
    • Testing environments
    Cross-Domain Tracking

    For multiple domains sharing analytics:

    1. Admin > Data streams > [Stream] > Configure tag settings
    2. Configure your domains
    3. List all domains that should share sessions
    Session Settings

    Admin > Data streams > [Stream] > Configure tag settings

    • Session timeout (default 30 min)
    • Engaged session duration (10 sec default)

    Integration with Google Ads

    Linking
    1. Admin > Product links > Google Ads links
    2. Enable auto-tagging in Google Ads
    3. Import conversions in Google Ads
    Audience Export

    Audiences created in GA4 can be used in Google Ads for:

    • Remarketing campaigns
    • Customer match
    • Similar audiences
  • references/gtm-implementation.md · 9 KB

    Google Tag Manager Implementation Reference

    Detailed guide for implementing tracking via Google Tag Manager.

    Contents

    • Container Structure (tags, triggers, variables)
    • Naming Conventions
    • Data Layer Patterns
    • Common Tag Configurations (GA4 configuration tag, GA4 event tag, Facebook pixel)
    • Preview and Debug
    • Workspaces and Versioning
    • Consent Management
    • Advanced Patterns (tag sequencing, exception handling, custom JavaScript variables)

    Container Structure

    Tags

    Tags are code snippets that execute when triggered.

    Common tag types:

    • GA4 Configuration (base setup)
    • GA4 Event (custom events)
    • Google Ads Conversion
    • Facebook Pixel
    • LinkedIn Insight Tag
    • Custom HTML (for other pixels)
    Triggers

    Triggers define when tags fire.

    Built-in triggers:

    • Page View: All Pages, DOM Ready, Window Loaded
    • Click: All Elements, Just Links
    • Form Submission
    • Scroll Depth
    • Timer
    • Element Visibility

    Custom triggers:

    • Custom Event (from dataLayer)
    • Trigger Groups (multiple conditions)
    Variables

    Variables capture dynamic values.

    Built-in (enable as needed):

    • Click Text, Click URL, Click ID, Click Classes
    • Page Path, Page URL, Page Hostname
    • Referrer
    • Form Element, Form ID

    User-defined:

    • Data Layer variables
    • JavaScript variables
    • Lookup tables
    • RegEx tables
    • Constants

    Naming Conventions

    Recommended Format
    [Type] - [Description] - [Detail]
    
    Tags:
    GA4 - Event - Signup Completed
    GA4 - Config - Base Configuration
    FB - Pixel - Page View
    HTML - LiveChat Widget
    
    Triggers:
    Click - CTA Button
    Submit - Contact Form
    View - Pricing Page
    Custom - signup_completed
    
    Variables:
    DL - user_id
    JS - Current Timestamp
    LT - Campaign Source Map
    

    Data Layer Patterns

    Basic Structure
    // Initialize (in <head> before GTM)
    window.dataLayer = window.dataLayer || [];
    
    // Push event
    dataLayer.push({
      'event': 'event_name',
      'property1': 'value1',
      'property2': 'value2'
    });
    
    Page Load Data
    // Set on page load (before GTM container)
    window.dataLayer = window.dataLayer || [];
    dataLayer.push({
      'pageType': 'product',
      'contentGroup': 'products',
      'user': {
        'loggedIn': true,
        'userId': '12345',
        'userType': 'premium'
      }
    });
    
    Form Submission
    document.querySelector('#contact-form').addEventListener('submit', function() {
      dataLayer.push({
        'event': 'form_submitted',
        'formName': 'contact',
        'formLocation': 'footer'
      });
    });
    
    Button Click
    document.querySelector('.cta-button').addEventListener('click', function() {
      dataLayer.push({
        'event': 'cta_clicked',
        'ctaText': this.innerText,
        'ctaLocation': 'hero'
      });
    });
    
    E-commerce Events
    // Product view
    dataLayer.push({ ecommerce: null }); // Clear previous
    dataLayer.push({
      'event': 'view_item',
      'ecommerce': {
        'items': [{
          'item_id': 'SKU123',
          'item_name': 'Product Name',
          'price': 99.99,
          'item_category': 'Category',
          'quantity': 1
        }]
      }
    });
    
    // Add to cart
    dataLayer.push({ ecommerce: null });
    dataLayer.push({
      'event': 'add_to_cart',
      'ecommerce': {
        'items': [{
          'item_id': 'SKU123',
          'item_name': 'Product Name',
          'price': 99.99,
          'quantity': 1
        }]
      }
    });
    
    // Purchase
    dataLayer.push({ ecommerce: null });
    dataLayer.push({
      'event': 'purchase',
      'ecommerce': {
        'transaction_id': 'T12345',
        'value': 99.99,
        'currency': 'USD',
        'tax': 5.00,
        'shipping': 10.00,
        'items': [{
          'item_id': 'SKU123',
          'item_name': 'Product Name',
          'price': 99.99,
          'quantity': 1
        }]
      }
    });
    

    Common Tag Configurations

    GA4 Configuration Tag

    Tag Type: Google Analytics: GA4 Configuration

    Settings:

    • Measurement ID: G-XXXXXXXX
    • Send page view: Checked (for pageviews)
    • User Properties: Add any user-level dimensions

    Trigger: All Pages

    GA4 Event Tag

    Tag Type: Google Analytics: GA4 Event

    Settings:

    • Configuration Tag: Select your config tag
    • Event Name: {{DL - event_name}} or hardcode
    • Event Parameters: Add parameters from dataLayer

    Trigger: Custom Event with event name match

    Facebook Pixel - Base

    Tag Type: Custom HTML

    <script>
      !function(f,b,e,v,n,t,s)
      {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
      n.callMethod.apply(n,arguments):n.queue.push(arguments)};
      if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
      n.queue=[];t=b.createElement(e);t.async=!0;
      t.src=v;s=b.getElementsByTagName(e)[0];
      s.parentNode.insertBefore(t,s)}(window, document,'script',
      'https://connect.facebook.net/en_US/fbevents.js');
      fbq('init', 'YOUR_PIXEL_ID');
      fbq('track', 'PageView');
    </script>
    

    Trigger: All Pages

    Facebook Pixel - Event

    Tag Type: Custom HTML

    <script>
      fbq('track', 'Lead', {
        content_name: '{{DL - form_name}}'
      });
    </script>
    

    Trigger: Custom Event - form_submitted


    Preview and Debug

    Preview Mode
    1. Click "Preview" in GTM
    2. Enter site URL
    3. GTM debug panel opens at bottom

    What to check:

    • Tags fired on this event
    • Tags not fired (and why)
    • Variables and their values
    • Data layer contents
    Debug Tips

    Tag not firing:

    • Check trigger conditions
    • Verify data layer push
    • Check tag sequencing

    Wrong variable value:

    • Check data layer structure
    • Verify variable path (nested objects)
    • Check timing (data may not exist yet)

    Multiple firings:

    • Check trigger uniqueness
    • Look for duplicate tags
    • Check tag firing options

    Workspaces and Versioning

    Workspaces

    Use workspaces for team collaboration:

    • Default workspace for production
    • Separate workspaces for large changes
    • Merge when ready
    Version Management

    Best practices:

    • Name every version descriptively
    • Add notes explaining changes
    • Review changes before publish
    • Keep production version noted

    Version notes example:

    v15: Added purchase conversion tracking
    - New tag: GA4 - Event - Purchase
    - New trigger: Custom Event - purchase
    - New variables: DL - transaction_id, DL - value
    - Tested: Chrome, Safari, Mobile
    

    Consent Management

    Consent Mode Integration
    // Default state (before consent)
    gtag('consent', 'default', {
      'analytics_storage': 'denied',
      'ad_storage': 'denied'
    });
    
    // Update on consent
    function grantConsent() {
      gtag('consent', 'update', {
        'analytics_storage': 'granted',
        'ad_storage': 'granted'
      });
    }
    
    GTM Consent Overview
    1. Enable Consent Overview in Admin
    2. Configure consent for each tag
    3. Tags respect consent state automatically

    Advanced Patterns

    Tag Sequencing

    Setup tags to fire in order: Tag Configuration > Advanced Settings > Tag Sequencing

    Use cases:

    • Config tag before event tags
    • Pixel initialization before tracking
    • Cleanup after conversion
    Exception Handling

    Trigger exceptions - Prevent tag from firing:

    • Exclude certain pages
    • Exclude internal traffic
    • Exclude during testing
    Custom JavaScript Variables
    // Get URL parameter
    function() {
      var params = new URLSearchParams(window.location.search);
      return params.get('campaign') || '(not set)';
    }
    
    // Get cookie value
    function() {
      var match = document.cookie.match('(^|;) ?user_id=([^;]*)(;|$)');
      return match ? match[2] : null;
    }
    
    // Read a machine-readable amount, not the localized display text.
    // Example: <span class="product-price" data-price="1234.56">$1,234.56</span>
    function() {
      var el = document.querySelector('.product-price');
      var raw = el ? el.getAttribute('data-price') : null;
      if (raw === null || !/^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/.test(raw)) return null;
      var amount = Number(raw);
      return isFinite(amount) ? amount : null;
    }
    

    For monetary tracking, prefer the numeric amount and currency from the application data layer. If a DOM variable is needed, have the application render data-price as an unformatted, non-negative decimal in major currency units; pass its currency separately. Do not infer the amount or currency from presentation text: parseFloat turns $1,234.56 into 1 after removing $, and localized separators have different meanings. A missing or invalid amount returns null, so skip that monetary event or diagnose it before sending; reserve 0 for an explicitly free item.