DEV Community

Cover image for Your Vibe-Coded Analytics Only Tracks You. I Wrote a Checker.
Vincent for Polydraft

Posted on

Your Vibe-Coded Analytics Only Tracks You. I Wrote a Checker.

This week on X, a Kyle Gawley post from November 24 was going around again: software is a $1.4 trillion market, and yet someone will still declare it dead because they "vibe coded their google analytics over the weekend." In the thread, samtestsai added the punchline I keep seeing: the vibe-coded Google Analytics only ever tracks one visitor. Him.

That is not a Realtime glitch. It is usually a leftover from the prompt that installed the tag.

The coding agent pastes the official gtag snippet. Then it wraps the config call in if (location.hostname === 'localhost') so a test property will not get polluted. It leaves debug_mode: true on. It hardcodes page_location to http://localhost:5173/ because that is where Vite is running. And the measurement id is still the placeholder from the docs, G-XXXXXXXXXX. The founder opens Realtime, hits the site from the dev server, sees themselves, and ships it. Chrome looks like a record shop. Production analytics is dark.

It does not matter whether the site came from Cursor, Claude Code or an AI website builder. If the snippet you ship only runs on the developer's laptop, or only points at a fake id, this applies.

So I wrote the kind of site a coding agent produces for "a neighborhood record shop in East Nashville with hours, a buy-records page, and a Friday in-store." The HTML is prerendered on purpose. There is a real title, a real H1, hours, and an address — this is not an empty #root. Then I wrote a short checker, analytics_tag.py, that reads the local HTML and source files and reports leftover or broken analytics. I ran it on the gated snippet, on the same site after I only removed the localhost if, and on a version with a real-looking measurement id and no debug flags. All the numbers below come from those three runs.

The fixture

The business is fictional. It is called Cedar Room Records, and it sells new and used vinyl on East Lapis Street in Nashville. The "before" tree is a finished-looking marketing site: a title, an H1, hours, a phone number, and JSON-LD. The leftovers are all in one script block in the head.

Here is the analytics that actually got deployed, with the body omitted.

<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
  // Only enable analytics while developing so we do not pollute the property.
  if (location.hostname === 'localhost' || location.hostname === '127.0.0.1') {
    window.dataLayer = window.dataLayer || [];
    function gtag(){ dataLayer.push(arguments); }
    gtag('js', new Date());
    gtag('config', 'G-XXXXXXXXXX', {
      debug_mode: true,
      page_location: 'http://localhost:5173/'
    });
  }
</script>
Enter fullscreen mode Exit fullscreen mode

If you open the site in a browser on your laptop, you see a visitor in Realtime. If you open the same files on the production host, the library may load, the config call never runs, and the measurement id was never yours in the first place.

The checker

analytics_tag.py reads a local HTML file — or the HTML and JS/TS/JSX files under a directory — and looks for analytics snippets. It does not call Google, it does not open a browser, and it does not prove that hits arrive in a property. Pass --host if you want it to flag a hardcoded page_location that does not match the production hostname.

It reports:

  • a snippet gated to localhost, 127.0.0.1, import.meta.env.DEV, or NODE_ENV !== 'production'
  • a placeholder measurement id such as G-XXXXXXXXXX, GTM-XXXXXXX, or YOUR_MEASUREMENT_ID
  • a Universal Analytics UA- property (those stopped collecting on 1 July 2023)
  • debug_mode: true or traffic_type: 'internal' left on
  • a hardcoded page_location, page_path, or cookie_domain pointing at localhost or a preview host
  • no analytics snippet at all
  • a Content-Security-Policy that loads gtag but does not allow googletagmanager.com or google-analytics.com
  • send_page_view: false with no manual page_view event (warning)
  • a client-side router with no virtual page view (warning)

It does not claim Google will count a given session. A localhost gate is the sharp one: production visitors are never sent. A placeholder id is almost as sharp: the hits go nowhere you can see. debug_mode on a real id is a messier hint — DebugView gets noisy, and some filters will drop the traffic. Either way, you should not ship it.

analytics_tag.py (about 680 lines, 13 tests)
#!/usr/bin/env python3
"""analytics_tag.py — static checker for leftover or broken analytics tags.

Reads local HTML and source files. Does not call Google, does not open a
browser, and does not prove that hits arrive in a property.
"""

from __future__ import annotations

import argparse
import os
import re
import sys
import tempfile
import unittest
from dataclasses import dataclass, field
from pathlib import Path

