Engineering Note · October 9, 2026

How to Send GA4 Events Through Cloudflare Workers

Google Analytics 4 (GA4) collects website interaction data to help businesses understand user behaviour, measure conversions, and analyse ecommerce performance. Browser-based tracking through Google tags is a common implementation, but some applications also need a server-side mechanism for sending events.

Cloudflare Workers provides a serverless environment for receiving website events, validating their payloads, and forwarding supported events to GA4 through the Measurement Protocol.

This architecture can be useful for WooCommerce purchases, backend-confirmed conversions, and event-processing systems that already have a server-side tracking gateway.

However, sending events from a server does not automatically preserve GA4 attribution or session context. Correct client identifiers, session information, timestamps, consent handling, and event parameters remain important.

This guide explains how to implement a basic GA4 event gateway using Cloudflare Workers and how to extend it for ecommerce tracking.

1. Understanding GA4 Measurement Protocol

GA4 Measurement Protocol allows applications to send measurement events directly to Google Analytics through HTTPS requests.

For a web data stream, the endpoint uses a Measurement ID and an API secret. The request body contains the client identifier and one or more events with their associated parameters.

A typical server-side tracking flow looks like this:

Website / WooCommerce
↓
HTTPS Event Request
↓
Cloudflare Worker
↓
Event Validation and Normalization
↓
GA4 Measurement Protocol
↓
Google Analytics 4

The Worker acts as an intermediary. It does not replace the GA4 collection infrastructure; it prepares and forwards supported events to the Measurement Protocol endpoint.

Official documentation: GA4 Measurement Protocol — Sending Events

2. Why Use Cloudflare Workers?

Cloudflare Workers can handle incoming HTTP requests and make outbound HTTPS requests without requiring a continuously running traditional application server.

For GA4 integrations, a Worker can:

  • Receive events from a website or backend system.
  • Validate event names and required parameters.
  • Normalize ecommerce event payloads.
  • Keep the GA4 API secret on the server.
  • Route events to GA4 through Measurement Protocol.
  • Integrate GA4 delivery into a larger tracking gateway.

Cloudflare Workers is particularly useful when a project needs lightweight event processing rather than a full server-side tagging container.

However, it does not automatically solve missing client identifiers, incorrect attribution, duplicate purchases, or consent-related problems.

3. Prerequisites

Before implementing the gateway, prepare:

  1. A GA4 property with a web data stream.
  2. The stream’s Measurement ID, typically beginning with G-.
  3. A Measurement Protocol API secret created for the relevant data stream.
  4. A Cloudflare Worker.
  5. A defined event schema for incoming requests.

The Measurement ID identifies the web data stream. The API secret authenticates Measurement Protocol requests and must remain private.

Create the API secret in the GA4 interface under the web stream’s Measurement Protocol settings.

Do not expose the API secret in browser JavaScript or public repositories.

4. Configure Cloudflare Worker Secrets

Store the API secret as a Cloudflare Worker secret.

Using Wrangler, run:

npx wrangler secret put GA4_API_SECRET

Configure the Measurement ID as a Worker environment variable named GA4_MEASUREMENT_ID.

The following example assumes these two bindings are available:

  • GA4_MEASUREMENT_ID
  • GA4_API_SECRET

Keep configuration specific to the intended GA4 property and web data stream.

Reference: Cloudflare Workers Secrets

5. Define the Incoming Event Schema

The website or backend should send a structured payload that the Worker can validate before forwarding it to GA4.

For example, a purchase event might look like this:

{
  "client_id": "123456789.1791500000",
  "timestamp_micros": "1791560000000000",
  "events": [
    {
      "name": "purchase",
      "params": {
        "transaction_id": "12345",
        "currency": "USD",
        "value": 149.99,
        "session_id": 1791559000,
        "engagement_time_msec": 1,
        "items": [
          {
            "item_id": "product-101",
            "item_name": "Example Product",
            "price": 149.99,
            "quantity": 1
          }
        ]
      }
    }
  ]
}

This is an illustrative internal request structure. The Worker will forward the relevant fields to Measurement Protocol, subject to validation.

The example uses a Unix timestamp in microseconds for timestamp_micros and a Unix timestamp in seconds for session_id.

The client ID should represent the appropriate GA4 web client identifier. It must not be replaced with an arbitrary random value if the goal is to associate the event with an existing browser-based user journey.

For real purchases, use the actual transaction details and currency from the source system.

6. Implement the Cloudflare Worker

The following starter implementation accepts a JSON POST request at /ga4, performs basic validation, and forwards a single event to GA4 Measurement Protocol.

It is designed to demonstrate the delivery flow, not to serve as a complete production gateway. It does not implement authentication for incoming callers, consent enforcement, durable retries, persistent deduplication, or comprehensive event-specific validation.

