Tips & Tricks (अपडेट: 3/6/2026)

Claude Code Analytics: GA4, GSC, Cloudflare से PV और Revenue

Claude Code से GA4, GSC, Cloudflare analytics, PV, CTA, revenue events और checks implement करें।

Claude Code Analytics: GA4, GSC, Cloudflare से PV और Revenue

Analytics tag लगाने से पहले design होता है

Analytics implementation का मतलब PV, clicks, article completion, inquiry, product click और purchase path को decision-ready data में बदलना है। PV यानी page view. Event यानी user action की record entry. Conversion या GA4 key event वह action है जिसे business outcome मानता है। UTM URL में campaign source की पहचान है। Consent यह rule है कि browser analytics भेज सकता है या नहीं।

Claude Code यहाँ इसलिए उपयोगी है क्योंकि वह measurement plan को code, tests और documentation में बदल सकता है। Masa ने इस site में गलती की थी: PV बढ़ रहा था, लेकिन product link clicks, lead form completion और free resource signup अलग-अलग track नहीं थे। Traffic अच्छा दिख रहा था, पर revenue path दिखाई नहीं दे रहा था।

यह guide GA4, Search Console, Cloudflare Workers Analytics Engine, Plausible और PostHog को practical roles में रखता है। Related reading: SEO optimization, A/B testing, performance optimization, और content funnel audit

Measurement plan पहले लिखें

Claude Code से tool list नहीं, decision table बनवाएँ।

इस content site के लिए analytics implementation plan बनाइए।
Goal सिर्फ PV growth नहीं है; article completion, CTA click, inquiry, product click और purchase path improve करना है।
Columns: business_question, event_name, trigger, required_params, provider, decision.
जहाँ fit हो वहाँ GA4 recommended events use करें। Custom events snake_case में रखें।
business_questionevent_nametriggerrequired_paramsproviderdecision
क्या article पूरा पढ़ा गया?article_read_completeFooter 70% visibleslug, category, reading_time_secGA4/PostHogintro, headings, internal links सुधारें
क्या CTA click हुआ?cta_clickproduct, training या PDF CTA clickslug, cta_id, cta_type, target_urlGA4/Plausible/PostHogCTA position और copy बदलें
inquiry पूरी हुई?generate_leadform submit successform_id, lead_source, value, currencyGA4/PostHogform और offer clarity सुधारें
product link intent बनाता है?purchase_link_clickproduct page या Gumroad clickproduct_id, price, currency, slugGA4/PostHogarticle-product match बदलें
कौन से search queries valuable हैं?gsc_query_pageSearch Console API page/query देpage, query, clicks, impressions, ctr, positionGSCtitle और updates prioritize करें
browser tag traffic miss कर रहा है?edge_page_viewCloudflare Worker request receive करेpath, country, status, duration_msCloudflareblockers और speed issues देखें

GA4 events को Google के recommended events से मिलाएँ। generate_lead standard में fit होता है; article completion custom रह सकता है।

flowchart LR
  Reader["Reader"]
  Consent["Consent"]
  Browser["browser analytics.js"]
  Server["GA4 Measurement Protocol"]
  GSC["Search Console API"]
  Edge["Cloudflare Worker"]
  Dashboard["Content, revenue, quality dashboards"]

  Reader --> Consent --> Browser
  Browser --> Server
  GSC --> Dashboard
  Edge --> Dashboard
  Browser --> Dashboard
  Server --> Dashboard

Event contract JS में रखें

Event contract names और required params को stable रखता है।

// event-plan.mjs
import { pathToFileURL } from "node:url";

export const eventPlan = {
  article_read_complete: { required: ["slug", "category", "reading_time_sec"], providers: ["GA4", "PostHog"] },
  cta_click: { required: ["slug", "cta_id", "cta_type", "target_url"], providers: ["GA4", "Plausible", "PostHog"] },
  generate_lead: { required: ["form_id", "lead_source", "value", "currency"], providers: ["GA4", "PostHog"] },
  purchase_link_click: { required: ["product_id", "price", "currency", "slug"], providers: ["GA4", "PostHog"] },
  campaign_landing: { required: ["utm_source", "utm_medium", "utm_campaign"], providers: ["GA4"] },
};

export function validateEvent(name, params = {}) {
  const contract = eventPlan[name];
  if (!contract) return { ok: false, missing: ["known_event_name"] };
  const missing = contract.required.filter((key) => params[key] === undefined || params[key] === "");
  return { ok: missing.length === 0, missing };
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  console.log(validateEvent("cta_click", { slug: "claude-code-analytics-implementation", cta_id: "products_footer", cta_type: "product", target_url: "/en/products/" }));
}

products और training अलग CTAs हैं। Product click template या guide interest दिखाता है; training click team adoption या consultation intent दिखाता है।

Browser layer

Browser layer consent, UTM, params cleanup और providers को एक जगह संभालता है।

// browser-analytics.js
const CONSENT_KEY = "analytics_consent";
const UTM_KEYS = ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"];

function inBrowser() {
  return typeof window !== "undefined" && typeof localStorage !== "undefined";
}

function hasConsent() {
  return inBrowser() && localStorage.getItem(CONSENT_KEY) === "granted";
}

function cleanParams(params = {}) {
  return Object.fromEntries(Object.entries(params).filter(([, value]) => value !== undefined && value !== null && value !== "").map(([key, value]) => [key, typeof value === "boolean" ? Number(value) : value]));
}

export function setAnalyticsConsent(state) {
  if (!inBrowser()) return;
  localStorage.setItem(CONSENT_KEY, state);
  window.gtag?.("consent", "update", { analytics_storage: state, ad_storage: "denied" });
}