VERSION = "1.0"
SKIP_DIRS = {
    "node_modules",
    ".git",
    ".hg",
    ".svn",
    ".next",
    ".cache",
    ".venv",
    "venv",
    "__pycache__",
    "coverage",
    "dist",  # still scanned if you point the tool AT dist/
    "build",
}
# If the user passes a tree, we *do* want dist/ and build/ when they are the
# deploy root. We only skip them when they appear as nested noise next to src/.
SKIP_NESTED = {"node_modules", ".git", ".hg", ".svn", ".next", ".cache", ".venv", "venv", "__pycache__", "coverage"}
EXTENSIONS = {
    ".html",
    ".htm",
    ".js",
    ".jsx",
    ".ts",
    ".tsx",
    ".mjs",
    ".cjs",
    ".vue",
    ".astro",
    ".svelte",
}

GA4_RE = re.compile(r"\bG-[A-Z0-9]{6,14}\b")
GTM_RE = re.compile(r"\bGTM-[A-Z0-9]{4,12}\b")
UA_RE = re.compile(r"\bUA-\d{4,10}-\d{1,3}\b")
PLACEHOLDER_ID_RE = re.compile(
    r"""
    \b(
        G-(?:X{6,14}|0{6,14}|YOUR[A-Z0-9]*|EXAMPLE[A-Z0-9]*|
           PLACEHOLDER[A-Z0-9]*|CHANGEME[A-Z0-9]*|INSERT[A-Z0-9]*|
           TODO[A-Z0-9]*)
      | GTM-(?:X{4,12}|0{4,12}|XXXXXXX)
      | UA-(?:X+|0+)(?:-\d+)?
    )\b
    """,
    re.I | re.X,
)
PLACEHOLDER_NAME_RE = re.compile(
    r"""['"](?:YOUR_?(?:GA|GTM|MEASUREMENT|ANALYTICS)_?ID|MEASUREMENT_ID|
         GA_MEASUREMENT_ID|GTM_ID|INSERT_?ID_?HERE|YOUR_DOMAIN)['"]""",
    re.I | re.X,
)
GTAG_HINT_RE = re.compile(
    r"gtag\s*\(|googletagmanager\.com|google-analytics\.com|"
    r"window\.dataLayer|function\s+gtag\s*\(|gtag/js",
    re.I,
)
ANALYTICS_HINT_RE = re.compile(
    r"gtag\s*\(|googletagmanager\.com|google-analytics\.com|www\.google-analytics\.com|"
    r"GTM-[A-Z0-9]+|\bG-[A-Z0-9]{6,14}\b|\bUA-\d+-\d+|"
    r"plausible\.io|usefathom\.com|umami\.is|cdn\.usefathom|"
    r"posthog\.|mixpanel|analytics\.js|ga\(\s*['\"]create|"
    r"goatcounter|cloudflareinsights|simpleanalytics|matomo|amplitude",
    re.I,
)
ROUTER_RE = re.compile(
    r"\b(BrowserRouter|createBrowserRouter|HashRouter|RouterProvider|"
    r"createWebHistory|vue-router|useNavigate|useRouter)\b",
)
VIRTUAL_PAGEVIEW_RE = re.compile(
    r"""gtag\(\s*['"]event['"]\s*,\s*['"]page_view['"]"""
    r"""|gtag\(\s*['"]config['"]"""
    r"""|analytics\.page\s*\(|plausible\(\s*['"]pageview['"]"""
    r"""|posthog\.capture\(\s*['"]\$pageview['"]"""
    r"""|mixpanel\.track\(\s*['"]Page\s*View['"]""",
    re.I,
)
DEBUG_RE = re.compile(r"""debug_mode\s*:\s*true|['"]debug_mode['"]\s*:\s*true""", re.I)
INTERNAL_TRAFFIC_RE = re.compile(
    r"""traffic_type\s*:\s*['"]internal['"]|['"]traffic_type['"]\s*:\s*['"]internal['"]""",
    re.I,
)
PAGE_LOCATION_RE = re.compile(
    r"""(?:page_location|page_path|cookie_domain)\s*:\s*['"]([^'"]+)['"]""",
    re.I,
)
MANUAL_PAGEVIEW_RE = re.compile(
    r"""gtag\(\s*['"]event['"]\s*,\s*['"]page_view['"]"""
    r"""|analytics\.page\s*\(|plausible\(\s*['"]pageview['"]"""
    r"""|posthog\.capture\(\s*['"]\$pageview['"]"""
    r"""|mixpanel\.track\(\s*['"]Page\s*View['"]""",
    re.I,
)
SEND_PAGE_VIEW_FALSE_RE = re.compile(r"""send_page_view\s*:\s*false""", re.I)
CSP_RE = re.compile(
    r"""<meta\s+http-equiv\s*=\s*['"]Content-Security-Policy['"][^>]*content\s*=\s*['"]([^'"]+)['"]"""
    r"""|Content-Security-Policy['"]?\s*:\s*['"]([^'"]+)""",
    re.I,
)
IF_RE = re.compile(r"\bif\s*\(([^)]{0,400})\)\s*\{", re.S)
AND_GATE_RE = re.compile(
    r"""((?:location\.hostname|window\.location\.hostname|import\.meta\.env\.DEV|process\.env\.NODE_ENV)[^\n]{0,200}?)&&\s*\{?""",
    re.I,
)
LOCAL_POS_RE = re.compile(
    r"""(?:location\.hostname|window\.location\.hostname|location\.host)\s*===?\s*['"](?:localhost|127\.0\.0\.1)['"]"""
    r"""|['"](?:localhost|127\.0\.0\.1)['"]\s*===?\s*(?:location\.hostname|window\.location\.hostname|location\.host)"""
    r"""|\.includes\(\s*(?:location\.hostname|window\.location\.hostname)\s*\)"""
    r"""|import\.meta\.env\.DEV\b"""
    r"""|process\.env\.NODE_ENV\s*===?\s*['"]development['"]"""
    r"""|process\.env\.NODE_ENV\s*!==?\s*['"]production['"]""",
    re.I,
)
LOCAL_NEG_RE = re.compile(
    r"""(?:location\.hostname|window\.location\.hostname|location\.host)\s*!==?\s*['"](?:localhost|127\.0\.0\.1)['"]"""
    r"""|['"](?:localhost|127\.0\.0\.1)['"]\s*!==?\s*(?:location\.hostname|window\.location\.hostname|location\.host)"""
    r"""|import\.meta\.env\.PROD\b"""
    r"""|process\.env\.NODE_ENV\s*===?\s*['"]production['"]"""
    r"""|process\.env\.NODE_ENV\s*!==?\s*['"]development['"]""",
    re.I,
)
LOOPBACK_HOST_RE = re.compile(r"""(?:^|://)(?:localhost|127\.0\.0\.1)(?::\d+)?(?:/|$)""", re.I)
PREVIEW_HOST_RE = re.compile(
    r"""(?:^|://)(?:[^/]+\.)?(?:vercel\.app|netlify\.app|netlify\.com|ngrok-free\.app|ngrok\.io|fly\.dev|onrender\.com)(?:/|$)""",
    re.I,
)

