To run server-side GTM on the same origin with Cloudflare, reserve a path on your site such as /metrics, add a Cloudflare Worker on the route www.example.com/metrics/* that forwards those requests to your tagging server with the visitor's IP in X-Forwarded-For, and register https://www.example.com/metrics as the only server container URL. Then point server_container_url and your GTM or gtag script at that path. Because the tagging server now answers from the same hostname and the same Cloudflare IP as the website, its cookies are true first-party cookies that Safari has no IP-based reason to shorten.
This is for developers and tracking leads at agencies who already have a server container running (on Cloud Run, Stape or another host) on a subdomain or a default URL, and want to move it to a path on the main domain. It covers why same origin matters, what Google's own instructions require, Worker code you can deploy, the tag changes, how to test preview mode and cookies, and the things that break most often.
Why serve server-side GTM from a path instead of a subdomain?
A tagging server on metrics.example.com is already first-party in the sense that it shares the registrable domain. Cookies it sets with Domain=example.com are readable on www.example.com. So why bother with a path?
- Safari's IP check. Since Safari 16.4, WebKit caps cookies set in an HTTP response to 7 days when the server that answered looks like a third party by IP address, even if the hostname is a subdomain of the site. Reports on the rule describe it as a comparison between the IP of the website and the IP of the server setting the cookie, roughly the first half of the address. A subdomain CNAMEd to Cloud Run or a tagging host usually fails that check, because the main site is served from somewhere else.
- Same IP by design. When
www.example.com is proxied by Cloudflare and /metrics is handled by a Worker on the same hostname, the browser talks to the same Cloudflare edge address for both. There is no mismatch to detect.
- Google calls it the best practice. Google's custom domain documentation for server-side tagging lists three options: the default domain, a subdomain and same origin. It recommends same origin, with the example
www.example.com/metrics, as the way to get the full security and durability benefits of server-set cookies.
- Simpler security headers. Google notes that the GA tag may send to the server container by image, fetch, XHR or a service worker in an iframe, so a strict Content Security Policy has to allow the server container URL in
img-src, connect-src and frame-src. On the same origin, 'self' covers it.
What same origin does not fix: cookies written by JavaScript. Safari caps script-set cookies such as _ga regardless of where your server lives. The benefit only applies to cookies the tagging server sets with a Set-Cookie header, such as the GA4 client's server-managed FPID cookie, or cookies set by tags that write their own first-party IDs from the server. If your server container only forwards hits and never sets cookies, moving it to a path changes very little for cookie lifetime.
If you are still deciding whether a server container is worth running at all, read is server-side tracking worth it first. For the base install, see the server-side Google Tag Manager setup guide.
What does Google require for a same origin tagging server?
Google's custom domain configuration guide (same origin option) is short but strict. The points that matter:
- Pick an unused path. Everything under that prefix goes to the tagging server, so it must not collide with real pages. Google gives
/collect, /metrics and /data as examples. The path must not contain /gtm.
- Route the whole path. Google says to route all traffic on the path to the server container. If you route only explicit sub-paths, you must cover every path a client claims and also
/_/*, or core functionality breaks. In practice: use a wildcard and forward everything.
- Forward cookies and query strings. The origin pointing at the tagging server must pass all cookies and query strings, with the Host header set to the tagging server's own hostname (for example the
run.app domain).
- Give the path rule priority. The
/metrics/* rule must win over the default rule that sends traffic to the website.
- Check health.
https://www.example.com/metrics/healthy should return ok.
- Replace the container URL. In the server container, under Admin, Container Settings, remove all previous server container URLs and add the new URL including the path. Google explains that all server container URLs must share the same path. If the URL in settings does not include the path, clients will not claim requests.
Note what Google's version does not do: it does not strip /metrics before forwarding. The tagging server receives /metrics/g/collect, and it knows how to handle the prefix because you registered the URL with the path in Container Settings. Keep that in mind when you compare Worker scripts from different sources.
Before you start: what has to be true on Cloudflare
- The site hostname is proxied. Workers routes only run on hostnames whose DNS record is proxied by Cloudflare (orange cloud). If
www is DNS only, the route never fires.
- The tagging server has a public HTTPS URL. For Cloud Run this is the service URL. For Stape it is your container's custom subdomain or default URL. That is the Worker's upstream.
- You know every hostname that needs tracking. Same origin is per hostname. If the client has
www.example.com and shop.example.com, each needs its own route and its own registered path decision. Do not mix a path on one host with a subdomain on another unless you have checked how the server container URLs will work, since Google requires them to share the same path.
How do you proxy server-side GTM through a Cloudflare Worker?
Create a Worker (Workers and Pages, Create, start from the Hello World template), replace its code with the script below, set the two constants, and deploy. Then attach the route. The script keeps the full path, passes method, body, cookies and query strings unchanged, adds the visitor IP, and returns the tagging server's response as is, including its Set-Cookie headers.
// Upstream tagging server, no trailing slash.
// Cloud Run example: https://sgtm-abc123-uc.a.run.app
const TAGGING_ORIGIN = "https://sgtm-abc123-uc.a.run.app";
// The reserved path. Must match Container Settings.
const PREFIX = "/metrics";
export default {
async fetch(request) {
const incoming = new URL(request.url);
// Safety net: only handle the reserved path.
if (incoming.pathname !== PREFIX &&
!incoming.pathname.startsWith(PREFIX + "/")) {
return fetch(request);
}
// Keep the path and query exactly as received.
const upstream = new URL(incoming.pathname + incoming.search, TAGGING_ORIGIN);
const headers = new Headers(request.headers);
// The real visitor IP, as seen by Cloudflare.
const clientIp = request.headers.get("CF-Connecting-IP");
if (clientIp) {
headers.set("X-Forwarded-For", clientIp);
}
// Avoid a stale or conflicting standard header.
headers.delete("Forwarded");
const proxied = new Request(upstream.toString(), {
method: request.method,
headers: headers,
body: request.method === "GET" || request.method === "HEAD" ? null : request.body,
redirect: "manual"
});
return fetch(proxied);
}
};
A few choices in that code deserve an explanation.
- No Host override. In a Worker, the Host header of an outgoing fetch follows the URL you fetch, so requesting the
run.app URL already sends the tagging server's hostname. That matches Google's instruction to set Host to the tagging server domain.
- X-Forwarded-For set, not appended. The server-side GTM API function
getRemoteAddress works out the visitor IP by reading headers such as Forwarded and X-Forwarded-For, and Google describes it as best effort. If the Worker forwards nothing, the tagging server sees a Cloudflare address, and every tag that uses the IP (GA4 geo, Meta Conversions API client_ip_address, fraud filters) gets the wrong value. Setting the header to CF-Connecting-IP gives the upstream a clean first value. Cloud Run or a load balancer may append its own hop after it, which is expected.
- redirect: "manual". If the tagging server ever answers with a redirect, the browser should see it. Following it inside the Worker hides problems and can turn a POST into a GET.
- The prefix is not stripped. This follows Google's same origin setup for a tagging server you run yourself. If your host's documentation tells you to strip the prefix, follow the host, but then the Container Settings URL and the Worker must agree. A mismatch is the most common reason clients stop claiming requests.
Add the route
In the Worker's Settings, under Domains and Routes, add a route with the pattern www.example.com/metrics/* and pick the zone. Cloudflare route patterns support only a * wildcard, which matches zero or more characters, and a pattern only matches URLs with a query string if it ends in a wildcard. Keep the slash before the wildcard: www.example.com/metrics* would also catch real pages like /metrics-report. If the apex serves pages without redirecting to www, it needs its own route.
If you deploy with Wrangler, the same route goes in the config file under routes with a pattern and a zone_name (or zone_id). Cloudflare's Workers routes documentation has the full syntax.
Keep Cloudflare features off the path
- Caching. Add a Cache Rule that bypasses cache when the URI path starts with
/metrics/. Collection requests must never be served from cache, and a cached response with a Set-Cookie header is a privacy problem.
- URL rewrites and query sorting. Do not apply transform rules, query string sorting or URL normalization tricks to this path. Stape's Cloudflare guide warns that query string sorting can break the pixel requests some server tags send back through the browser.
- Bot and WAF challenges. A challenge page returned to a
fetch or sendBeacon call fails silently. Check Security Events for blocked requests on the path after launch, and add a narrow skip rule if needed. Do not skip all security for the whole site.
- Security headers added at the edge. If a Transform Rule adds
X-Frame-Options: DENY to every response, it will also land on /metrics responses. Google notes that X-Frame-Options must not stop the server container URL from loading in an iframe, because the GA tag can use a service worker in an iframe as one of its transports.
How do you update server_container_url and the GTM script?
Two separate things point at the tagging server: where events are sent, and where the scripts load from. Change both, or you get half a first-party setup.
Where events go: server_container_url
In a GTM web container, open the Google tag that sends to GA4 and set the configuration parameter server_container_url to https://www.example.com/metrics. No trailing slash. With gtag.js on the page, it goes in the config call:
<script async src="https://www.example.com/metrics/YOUR_TAG_SERVING_PATH/"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX', {
server_container_url: 'https://www.example.com/metrics'
});
</script>
Older server-side guides use transport_url. That parameter came from the Universal Analytics era. For the Google tag and GA4, use server_container_url, which is what Google's current documentation shows. If a container still has both, remove the old one so there is only one source of truth.
If the site also has a hardcoded gtag.js next to GTM, it will keep sending straight to Google. See Google tag vs Google Tag Manager for how to find and remove it.
Where scripts load from: the Web Container client
Google's first-party script serving documentation describes the tagging server option like this: in the server container, create a client of type Google Tag Manager: Web Container, add your web container ID (such as GTM-XXXXXXX) or Google tag ID (such as G-XXXXXXXXXX) under Allowed Container IDs, and note the Tag serving path. Tag Manager generates a random path for each ID so it does not clash with other paths. That client can now serve gtm.js and gtag.js.
Then the GTM snippet on the site changes. Google's updated head snippet builds the source from the tagging server URL plus the tag serving path:
<!-- Google Tag Manager -->
<script>(function(w,d,s,l){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'?l='+l:'';j.async=true;j.src=
'https://www.example.com/metrics/YOUR_TAG_SERVING_PATH/'+dl;
f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer');</script>
<!-- End Google Tag Manager -->
The noscript iframe becomes https://www.example.com/metrics/ns.html?id=GTM-XXXXXXX. Two rules from Google's page that people get wrong:
- The tag serving path is not part of server_container_url. The script URL is
/metrics/your-serving-path/. The event URL is just /metrics.
- Serving scripts adds load. Every page view now pulls the script through your tagging server, which adds requests and egress cost on hosts that bill for it. Google's same page offers serving the scripts through a CDN instead (Google tag gateway for advertisers), which it lists as the recommended option for scripts.
Where does Cloudflare's Google tag gateway fit?
Cloudflare has a built-in integration for Google tag gateway for advertisers, set up from the Cloudflare dashboard or from Google Tag Manager. It serves Google's scripts and measurement requests from a path on your domain and forwards them to Google. It is not the same thing as a server container:
| Need | Google tag gateway on Cloudflare | sGTM on same origin via Worker |
| Load gtm.js or gtag.js from your domain | Yes | Yes, through the Web Container client |
| Google measurement sent to your domain | Yes, forwarded to Google | Yes, processed in your container |
| Change, enrich or remove data before it leaves | No | Yes |
| Send to Meta, TikTok or other vendors server side | No | Yes, with server tags |
| Infrastructure to run and pay for | None of your own | Tagging server plus Worker requests |
Do not run both on the same path. If you enable the gateway and also have a Worker route on a path, pick different paths and be clear about which tags use which. For a client who only needs Google Ads and GA4 with no data changes, the gateway is often enough. For anyone sending the Meta Conversions API from the server or cleaning data before it reaches vendors, you need the container.
What about Stape's same origin setup?
If the container is hosted on Stape, it publishes its own same origin guides for Cloudflare, Nginx, Fastly, Caddy and others. Its Cloudflare guide differs from the Google version in ways that matter:
- The path is stripped. Stape's Worker replaces
/metrics/ with / before forwarding to the Stape host. Follow that pattern for Stape, not the full-path version above, and do not mix the two.
- Upstream choice. Stape recommends proxying to your custom Stape subdomain rather than the default Stape URL. If you proxy to the default URL, its guide adds a request header transform rule that sets
X-Stape-Host to the host where events happen.
- SSL mode. Stape's guide sets SSL to Full for the path with a Configuration Rule, warning that otherwise the proxy may return a 301 redirect.
- Script loading. Stape uses its Custom Loader power-up for the GTM script, where you enter the same origin path.
- Own CDN. Stape says not to combine this with its Own CDN feature.
Stape's published script does not set X-Forwarded-For itself, so test what IP your tags receive rather than assuming.
How do you test preview mode on a same origin container?
- Health check. Open
https://www.example.com/metrics/healthy. You should see ok. A 404 from your CMS means the route is not firing. A Cloudflare error means the Worker is failing.
- Container Settings. Confirm the only server container URL is
https://www.example.com/metrics. Old subdomain URLs left in place are against Google's rule that all URLs share the same path.
- Start Preview in the server container. It should open at the same origin URL. Then start web container preview on the site in another tab, or just browse the site.
- Check a request was claimed. Click an incoming request in server preview. The GA4 client should have claimed it. If requests arrive but nothing claims them, the URL in Container Settings and the path the Worker forwards do not match.
- No incoming requests at all. Google's troubleshooting points to three things: confirm the tagging server receives traffic in your cloud logs, confirm the proxy forwards cookies (preview depends on them), and confirm you have a single preview server with
PREVIEW_SERVER_URL set on the tagging servers and returning ok on its own /healthy.
- Check the IP. In the server preview, look at the request details or check the location data on a test hit in GA4 DebugView. It should be your own public IP, not a Cloudflare or Google address.
How do you check the cookies are actually first-party and long-lived?
This is the whole point of the project, so test it in the browser that matters.
- Network tab. In Chrome DevTools, filter on
metrics. Collection requests should go to www.example.com/metrics/..., not region1.google-analytics.com or the old subdomain. Open one response and look for Set-Cookie if your client sets server cookies.
- Cookie attributes. For the GA4 client in server-managed mode, look for the
FPID cookie in Application, Cookies. Check its Domain, Path, HttpOnly flag and Expires. If the domain is wrong (for example scoped to the run.app host or missing entirely when you expected .example.com), review the cookie settings in the GA4 client.
- Safari. Open the site in Safari with Web Inspector, Storage, Cookies. A server-set cookie that shows an expiry about 7 days out is still being capped. Expect JavaScript cookies like
_ga to be capped no matter what you do.
- Scripts. In the Sources tab, gtm.js or gtag.js should load from
www.example.com. If it still shows www.googletagmanager.com, the old snippet is still live somewhere.
Common failures and their causes
| Symptom | Likely cause | Fix |
/metrics/healthy returns the site's 404 page | Route pattern wrong, hostname not proxied, or Worker not attached to the zone | Check the pattern includes the right host and ends in /*, and the DNS record is orange-clouded |
| Requests arrive in preview but no client claims them | Container Settings URL lacks the path, or the Worker strips the prefix on a self-hosted server | Make the registered URL and forwarded path agree |
| All visitors show the same city or a data center location | Visitor IP not forwarded | Set X-Forwarded-For from CF-Connecting-IP |
| Hits double in GA4 | Page sends to both the old subdomain and the new path, or a hardcoded gtag sends direct | Remove the old URL everywhere, search the page source for every Google tag ID |
| Preview works for you, data missing for some users | WAF or bot challenge on POST requests | Check Security Events for the path, add a narrow skip rule |
| Random 301s on the path | SSL mode or redirect rules on the path | Exclude the path from redirect rules, check SSL settings, keep redirect: "manual" |
If Google Ads conversions move from browser tags to the server container, make sure only one path stays live per conversion, and that enhanced conversions are set up on the tag that remains.
Caveats before you switch a client over
- Consent still applies. Moving the endpoint does not change what you are allowed to collect. The tags still need to respect Consent Mode signals and your CMP. See the Consent Mode v2 implementation guide.
- Cross-domain journeys. Same origin cookies live on one site. If the funnel crosses to a different registrable domain (a booking tool, a separate checkout), you still need linker parameters. See GA4 cross-domain tracking and self-referrals.
- Cost. Every tracking request is now a Worker invocation as well as a tagging server request. Check the client's Workers plan limits against their traffic, especially if you also serve the scripts through the tagging server.
- Change order. Deploy the Worker and test
/healthy first, then update Container Settings, then publish the web container with the new URLs. Updating Container Settings before the route works leaves the container claiming nothing.
Getting it fixed for a client
Moving a server container to the same origin is a small amount of code and a long list of places where one mismatch quietly drops data: the route, the registered URL, the forwarded IP, the script snippet, the cache and the WAF. If you have a client whose server-side setup is live but the numbers or the cookie lifetimes do not look right, we can review it for you, white-label. Start with a free tracking check and we will tell you what is broken and what it takes to fix it.