export function readUtmParams() {
  if (!inBrowser()) return {};
  const current = new URLSearchParams(window.location.search);
  const saved = JSON.parse(localStorage.getItem("landing_utm") || "{}");
  const next = { ...saved };
  for (const key of UTM_KEYS) {
    const value = current.get(key);
    if (value) next[key] = value;
  }
  localStorage.setItem("landing_utm", JSON.stringify(next));
  return next;
}

export function trackEvent(name, params = {}) {
  if (!hasConsent()) return;
  const payload = cleanParams({ ...readUtmParams(), ...params });
  window.gtag?.("event", name, payload);
  window.plausible?.(name, { props: payload });
  window.posthog?.capture(name, payload);
}

generate_lead button click पर नहीं, successful form submit के बाद भेजें। Article completion को footer visible होने पर एक बार भेजें।

GA4, GSC, Cloudflare examples

Server-confirmed events GA4 Measurement Protocol से भेजें और validation server से check करें।

// ga4-server-event.mjs
import { pathToFileURL } from "node:url";

const { GA4_MEASUREMENT_ID, GA4_API_SECRET, GA4_DEBUG } = process.env;
if (!GA4_MEASUREMENT_ID || !GA4_API_SECRET) throw new Error("GA4_MEASUREMENT_ID and GA4_API_SECRET are required");

export async function sendGa4Event({ clientId, name, params = {} }) {
  const endpoint = new URL(GA4_DEBUG === "1" ? "https://www.google-analytics.com/debug/mp/collect" : "https://www.google-analytics.com/mp/collect");
  endpoint.searchParams.set("measurement_id", GA4_MEASUREMENT_ID);
  endpoint.searchParams.set("api_secret", GA4_API_SECRET);
  const response = await fetch(endpoint, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ client_id: clientId, events: [{ name, params }] }) });
  if (!response.ok) throw new Error("GA4 request failed with status " + response.status);
  if (GA4_DEBUG === "1") {
    const result = await response.json();
    if (result.validationMessages?.length) throw new Error(JSON.stringify(result.validationMessages, null, 2));
  }
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  await sendGa4Event({ clientId: "555.1234567890", name: "generate_lead", params: { form_id: "training", lead_source: "article_footer", value: 1, currency: "USD" } });
  console.log("sent");
}

Search demand Search Analytics API से आता है।

// gsc-query.mjs
import { pathToFileURL } from "node:url";

const { GSC_ACCESS_TOKEN, GSC_SITE_URL = "https://example.com/" } = process.env;
if (!GSC_ACCESS_TOKEN) throw new Error("GSC_ACCESS_TOKEN is required");

export async function querySearchConsole({ startDate, endDate, pageContains }) {
  const endpoint = "https://www.googleapis.com/webmasters/v3/sites/" + encodeURIComponent(GSC_SITE_URL) + "/searchAnalytics/query";
  const response = await fetch(endpoint, {
    method: "POST",
    headers: { authorization: "Bearer " + GSC_ACCESS_TOKEN, "content-type": "application/json" },
    body: JSON.stringify({ startDate, endDate, dimensions: ["page", "query"], dimensionFilterGroups: pageContains ? [{ filters: [{ dimension: "page", operator: "contains", expression: pageContains }] }] : [], rowLimit: 25 }),
  });
  if (!response.ok) throw new Error("Search Console request failed with status " + response.status);
  return response.json();
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  const data = await querySearchConsole({ startDate: "2026-05-01", endDate: "2026-05-31", pageContains: "/blog/claude-code-analytics-implementation" });
  console.log(JSON.stringify(data.rows ?? [], null, 2));
}

Edge events के लिए Workers Analytics Engine और writeDataPoint example देखें।

// cloudflare-worker.js
function json(data, status = 200) {
  return new Response(JSON.stringify(data), { status, headers: { "content-type": "application/json" } });
}

export default {
  async fetch(request, env) {
    if (request.method !== "POST") return json({ ok: false, error: "method_not_allowed" }, 405);
    const event = await request.json().catch(() => null);
    if (!event?.event_name || !event?.slug) return json({ ok: false, error: "event_name_and_slug_required" }, 400);
    const country = request.cf?.country || request.headers.get("cf-ipcountry") || "XX";
    env.ANALYTICS?.writeDataPoint({ blobs: [event.event_name, event.slug, event.cta_id || "", country], doubles: [Number(event.value || 1)], indexes: [String(event.slug).slice(0, 96)] });
    return json({ ok: true });
  },
};

Cloudflare में email, name, free text या raw IP न रखें।

Use cases और pitfalls

Use case 1: SEO. GSC impressions high और CTR low हो तो title/description बदलें। PV high और completion low हो तो intro, heading order और examples बदलें। Use case 2: products. purchase_link_click में product_id, price, currency और slug डालें। Use case 3: consultation. cta_click interest है; generate_lead completed form है। Use case 4: campaigns. UTM first landing पर save करें ताकि बाद की inquiry source रखे।

Pitfalls: event names बदलना, consent से पहले send करना, server और browser conversion duplicate करना, GSC को complete log समझना, बहुत scripts से Core Web Vitals बिगाड़ना। Dashboards को content growth, revenue funnel और technical quality में बाँटें। Release के 24 घंटे में GA4 DebugView, Realtime, Plausible Goals, PostHog Events और Cloudflare aggregate देखें।

Existing setup सुधारने के लिए products से templates लें या team rollout के लिए training में measurement plan, implementation review और dashboard cleanup साथ करें।

#Claude Code #analytics #tracking #React #TypeScript
मुफ़्त

मुफ़्त PDF: Claude Code cheatsheet

Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.

हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.

Masa

लेखक के बारे में

Masa

Claude Code workflow और team adoption पर काम करने वाला engineer.