# Hosts commonly used as placeholder domains in snippets.
PLACEHOLDER_DOMAINS = {
    "example.com",
    "yoursite.com",
    "yourdomain.com",
    "your-site.com",
    "mysite.com",
    "localhost",
}


@dataclass
class Finding:
    code: str
    message: str
    path: str = ""
    severity: str = "error"  # error | warning


@dataclass
class Report:
    root: Path
    files: list[Path] = field(default_factory=list)
    ids: list[str] = field(default_factory=list)
    findings: list[Finding] = field(default_factory=list)
    title: str = ""
    h1: str = ""
    notes: list[str] = field(default_factory=list)

    def add(self, code: str, message: str, path: str = "", severity: str = "error") -> None:
        key = (code, message, path, severity)
        if any((f.code, f.message, f.path, f.severity) == key for f in self.findings):
            return
        self.findings.append(Finding(code, message, path, severity))


def rel(path: Path, root: Path) -> str:
    try:
        return str(path.relative_to(root))
    except ValueError:
        return str(path)


def collect_files(root: Path) -> list[Path]:
    if root.is_file():
        return [root]
    out: list[Path] = []
    for dirpath, dirnames, filenames in os.walk(root):
        p = Path(dirpath)
        # If the user pointed us at dist/ or build/, keep it. If they pointed
        # us at a repo, skip those as nested output unless they are the root.
        dirnames[:] = [
            d
            for d in dirnames
            if d not in SKIP_NESTED and not d.startswith(".")
        ]
        for name in filenames:
            fp = p / name
            if fp.suffix.lower() in EXTENSIONS:
                out.append(fp)
    return sorted(out)


def extract_brace_block(src: str, open_idx: int) -> str:
    if open_idx >= len(src) or src[open_idx] != "{":
        return ""
    depth = 0
    for i, ch in enumerate(src[open_idx:], open_idx):
        if ch == "{":
            depth += 1
        elif ch == "}":
            depth -= 1
            if depth == 0:
                return src[open_idx : i + 1]
    return src[open_idx:]


def looks_like_placeholder_id(value: str) -> bool:
    v = value.strip()
    if PLACEHOLDER_ID_RE.fullmatch(v) or PLACEHOLDER_ID_RE.search(v):
        # fullmatch on the id itself
        if PLACEHOLDER_ID_RE.fullmatch(v):
            return True
    if re.fullmatch(r"G-X{6,14}", v, re.I):
        return True
    if re.fullmatch(r"G-0{6,14}", v, re.I):
        return True
    # All-X or obviously fake after the prefix.
    m = re.fullmatch(r"G-([A-Z0-9]{6,14})", v, re.I)
    if m and re.fullmatch(r"X+", m.group(1), re.I):
        return True
    if re.search(r"YOUR|EXAMPLE|PLACEHOLDER|CHANGEME|INSERT|TODO", v, re.I):
        return True
    return bool(PLACEHOLDER_ID_RE.fullmatch(v))


