digital-identity-platform-docs
digital-identity-platform-docs / workers/sgtm-router/worker
workers/sgtm-router/worker
Cloudflare Worker that fronts SGTM container origins and related platform endpoints by resolving an incoming host to an upstream base URL, proxying requests, and emitting access logs to Analytics Engine and R2 for analytics/observability.
Role in the platform
- Acts as the public edge router for customer domains.
- Resolves
{hostname}to an upstream SGTM origin (and optionally a preview UI origin) via KV. - Supports an obfuscated proxy path (
/k/...) where the true upstream target is encoded in a query param. - Emits structured access logs to Cloudflare Analytics Engine + R2 when configured.
Request flow
- Handle CORS preflight requests early (
OPTIONS->204). - Fetch runtime configuration (from KV
EDGE_CONFIG); fails open if unavailable. - Enforce
allowed_hostsvalidation to prevent cross-domain abuse. - Lookup routing config by request hostname (
ROUTING_MAP).- Note:
ROUTING_MAPis managed byinfra-provisioner.
- Note:
- Determine whether the request targets SGTM preview UI paths vs the primary origin.
- Decode
/k/...proxy requests (when not preview UI) to rewrite the upstream target. - Proxy the request upstream and mirror the response status/body/headers downstream.
- Emit a fire-and-forget access log (
ctx.waitUntil(logAccess(...))).
Security & trust boundaries
- Routing config is resolved from KV:
ROUTING_MAP(Host -> Container ID)EDGE_CONFIG(Container ID -> Runtime features)COOKIE_STORE(FPID -> Cookie State)
- External Allowlist:
/ccm/collectis explicitly allowed to Google endpoints. - Open Proxy Protection:
/k/endpoints require a valid container token or signature (future).
CORS & browser behavior
- Preflight requests (
OPTIONS) return204with CORS headers frommakeCorsHeaders. - CORS headers reflect the request
Originand allow credentials. Access-Control-Allow-HeadersmirrorsAccess-Control-Request-Headerswhen present.
Error handling
- Returns explicit
4xx/5xxresponses for missing KV entry, invalid routing config, and bad KV writes. - Logging failures are caught and logged to
console.errorwithout failing the proxied request. - Billing Paused: Returns
402JSON ifsubscription_status === "paused".
Observability
- Adds
x-qaxal-router-targetto upstream request headers and downstream response headers. - Creates a structured log payload including request/response metadata and correlation IDs.
- Uses
ctx.waitUntil(...)for non-blocking logging to AE + R2.
Runtime Configuration & Module Gating Architecture
This worker participates in the v2 runtime configuration system:
- Source of Truth: Fetches config from KV (
EDGE_CONFIG) keyed by container ID. - Caching: Config is cached in
caches.defaultwith a generic TTL (default 60s). - Fail-Open: If config is unavailable, the worker proceeds without breaking traffic.
Feature Gating
- Allowed Hosts Enforcement: Request validation against
allowed_hostslist.X-Public-Hostmust match an allowed entry.- If not allowed ->
404 Unknown project host. - Applies to
/gtm.js,/k/*, and measurement endpoints.
Cookie Restoration & Billing Events
To ensure accurate billing despite client-side race conditions (tracking requests vs restoration requests), this worker implements a Virtual Billing Event strategy:
- Automatic Restoration: Every request attempts to restore/extend cookies if configured.
- Duplicate Logging: If restoration occurs on a non-dedicated endpoint (e.g. a tracking pixel), the worker emits TWO events:
- The original tracking event (e.g.
view_item) with restoration metrics attached for debugging. - A dedicated Virtual Billing Event (
event_type="cookie_restored"or"cookie_extended").
- The original tracking event (e.g.
Billing Schema (Analytics Engine)
blob3("Event Type"):cookie_restored(if count > 0) orcookie_extended(if only extension).double7:cookies_restored_countdouble8:cookies_extended_countblob12:restored_types(comma-separated list, e.g. "ga4,facebook")