Two Cloudflare Snippets that serve Google tags and collect tracking data on the website's own domain.
| Path on the website | Cloudflare sends it to | Code |
|---|---|---|
/scripts/… |
Google tag gateway, gtm-<container>.fps.goog |
snippets/google-tag-gateway.js |
/metrics/… |
Server-side Tag Manager at events.<domain> |
snippets/metrics-proxy.js |
The examples use www.example.com. Replace the domains and container IDs with your own.
- Snippet
metrics-proxy: codesnippets/metrics-proxy.js, rulerules/metrics.txt. - Snippet
google-tag-gateway: codesnippets/google-tag-gateway.js, with oneGATEWAYline per website, and rulerules/scripts.txt. - Cache rule: Bypass cache, expression
rules/cache-and-waf.txt. - WAF custom rule: Skip bot protection, rate limiting and managed rules, with the same expression. Tracking requests run in the background and can't answer a bot challenge, so a challenged request is a lost event.
- DNS: keep the
events.<domain>record proxied. It is the target of/metrics.
Snippets need the Pro plan or higher. On the Free plan, use a Worker with the same code.
- Replace the current Tag Manager snippet with
website/gtm-snippet.html, below the consent mode defaults. - If
/scriptsfails, the snippet loads Tag Manager from googletagmanager.com. - With consent mode, keep Cloudflare's automatic tag insertion off.
- If the site has a Content Security Policy, allow
'self'inscript-srcandconnect-src.
- Server container: in Admin > Container Settings, the server container URLs are
https://www.example.com/metrics, one per domain, all with the same path. - Web container:
- Google tags that send to the server container use
server_container_url=https://www.example.com/metrics. - Google Ads Google tags have no
server_container_url, so their scripts load through/scripts.
- Google tags that send to the server container use
Each URL returns ok:
https://www.example.com/metrics/healthyhttps://www.example.com/scripts/healthyhttps://www.example.com/scripts/?validate_geo=healthy
The geo check fails with an error (500) when the request has no X-Forwarded-Country header. The gateway snippet sets it from Cloudflare.
- The gateway snippet doesn't forward the site's cookies to Google.
- Both snippets set
X-Forwarded-ForfromCF-Connecting-IP, so a value sent by the browser can't replace the visitor's IP. /metricsand/scriptsmust not overlap: Google tag gateway and the server container each need their own path.