def first_heading(html: str, tag: str) -> str:
    m = re.search(rf"<{tag}[^>]*>(.*?)</{tag}>", html, re.I | re.S)
    if not m:
        return ""
    text = re.sub(r"<[^>]+>", "", m.group(1))
    return re.sub(r"\s+", " ", text).strip()


def staging_kind(value: str) -> str | None:
    if LOOPBACK_HOST_RE.search(value) or "localhost" in value.lower() or "127.0.0.1" in value:
        return "loopback"
    if PREVIEW_HOST_RE.search(value):
        return "preview"
    return None


def condition_is_local_positive(cond: str) -> bool:
    """True when the condition is true only in local / dev."""
    if LOCAL_NEG_RE.search(cond) and not LOCAL_POS_RE.search(cond):
        return False
    # Mixed conditions: if both pos and neg appear, be conservative.
    if LOCAL_NEG_RE.search(cond) and LOCAL_POS_RE.search(cond):
        return False
    return bool(LOCAL_POS_RE.search(cond))


def find_localhost_gates(src: str, path_label: str, report: Report) -> None:
    for m in IF_RE.finditer(src):
        cond = m.group(1)
        if not condition_is_local_positive(cond):
            continue
        # m.end() is just after "{", so the brace starts at m.end()-1
        block = extract_brace_block(src, m.end() - 1)
        if ANALYTICS_HINT_RE.search(block) or GTAG_HINT_RE.search(block):
            report.add(
                "localhost-gated",
                f"analytics snippet runs only when ({_squash(cond)}) in {path_label}",
                path_label,
            )
    for m in AND_GATE_RE.finditer(src):
        left = m.group(1)
        if not condition_is_local_positive(left):
            continue
        window = src[m.start() : m.start() + 400]
        if ANALYTICS_HINT_RE.search(window) or GTAG_HINT_RE.search(window):
            report.add(
                "localhost-gated",
                f"analytics snippet is short-circuit gated on ({_squash(left)}) in {path_label}",
                path_label,
            )


def _squash(s: str) -> str:
    return re.sub(r"\s+", " ", s).strip()[:160]


def extract_csp(src: str) -> str:
    m = CSP_RE.search(src)
    if not m:
        return ""
    return m.group(1) or m.group(2) or ""


def csp_allows_google(csp: str) -> bool:
    lower = csp.lower()
    # script-src or default-src must mention the Google hosts or be extremely loose.
    if "script-src" in lower:
        section = lower.split("script-src", 1)[1].split(";", 1)[0]
    elif "default-src" in lower:
        section = lower.split("default-src", 1)[1].split(";", 1)[0]
    else:
        return True
    if "*" in section.split() or "'unsafe-eval'" in section and "http:" in section:
        # still require the vendor host unless wildcard is present
        if "*" in section.split():
            return True
    return "googletagmanager.com" in section or "google-analytics.com" in section


def scan_text(src: str, path_label: str, report: Report, host: str | None) -> None:
    if path_label.endswith((".html", ".htm")) or "<title" in src.lower():
        report.title = report.title or first_heading(src, "title")
        report.h1 = report.h1 or first_heading(src, "h1")

    for mid in GA4_RE.findall(src):
        if mid not in report.ids:
            report.ids.append(mid)
        if looks_like_placeholder_id(mid):
            report.add(
                "placeholder-id",
                f"placeholder measurement id {mid} in {path_label}",
                path_label,
            )
    for mid in GTM_RE.findall(src):
        if mid not in report.ids:
            report.ids.append(mid)
        if looks_like_placeholder_id(mid):
            report.add(
                "placeholder-id",
                f"placeholder container id {mid} in {path_label}",
                path_label,
            )
    for mid in UA_RE.findall(src):
        if mid not in report.ids:
            report.ids.append(mid)
        report.add(
            "legacy-ua",
            f"Universal Analytics id {mid} in {path_label} (UA properties stopped collecting on 1 July 2023)",
            path_label,
        )
        if looks_like_placeholder_id(mid):
            report.add(
                "placeholder-id",
                f"placeholder measurement id {mid} in {path_label}",
                path_label,
            )
    if PLACEHOLDER_NAME_RE.search(src) and (GTAG_HINT_RE.search(src) or ANALYTICS_HINT_RE.search(src)):
        report.add(
            "placeholder-id",
            f"placeholder measurement id name in {path_label}",
            path_label,
        )

    find_localhost_gates(src, path_label, report)

    if DEBUG_RE.search(src) and GTAG_HINT_RE.search(src):
        report.add(
            "debug-mode",
            f"debug_mode: true left on in {path_label}",
            path_label,
        )
    if INTERNAL_TRAFFIC_RE.search(src) and GTAG_HINT_RE.search(src):
        report.add(
            "debug-mode",
            f"traffic_type: 'internal' left on in {path_label}",
            path_label,
        )

    for m in PAGE_LOCATION_RE.finditer(src):
        key = m.group(0).split(":")[0].strip()
        val = m.group(1)
        kind = staging_kind(val)
        if kind:
            code = "hardcoded-page-location" if "cookie" not in key.lower() else "cookie-domain-localhost"
            if "cookie" in key.lower():
                report.add(
                    "cookie-domain-localhost",
                    f"cookie_domain is {val} ({kind}) in {path_label}",
                    path_label,
                )
            else:
                report.add(
                    "hardcoded-page-location",
                    f"{key} is {val} ({kind}) in {path_label}",
                    path_label,
                )
        elif host:
            # If an absolute URL is hardcoded to a different public host, warn.
            mhost = re.search(r"https?://([^/:]+)", val, re.I)
            if mhost and mhost.group(1).lower() != host.lower() and "cookie" not in key.lower():
                report.add(
                    "hardcoded-page-location",
                    f"{key} is {val} (does not match --host {host}) in {path_label}",
                    path_label,
                    severity="warning",
                )

    if SEND_PAGE_VIEW_FALSE_RE.search(src) and not MANUAL_PAGEVIEW_RE.search(src):
        report.add(
            "send-page-view-false",
            f"send_page_view: false and no manual page_view event in {path_label}",
            path_label,
            severity="warning",
        )

    csp = extract_csp(src)
    if csp and GTAG_HINT_RE.search(src) and not csp_allows_google(csp):
        report.add(
            "csp-blocks",
            f"Content-Security-Policy in {path_label} does not allow googletagmanager.com or google-analytics.com",
            path_label,
        )