function jsonResponse(data, status = 200) {
  return new Response(JSON.stringify(data), {
    status,
    headers: {
      "Content-Type": "application/json; charset=utf-8",
      "Cache-Control": "no-store"
    }
  });
}

const ALLOWED_EVENTS = new Set([
  "page_view",
  "view_item",
  "add_to_cart",
  "begin_checkout",
  "add_payment_info",
  "purchase",
  "search",
  "generate_lead",
  "sign_up",
  "add_to_wishlist"
]);

export default {
  async fetch(request, env) {
    const url = new URL(request.url);

    if (url.pathname !== "/ga4") {
      return jsonResponse({ error: "Not found" }, 404);
    }

    if (request.method !== "POST") {
      return jsonResponse(
        { error: "Method not allowed" },
        405
      );
    }

    const contentType =
      request.headers.get("content-type") || "";

    if (!contentType.toLowerCase().includes("application/json")) {
      return jsonResponse(
        { error: "JSON content type required" },
        415
      );
    }

    if (!env.GA4_MEASUREMENT_ID || !env.GA4_API_SECRET) {
      return jsonResponse(
        { error: "GA4 configuration missing" },
        500
      );
    }

    let input;

    try {
      input = await request.json();
    } catch {
      return jsonResponse({ error: "Invalid JSON" }, 400);
    }

    if (
      !input ||
      typeof input !== "object" ||
      Array.isArray(input) ||
      typeof input.client_id !== "string" ||
      input.client_id.length === 0 ||
      input.client_id.length > 256 ||
      !Array.isArray(input.events) ||
      input.events.length === 0 ||
      input.events.length > 25
    ) {
      return jsonResponse(
        { error: "Invalid event payload" },
        400
      );
    }

    for (const event of input.events) {
      if (
        !event ||
        typeof event !== "object" ||
        Array.isArray(event) ||
        typeof event.name !== "string" ||
        !ALLOWED_EVENTS.has(event.name) ||
        (
          event.params !== undefined &&
          (
            !event.params ||
            typeof event.params !== "object" ||
            Array.isArray(event.params)
          )
        )
      ) {
        return jsonResponse(
          { error: "Invalid event structure" },
          400
        );
      }
    }

    const payload = {
      client_id: input.client_id,
      events: input.events
    };

    if (input.timestamp_micros !== undefined) {
      if (
        typeof input.timestamp_micros !== "string" ||
        !/^[0-9]{1,20}$/.test(input.timestamp_micros)
      ) {
        return jsonResponse(
          { error: "Invalid timestamp_micros" },
          400
        );
      }

      payload.timestamp_micros = input.timestamp_micros;
    }

    const endpoint = new URL(
      "https://www.google-analytics.com/mp/collect"
    );

    endpoint.searchParams.set(
      "measurement_id",
      env.GA4_MEASUREMENT_ID
    );

    endpoint.searchParams.set(
      "api_secret",
      env.GA4_API_SECRET
    );

    let upstream;

    try {
      upstream = await fetch(endpoint.toString(), {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(payload)
      });
    } catch {
      return jsonResponse(
        { error: "GA4 request failed" },
        502
      );
    }

    if (!upstream.ok) {
      return jsonResponse(
        {
          error: "GA4 endpoint returned an error",
          upstream_status: upstream.status
        },
        502
      );
    }

    return jsonResponse({
      accepted: true,
      destination: "GA4 Measurement Protocol"
    });
  }
};

What the code does

  1. Restricts requests to the /ga4 endpoint.
  2. Accepts only POST requests with JSON content.
  3. Checks that GA4 configuration exists.
  4. Validates the client ID and event structure.
  5. Restricts event names to an allowlist.
  6. Forwards the validated payload to GA4 Measurement Protocol.
  7. Returns a response indicating that the request was accepted by the upstream endpoint.

Important limitation

GA4 Measurement Protocol’s collection endpoint can return a successful HTTP response even when some event data is invalid or not processed as expected. Therefore, an HTTP success response is not proof that the event appeared in GA4 reports.

Use the Measurement Protocol validation endpoint during development, together with DebugView and other GA4 diagnostics.

7. Preserve Client and Session Context

One of the most important challenges in server-side GA4 tracking is preserving the context needed for meaningful reporting.

Client ID

The client_id identifies the web client associated with the event. For browser-based tracking, it should generally come from the existing GA4 client identifier when available.

Generating a new random client ID for every server event can fragment measurement and prevent appropriate association with existing browser activity.

Session ID

The session_id event parameter can help associate a server-side event with the relevant GA4 session.

For events intended to belong to an existing browser session, use the genuine session information when it is available and applicable.

A session ID alone does not guarantee correct attribution. Event timing, client identity, campaign context, consent, and other implementation details also matter.

Event timestamp

Measurement Protocol supports event timestamps in microseconds through timestamp_micros.