def scan_tree(root: Path, host: str | None = None) -> Report:
    root = root.resolve()
    report = Report(root=root)
    files = collect_files(root)
    report.files = files
    joined = []
    router = False
    virtual = False
    for fp in files:
        try:
            text = fp.read_text(encoding="utf-8", errors="replace")
        except OSError:
            continue
        label = rel(fp, root)
        joined.append(text)
        scan_text(text, label, report, host)
        if ROUTER_RE.search(text):
            router = True
        if VIRTUAL_PAGEVIEW_RE.search(text):
            virtual = True
    blob = "\n".join(joined)
    if not ANALYTICS_HINT_RE.search(blob):
        report.add("missing", "no analytics snippet or measurement id found in the scanned files")
    if router and not virtual:
        report.add(
            "spa-no-virtual-pageviews",
            "a client-side router is present, but no virtual page_view / page() call was found",
            severity="warning",
        )
    # Duplicate: same GA4 id configured more than twice in one file is a smell;
    # gtag.js?id= plus gtag('config', id) is normal (count 2). Flag 3+.
    for mid in [i for i in report.ids if i.startswith("G-") and not i.startswith("GTM-")]:
        total = len(re.findall(re.escape(mid), blob))
        config_hits = len(re.findall(rf"gtag\(\s*['\"]config['\"]\s*,\s*['\"]{re.escape(mid)}['\"]", blob))
        script_hits = len(re.findall(rf"gtag/js\?id={re.escape(mid)}", blob))
        if config_hits >= 2 or (config_hits + script_hits >= 3 and config_hits >= 2):
            report.add(
                "duplicate-tags",
                f"measurement id {mid} is configured more than once",
                severity="warning",
            )
    return report


def format_report(report: Report, host: str | None = None) -> str:
    errors = [f for f in report.findings if f.severity == "error"]
    warnings = [f for f in report.findings if f.severity == "warning"]
    files = ", ".join(rel(p, report.root) for p in report.files[:8])
    if len(report.files) > 8:
        files += f", … ({len(report.files)} files)"
    ids = ", ".join(report.ids) if report.ids else "(none)"
    lines = [
        "analytics_tag.py  (local files only)",
        f"root: {report.root}",
        "",
        "PAGE",
        f"  title              {report.title or '(none)'}",
        f"  H1                 {report.h1 or '(none)'}",
        f"  files              {files or '(none)'}",
        f"  measurement ids    {ids}",
        "",
        "FINDINGS",
    ]
    if not report.findings:
        lines.append("  (none)")
    else:
        for f in report.findings:
            flag = "  - " if f.severity == "error" else "  ~ "
            lines.append(f"{flag}{f.code:<28} {f.message}")
    lines.append("")
    lines.append("VERDICT")
    if any(f.code == "localhost-gated" for f in errors):
        lines.append("  Analytics is gated to localhost or a dev environment.")
        lines.append("  Production visitors will not be recorded. The one")
        lines.append("  visitor you see in Realtime is probably you, on the dev server.")
    elif any(f.code == "missing" for f in errors):
        lines.append("  No analytics snippet was found in the scanned files.")
    elif any(f.code == "placeholder-id" for f in errors):
        lines.append("  A measurement id is present, but it is still a placeholder.")
        lines.append("  Hits, if any, are not going to a real property.")
    elif any(f.code == "legacy-ua" for f in errors):
        lines.append("  The page still references a Universal Analytics property.")
        lines.append("  Those properties stopped collecting data on 1 July 2023.")
    elif errors:
        lines.append("  Analytics is present, but one or more production issues remain.")
    elif warnings:
        lines.append("  No hard errors. Warnings are listed above.")
    else:
        lines.append("  No leftover localhost gates, placeholder ids, debug flags,")
        lines.append("  or hardcoded dev page locations in the scanned files.")
        lines.append("  This does not prove hits arrive in your property.")
    if host:
        lines.append(f"  production host     {host}")
    lines.append("")
    return "\n".join(lines)


# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------


class AnalyticsTagTests(unittest.TestCase):
    def _scan_src(self, name: str, src: str, host: str | None = "cedarroom.example") -> Report:
        with tempfile.TemporaryDirectory() as td:
            p = Path(td) / name
            p.write_text(src, encoding="utf-8")
            return scan_tree(Path(td), host=host)

    def test_localhost_gate_detected(self):
        src = """
        <html><head><title>Test</title>
        <script>
          if (location.hostname === 'localhost' || location.hostname === '127.0.0.1') {
            gtag('config', 'G-CEDARROOM1');
          }
        </script></head><body><h1>Hi</h1></body></html>
        """
        r = self._scan_src("index.html", src)
        self.assertTrue(any(f.code == "localhost-gated" for f in r.findings))

    def test_production_gate_not_flagged(self):
        src = """
        <script>
          if (location.hostname !== 'localhost' && location.hostname !== '127.0.0.1') {
            gtag('config', 'G-CEDARROOM1');
          }
        </script>
        """
        r = self._scan_src("ok.js", src)
        self.assertFalse(any(f.code == "localhost-gated" for f in r.findings))

    def test_import_meta_env_dev_gate(self):
        src = """
        if (import.meta.env.DEV) {
          gtag('js', new Date());
          gtag('config', 'G-CEDARROOM1');
        }
        """
        r = self._scan_src("main.js", src)
        self.assertTrue(any(f.code == "localhost-gated" for f in r.findings))

    def test_placeholder_id(self):
        src = "<script src='https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX'></script>"
        r = self._scan_src("index.html", src)
        self.assertTrue(any(f.code == "placeholder-id" for f in r.findings))

    def test_real_id_not_placeholder(self):
        src = """
        <script async src='https://www.googletagmanager.com/gtag/js?id=G-CEDARROOM1'></script>
        <script>
          window.dataLayer = window.dataLayer || [];
          function gtag(){ dataLayer.push(arguments); }
          gtag('js', new Date());
          gtag('config', 'G-CEDARROOM1');
        </script>
        """
        r = self._scan_src("index.html", src)
        self.assertFalse(any(f.code == "placeholder-id" for f in r.findings))
        self.assertFalse(any(f.severity == "error" for f in r.findings))

    def test_legacy_ua(self):
        src = "ga('create', 'UA-12345678-1', 'auto');"
        r = self._scan_src("legacy.js", src)
        self.assertTrue(any(f.code == "legacy-ua" for f in r.findings))

    def test_debug_mode(self):
        src = "gtag('config', 'G-CEDARROOM1', { debug_mode: true });"
        r = self._scan_src("ga.js", src)
        self.assertTrue(any(f.code == "debug-mode" for f in r.findings))

    def test_hardcoded_page_location(self):
        src = "gtag('config', 'G-CEDARROOM1', { page_location: 'http://localhost:5173/' });"
        r = self._scan_src("ga.js", src)
        self.assertTrue(any(f.code == "hardcoded-page-location" for f in r.findings))

    def test_missing(self):
        src = "<html><head><title>None</title></head><body><h1>Hi</h1></body></html>"
        r = self._scan_src("index.html", src)
        self.assertTrue(any(f.code == "missing" for f in r.findings))

    def test_spa_warning(self):
        src = """
        import { BrowserRouter, Routes, Route } from 'react-router-dom';
        export function App(){ return <BrowserRouter><Routes><Route path='/' /></Routes></BrowserRouter>; }
        """
        r = self._scan_src("App.jsx", src)
        self.assertTrue(any(f.code == "spa-no-virtual-pageviews" for f in r.findings))

    def test_csp_blocks(self):
        src = """
        <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
        <script async src="https://www.googletagmanager.com/gtag/js?id=G-CEDARROOM1"></script>
        <script>gtag('config', 'G-CEDARROOM1');</script>
        """
        r = self._scan_src("index.html", src)
        self.assertTrue(any(f.code == "csp-blocks" for f in r.findings))

    def test_send_page_view_false(self):
        src = "gtag('config', 'G-CEDARROOM1', { send_page_view: false });"
        r = self._scan_src("ga.js", src)
        self.assertTrue(any(f.code == "send-page-view-false" for f in r.findings))

    def test_clean_fixture_shape(self):
        src = """<!doctype html><html><head>
        <title>Cedar Room Records | New and used vinyl in Nashville</title>
        <script async src="https://www.googletagmanager.com/gtag/js?id=G-CEDARROOM1"></script>
        <script>
          window.dataLayer = window.dataLayer || [];
          function gtag(){ dataLayer.push(arguments); }
          gtag('js', new Date());
          gtag('config', 'G-CEDARROOM1');
        </script>
        </head><body><h1>New and used vinyl in East Nashville</h1></body></html>
        """
        r = self._scan_src("index.html", src)
        self.assertEqual([f.code for f in r.findings], [])
        self.assertIn("Cedar Room Records", r.title)
        self.assertIn("vinyl", r.h1.lower())