Use an accurate timestamp from the source event when appropriate. Do not substitute the gateway’s processing time for the original event time without considering the measurement implications.

Official reference: GA4 Measurement Protocol Reference

8. Implement WooCommerce Ecommerce Events

For WooCommerce, GA4 Measurement Protocol can support server-side ecommerce events such as:

  • view_item
  • add_to_cart
  • begin_checkout
  • add_payment_info
  • purchase

The actual implementation must map the WooCommerce event data into GA4’s expected event and item parameters.

For a purchase event, common fields include:

  • transaction_id
  • currency
  • value
  • items
  • Appropriate client and session context

A purchase event should use the actual transaction details from WooCommerce. The transaction ID should remain stable across retries and repeated notifications.

The integration must also define when a purchase is considered complete. Repeated checkout-page visits, payment callbacks, or order-status updates should not unintentionally produce multiple purchase events for the same transaction.

GA4’s ecommerce event requirements are documented here:

GA4 Ecommerce Measurement

9. Avoid Duplicate GA4 Events

If browser-based GA4 tracking and server-side Measurement Protocol both report the same event, duplicate measurement can occur unless the implementation explicitly prevents it.

Do not assume GA4 automatically deduplicates all matching events based on a generic event_id.

For purchases, GA4 uses transaction_id as an important mechanism for transaction deduplication in supported reporting contexts. Other event types require their own deliberate duplicate-prevention strategy.

Recommended practices:

  1. Decide which system is responsible for each event.
  2. Use stable transaction identifiers for purchases.
  3. Record delivery state where reliable retry handling is required.
  4. Prevent repeated order callbacks from creating unintended duplicate events.
  5. Test browser and server event flows independently.
  6. Compare received events with the source transactions.

Deduplication should be designed alongside retry handling. Marking an event as permanently processed before successful delivery can cause lost measurement when a transient failure occurs.

10. Secure the Gateway

A public endpoint that forwards arbitrary events to GA4 can be abused to generate unwanted traffic or consume processing resources.

Important safeguards include:

Input validation: Enforce supported event names, payload structures, field types, and request-size limits.

API secret protection: Store the GA4 API secret in Cloudflare Worker secrets and never expose it to the browser.

Abuse prevention: Use appropriate rate limiting and request controls. Do not rely on a secret embedded in public JavaScript as the sole authentication mechanism.

Consent enforcement: Apply the relevant consent and destination eligibility rules before forwarding events.

Data minimization: Send only the identifiers and parameters required for the intended measurement.

Logging: Avoid recording API secrets, complete payloads containing personal information, or unnecessary identifiers.

CORS: If browser clients call the gateway directly, configure allowed origins and preflight handling. CORS does not authenticate requests.

11. Debug GA4 Measurement Protocol Events

Testing should confirm that the gateway accepts valid events and that GA4 receives events with the intended parameters.

A practical workflow is:

  1. Create a controlled test event.
  2. Send it through the Cloudflare Worker.
  3. Inspect the Worker response and any upstream errors.
  4. Validate the payload using GA4’s Measurement Protocol validation endpoint.
  5. Check DebugView when events are configured appropriately for debugging.
  6. Verify event names and ecommerce parameters.
  7. Confirm client and session identifiers.
  8. Test duplicate purchases, invalid payloads, and destination failures.
  9. Compare GA4 events with the source website or WooCommerce transactions.

Validate payloads before production

GA4 provides a dedicated validation endpoint for Measurement Protocol payloads. It is intended for validating event structure and parameters and should not be treated as a production collection endpoint.

Reference: GA4 Measurement Protocol Validation Server

12. Production Readiness Checklist

  • GA4 Measurement ID and API secret are configured.
  • The Worker validates incoming event payloads.
  • Unsupported event names are rejected.
  • Client identifiers are preserved where appropriate.
  • Session context and timestamps are handled correctly.
  • Ecommerce parameters follow GA4 specifications.
  • Purchase events use stable transaction IDs.
  • Consent and data-minimization requirements are enforced.
  • Request-size and abuse controls are implemented.
  • API secrets are stored securely.
  • Errors and retries are handled deliberately.
  • Measurement Protocol validation and GA4 diagnostics have been completed.

Conclusion

Cloudflare Workers provides a flexible way to build a lightweight server-side gateway for Google Analytics 4.

By validating event payloads, preserving available client and session context, and forwarding supported events through Measurement Protocol, a Worker can complement browser-based GA4 tracking and support backend-driven measurement workflows.

For WooCommerce, this architecture can be useful for purchase events and other ecommerce interactions that require controlled server-side delivery.

Reliable measurement still depends on correct event mapping, appropriate identifiers, consent enforcement, duplicate prevention, and destination validation. The gateway should therefore be treated as part of the wider analytics architecture rather than a replacement for sound measurement design.