def self_test() -> int:
    suite = unittest.defaultTestLoader.loadTestsFromTestCase(AnalyticsTagTests)
    result = unittest.TextTestRunner(verbosity=2).run(suite)
    return 0 if result.wasSuccessful() else 1


def main(argv: list[str] | None = None) -> int:
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("path", nargs="?", help="file or directory to scan")
    p.add_argument("--host", help="production hostname, used to flag mismatched page_location")
    p.add_argument("--self-test", action="store_true", help="run the unit tests")
    args = p.parse_args(argv)
    if args.self_test:
        return self_test()
    if not args.path:
        p.print_help()
        return 2
    root = Path(args.path)
    if not root.exists():
        print(f"analytics_tag.py: no such file or directory: {root}", file=sys.stderr)
        return 2
    report = scan_tree(root, host=args.host)
    sys.stdout.write(format_report(report, host=args.host))
    errors = [f for f in report.findings if f.severity == "error"]
    return 1 if errors else 0


if __name__ == "__main__":
    sys.exit(main())
Enter fullscreen mode Exit fullscreen mode

Run 1: the localhost gate on a finished page

$ python3 analytics_tag.py fixtures/before --host cedarroom.example

analytics_tag.py  (local files only)
root: fixtures/before

PAGE
  title              Cedar Room Records | New and used vinyl in Nashville
  H1                 New and used vinyl in East Nashville
  files              index.html
  measurement ids    G-XXXXXXXXXX

FINDINGS
  - placeholder-id               placeholder measurement id G-XXXXXXXXXX in index.html
  - localhost-gated              analytics snippet runs only when (location.hostname === 'localhost' || location.hostname === '127.0.0.1') in index.html
  - debug-mode                   debug_mode: true left on in index.html
  - hardcoded-page-location      page_location is http://localhost:5173/ (loopback) in index.html

VERDICT
  Analytics is gated to localhost or a dev environment.
  Production visitors will not be recorded. The one
  visitor you see in Realtime is probably you, on the dev server.
  production host     cedarroom.example
Enter fullscreen mode Exit fullscreen mode

A real title. A real H1. A shop address. And a config call that will not run once the site is on a custom domain. The measurement id is the placeholder from the setup docs. The page location is the Vite dev server. Debug mode is on, for a property that does not exist.

This is easy to miss because the failure looks like success in the tool you use all day. You are on localhost:5173. Realtime shows one user. The tag "works." The condition that makes it work is the same condition that hides it from everyone else.

Terminal output of analytics_tag.py on the Cedar Room Records fixture. The first run flags a localhost gate, a placeholder measurement id, debug_mode, and a localhost page_location; the final run has no findings.

Why a localhost gate is worse than a missing tag

A missing tag is an omission. You go to Realtime, you see nothing, and you go add the snippet. A localhost gate is a false positive. You go to Realtime from the dev server, you see yourself, and you stop looking.

Coding agents add the gate for a good reason. Nobody wants a half-built preview to flood a production property, and the official docs do talk about debug mode. The mistake is leaving the gate, the debug flag, and the placeholder id in the document you are about to point a domain at.

Clearing only the if is not enough, which is the next run.

Run 2: the gate is gone, the placeholder is not

The first rewrite removes the localhost if and leaves everything else. The visible page did not change. The library now runs on the production host too.

$ python3 analytics_tag.py fixtures/mid --host cedarroom.example

PAGE
  title              Cedar Room Records | New and used vinyl in Nashville
  H1                 New and used vinyl in East Nashville
  files              index.html
  measurement ids    G-XXXXXXXXXX

FINDINGS
  - placeholder-id               placeholder measurement id G-XXXXXXXXXX in index.html
  - debug-mode                   debug_mode: true left on in index.html
  - hardcoded-page-location      page_location is http://localhost:5173/ (loopback) in index.html

VERDICT
  A measurement id is present, but it is still a placeholder.
  Hits, if any, are not going to a real property.
  production host     cedarroom.example
Enter fullscreen mode Exit fullscreen mode

The hide-the-traffic bug is gone. The hits, if any, still do not belong to you. And if you later paste a real id but leave page_location set to http://localhost:5173/, every production pageview is reported as a visit to the dev server.

Taking the if off is necessary. It is not sufficient.

Run 3: a real id, no debug, no hardcoded location

The second rewrite puts in a dummy production id (G-CEDARROOM1 in the fixture — not a real property), drops debug_mode, and drops the hardcoded page_location so the browser can report the URL the visitor actually requested. The visible page did not change.

$ python3 analytics_tag.py fixtures/after --host cedarroom.example

PAGE
  title              Cedar Room Records | New and used vinyl in Nashville
  H1                 New and used vinyl in East Nashville
  files              index.html
  measurement ids    G-CEDARROOM1

FINDINGS
  (none)

VERDICT
  No leftover localhost gates, placeholder ids, debug flags,
  or hardcoded dev page locations in the scanned files.
  This does not prove hits arrive in your property.
  production host     cedarroom.example
Enter fullscreen mode Exit fullscreen mode

That is the bar the checker can hold you to. Not "Realtime showed me on my laptop." "The snippet runs off localhost, the id is not a placeholder, debug mode is off, and the page location is not a dev-server URL." Confirming that the property actually receives production traffic is a later step, in the GA4 interface, with a real measurement id.

Table comparing the Cedar Room Records fixture across three runs: a localhost-gated placeholder tag, the same tag with the gate removed, and a version with a real-looking id and no debug flags.

Three decisions

Once the checker has barked at you, the work is three decisions, not one "take the localhost if off" prompt.

  1. Do not gate production analytics on localhost or import.meta.env.DEV. If you need to keep a preview from polluting a property, use a separate measurement id for preview hosts, or a server-side check on the preview hostname. The document behind the custom domain should send pageviews.
  2. Put a real measurement id in, and turn debug_mode off. G-XXXXXXXXXX is a documentation placeholder. debug_mode: true and traffic_type: 'internal' belong in a local session, not in the shipped head.
  3. Do not hardcode page_location to the dev server. Let the library use the URL the browser requested. A production visit reported as http://localhost:5173/ is how you get a property that only ever seems to see you.

Three decisions for production analytics: do not gate the snippet on localhost, use a real measurement id with debug mode off, and do not hardcode page_location to the dev server.

This sits next to a post-launch SEO checklist: analytics is not a tag you paste once on launch day and forget. You still have to confirm the property is receiving the production host, not the Vite port you tested on. The same idea shows up in a plan for SEO on a new website launch: the launch is not only DNS, titles, and a sitemap. It is also "does the tag fire for anyone but the person who built the site?"

What I would do with a real repo

If I were handed a vibe-coded marketing site tomorrow, I would check this before I trusted the dashboard:

  1. View-source the production URL, or the files you are about to deploy, and search for gtag, G-, GTM-, localhost, and debug_mode.
  2. Confirm the measurement id is the one in your GA4 admin, not G-XXXXXXXXXX.
  3. Run python3 analytics_tag.py . --host yourdomain.com against the HTML and JS you are shipping.
  4. Load the production URL in a private window, without an ad blocker, and confirm a pageview lands in Realtime on that id. Then run the checker again after the next prompt. A scan you run once is a scan that is out of date after the agent "adds analytics" or "turns on debug mode."

A site built with an AI website builder still has to pass this test. The builder is doing the right kind of work if the published document already has a real measurement id, no localhost gate, and no leftover debug flags. Generating the first version of the site is the cheap part. Knowing whether anyone but you is being counted is the part that decides whether the dashboard is a product metric or a diary.

What we do in PolyDraft, and what we do not claim

PolyDraft is the AI website builder we work on. It publishes server-rendered HTML to your own Cloudflare account, so the document a visitor fetches is the document you can view-source. That makes a check like this easy to run. It does not make it unnecessary. An agent can still wrap a tag in a localhost if, or leave a placeholder id in the head. We still run checks like these on what we ship, and you should run them on anything with your name on the domain, whoever or whatever built it.

Before you trust the dashboard

  1. Read the production head, not just Realtime on your laptop. If you see a localhost if, a placeholder id, or debug_mode: true, stop there.
  2. Confirm the measurement id matches the property in your GA4 admin.
  3. Confirm page_location is not hardcoded to a dev server or a preview host.
  4. Save the files and run analytics_tag.py --host yourdomain.com again after the next change. Then confirm one production pageview in Realtime from a browser that is not yours on localhost.

Ten minutes, most of it against HTML you already have, all of it on your own site. Cheaper than spending a month optimizing a funnel that only ever contained one person.

Top comments (0)