---
title: How to set up Google tag gateway for advertisers on Vercel
description: Rewrite a path on your domain to Google's gateway with Routing Middleware, pass the visitor's location from Vercel's geolocation headers, and verify the setup.
keywords: ["Google Tag Gateway"]
url: "https://vercel.com/kb/guide/google-tag-gateway-for-advertisers-on-vercel"
published: 2026-12-03
last_updated: 2026-12-03
authors: Jonas Herrmannsdörfer
related_resources:
  - title: "Using Cloudflare and other reverse proxies with Vercel"
    url: "/kb/guide/can-i-use-a-proxy-on-top-of-my-vercel-deployment"
    description: "General information about using an external proxy to serve a Vercel Deployment."
install_vercel_plugin: npx plugins add vercel/vercel-plugin
search_with_vercel_cli: npx vercel@latest kb search "<query>"
read_with_vercel_cli: "npx vercel@latest kb inspect google-tag-gateway-for-advertisers-on-vercel"
---

Google tag gateway for advertisers loads Google Tag Manager from a path on your own domain, such as `/metrics`, and sends measurement requests to Google through the same path. On Vercel, [Routing Middleware](https://vercel.com/docs/routing-middleware) rewrites that path to Google's gateway and adds the visitor's location.

In a Next.js App Router application, you can keep your Tag Manager container and route its script and measurement requests through your domain.

## Prerequisites

Before you begin, make sure you have:

- Next.js 15 or later with the App Router and a production domain on Vercel
  
- Your Google Tag Manager container ID
  
- Permission to configure firewall rules if your measurement path is blocked: the Project administrator, Team member, or Security role
  

## Steps

### 1\. Choose a measurement path and find your gateway host

Choose an unused path such as `/metrics`. Google limits it to 100 characters, excludes the root path, and requires a separate path for each container. The configuration here uses `/metrics` with the placeholder container ID `GTM-XXXXXXX`.

Your gateway host is your container ID in lowercase, followed by `.fps.goog`. The container `GTM-XXXXXXX` uses `gtm-xxxxxxx.fps.goog`. Google describes this manual setup in its [setup guide](https://developers.google.com/tag-platform/tag-manager/gateway/setup-guide?setup=manual) under the "Other" CDN option.

### 2\. Rewrite the path to Google with Routing Middleware

In Next.js 16 and later, use a [proxy file](https://nextjs.org/docs/app/api-reference/file-conventions/proxy) named `proxy.ts` with an exported `proxy` function. On Next.js 15, use `middleware.ts` and export `middleware`. Place it beside `app`, either at the project root or inside `src`.

If that file already exists, merge the measurement route into its function and matcher. Keep the existing behavior for other paths and run the gateway rewrite only for `/metrics` requests. Otherwise, create the file with this code and replace `TAG_ID` with your container ID:

```typescript
import { NextResponse, type NextRequest } from "next/server";

// Replace with your own tag or container ID.
const TAG_ID = "GTM-XXXXXXX";
const GATEWAY_ORIGIN = `https://${TAG_ID.toLowerCase()}.fps.goog`;

function coordinate(value: string | null, limit: number) {
  if (!value || !/^-?\d+(\.\d+)?$/.test(value)) return null;
  const number = Number(value);
  return Number.isFinite(number) && Math.abs(number) <= limit
    ? number
    : null;
}

function cityName(value: string | null) {
  if (!value) return null;
  try {
    const city = decodeURIComponent(value).trim();
    // Omit unsupported characters rather than invent an encoding.
    return /^[\x20-\x7e]+$/.test(city) && !/[;=]/.test(city)
      ? city
      : null;
  } catch {
    return null;
  }
}

export function proxy(request: NextRequest) {
  const headers = new Headers(request.headers);

  // Replace caller-supplied location with Vercel's values.
  headers.delete("x-forwarded-country");
  headers.delete("x-forwarded-region");
  headers.delete("x-forwarded-countryregion");
  headers.delete("x-forwarded-geolocation");

  const country = request.headers.get("x-vercel-ip-country");
  const region = request.headers.get("x-vercel-ip-country-region");

  if (country && region) {
    headers.set("x-forwarded-countryregion", `${country}-${region}`);
  } else if (country) {
    headers.set("x-forwarded-country", country);
  }

  const latitude = coordinate(
    request.headers.get("x-vercel-ip-latitude"), 90,
  );
  const longitude = coordinate(
    request.headers.get("x-vercel-ip-longitude"), 180,
  );
  const city = cityName(request.headers.get("x-vercel-ip-city"));
  const location: string[] = [];

  if (latitude !== null && longitude !== null) {
    location.push(`latlong=${latitude},${longitude}`);
  }
  if (city) location.push(`city=${city}`);
  if (location.length) {
    headers.set("x-forwarded-geolocation", location.join(";"));
  }

  // Keep the full path and restore the gateway's trailing slash.
  const { pathname, search } = request.nextUrl;
  const path = pathname === "/metrics" ? "/metrics/" : pathname;
  const destination = new URL(`${path}${search}`, GATEWAY_ORIGIN);

  return NextResponse.rewrite(destination, {
    request: { headers },
  });
}

export const config = {
  matcher: "/metrics/:path*",
};
```

The matcher restricts this rewrite to your measurement path. To use another path, replace both `/metrics` values in the pathname check, update the matcher, and use the same path in the tag loader.

The proxy converts Vercel's [geolocation request headers](https://vercel.com/docs/headers/request-headers) to [Google's location format](https://support.google.com/tagmanager/answer/17141867), combining country and region as `US-CA` or sending the country alone. It also forwards valid coordinates and decoded city names, omitting malformed coordinates and city names with non-ASCII characters or header delimiters.

On [rewrites to external origins](https://vercel.com/docs/routing/rewrites#identifying-the-visitor-at-your-origin), Vercel forwards the visitor's public IP in `x-forwarded-for` and `x-real-ip`, so the proxy doesn't set the IP. The rewrite also sends the gateway host in the `Host` header, which Google's setup requires. Step 4 checks the rewrite after you deploy.

#### Why the proxy adds the trailing slash

With the default Next.js configuration, a request to `/metrics/` receives a `308` redirect to `/metrics` before Proxy runs. The rewrite restores the slash upstream to match Google's gateway URL format, while deeper paths such as `/metrics/g/collect` pass through unchanged.

This keeps the default URL behavior elsewhere on your site and adds one redirect when the tag loads. If your app customizes trailing slashes or uses a base path, adapt the route and matcher together before testing the gateway.

### 3\. Load the tag from your first-party path

Install `@next/third-parties`, which provides the `GoogleTagManager` component:

**pnpm**

```bash
pnpm add @next/third-parties@latest
```

**npm**

```bash
npm install @next/third-parties@latest
```

**yarn**

```bash
yarn add @next/third-parties@latest
```

**bun**

```bash
bun add @next/third-parties@latest
```

The command installs the latest experimental `@next/third-parties` release without changing `next`. The versions do not need to match, but check the package's Next.js and React peer dependencies when upgrading.

In `app/layout.tsx`, configure `GoogleTagManager` to load from your measurement URL. Update an existing component or replace the existing script loader for this container so it is loaded once:

```tsx
import { GoogleTagManager } from "@next/third-parties/google";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>{children}</body>
      <GoogleTagManager
        gtmId="GTM-XXXXXXX"
        gtmScriptUrl="https://www.example.com/metrics/"
      />
    </html>
  );
}
```

Replace the container ID and domain with your own values, keeping the URL absolute and the trailing slash. This format works across supported package versions, including older releases that still require `gtmId`.

### 4\. Verify the setup

Deploy and run both checks against your production domain. Replace `www.example.com` in the commands; each response should contain `ok`. The `-L` option follows redirects, and `-f` makes HTTP errors fail the command:

```bash
curl -fsSL "https://www.example.com/metrics/healthy"
curl -fsSL "https://www.example.com/metrics/?validate_geo=healthy"
```

The first check tests routing; the second tests the gateway's geolocation validation. If either fails, inspect the HTTP response and firewall logs before checking the container ID, matcher, and forwarded location headers. Passing both checks does not establish that tags fire or that reported visitor locations are accurate.

Open Tag Assistant preview and trigger a tag in your container, then inspect **Summary** > **Output** > **Hits Sent**. Gateway-routed hits should use `/metrics`. GA4 hits from visitors in the European Economic Area (EEA) go directly to Google's regional endpoints; Google Ads hits still use your measurement path.

### 5\. Let measurement requests pass your firewall

Skip this step unless the firewall challenges or denies requests to your measurement path. Tag scripts and measurement requests cannot complete a [challenge](https://vercel.com/docs/vercel-firewall/firewall-concepts#challenge); they depend on the visitor already having a valid challenge session, which lasts one hour.

> **Note:**
>
> Every request that matches a Bypass rule skips the custom rules after it and WAF Managed Rulesets. Keep the match as narrow as your measurement path.

If measurement requests are blocked, use the latest [Vercel CLI](https://vercel.com/docs/cli/firewall) to add a [WAF custom rule](https://vercel.com/docs/vercel-firewall/vercel-waf/custom-rules). From your app's directory, link the intended project, create the rule, and place it before the other project rules:

```bash
vercel link

vercel firewall rules add "Google tag gateway" \
  --condition '{"type":"path","op":"eq","value":"/metrics"}' \
  --or \
  --condition '{"type":"path","op":"pre","value":"/metrics/"}' \
  --action bypass

vercel firewall rules move "Google tag gateway" --first
```

The rule excludes paths such as `/metrics-other`. Review the staged changes before publishing; the CLI asks for confirmation before applying them all:

```bash
vercel firewall diff
vercel firewall publish
```

Project rules with the [Bypass action](https://vercel.com/docs/vercel-firewall/firewall-concepts#bypass) skip what runs after them: project rules lower in the list, team shared rules that run after project rules, and [WAF Managed Rulesets](https://vercel.com/docs/vercel-firewall/vercel-waf/managed-rulesets#bypassing-rulesets). They don't skip rules placed above them, [team shared rules that run before project rules](https://vercel.com/docs/vercel-firewall/vercel-waf/team-configuration#shared-rules-that-run-before-project-rules), or system-level mitigations such as [DDoS Mitigation](https://vercel.com/docs/vercel-firewall/ddos-mitigation).

Published rules take effect without redeploying your app. You can review them on your [project's firewall rules page](https://vercel.com/d?to=%2F%5Bteam%5D%2F%5Bproject%5D%2Ffirewall%2Frules) and repeat both checks from step four to confirm the URLs still return `ok`.

## Why this setup works

The rewrite keeps the measurement path and query string when forwarding requests to Google. It replaces caller-supplied location headers with values derived from Vercel, so a caller cannot override those fields directly. Those values describe an IP-derived location; they are not proof of a visitor's physical location.

Static [rewrites to external origins](https://vercel.com/docs/routing/rewrites) are enough when requests can pass through unchanged. This setup also combines country and region headers for Google. The [route transform options](https://vercel.com/docs/project-configuration/vercel-json#transform-object-definition) cannot combine those incoming values, so Routing Middleware prepares them before forwarding the request.

## Caveats

### External rewrite caching

For projects created on or after April 6, 2026, Vercel honors the upstream `cache-control`, `CDN-Cache-Control`, and `Vercel-CDN-Cache-Control` headers on [rewrites to external origins](https://vercel.com/docs/routing/rewrites#caching-rewrites-to-external-origins) by default. Older projects don't cache external rewrites unless they opted in.

Check the effective cache policy for measurement responses. Vercel prioritizes `Vercel-CDN-Cache-Control`, then `CDN-Cache-Control`, then `Cache-Control`. Responses governed by [private or no-store directives](https://vercel.com/docs/caching/cdn-cache#cacheable-response-criteria) are not cached.

Inspect repeated responses and their [`x-vercel-cache`](https://vercel.com/docs/headers/response-headers#x-vercel-cache) [status](https://vercel.com/docs/headers/response-headers#x-vercel-cache). Both `MISS` and `BYPASS` indicate a fresh response. Investigate unexpected cached measurement responses before treating the setup as verified; a successful health check does not establish its caching behavior.

### Another CDN in front of Vercel

Another CDN can cause Vercel's location headers and [forwarded client IP](https://vercel.com/docs/headers/request-headers#x-forwarded-for) to describe the proxy instead of the visitor. Enterprise teams can use [Verified Proxy Advanced](https://vercel.com/docs/security/reverse-proxy) to preserve both after configuring it for their upstream proxy.

For a custom setup, accept location headers only from a trusted proxy that overwrites caller-supplied values. Verify the original client IP separately because copying location headers does not preserve it, and review the [security and caching tradeoffs](https://vercel.com/kb/guide/can-i-use-a-proxy-on-top-of-my-vercel-deployment) before adding another CDN.

### Visitors in the European Economic Area

Google Analytics 4 hits from visitors in the European Economic Area (EEA) go directly to Google's regional endpoints and skip your path. Google Ads conversion hits still use the gateway. Google lists this as [expected behavior](https://support.google.com/tagmanager/answer/17141867).

### The noscript snippet

The gateway doesn't support the Google Tag Manager `<noscript>` snippet. If you use it, keep the standard snippet that points to `www.googletagmanager.com`.

### Consent banners

Consent tools that block scripts by matching `googletagmanager.com` won't match your first-party path. Update the rule so it matches `/metrics` as well.

### Content Security Policy

Allow your measurement path in `script-src` and `connect-src`, keeping any Google origins your tags still contact directly. The component's inline initialization script also needs authorization under a strict CSP. For nonce-based policies, pass the policy's nonce through the `nonce` prop.

Follow Google's [tag-specific CSP requirements](https://developers.google.com/tag-platform/security/guides/csp), including `frame-src` for any noscript iframe. For cached HTML, keep the policy and script nonces synchronized with [per-request nonce handling](https://vercel.com/kb/guide/csp-nonces-with-cdn-cache).

### Several containers

Each container needs its own path and its own gateway host. In `proxy.ts`, add each path to the `matcher`, map each path to its gateway host, and repeat the trailing-slash check for each one.

## Next steps

- Configure additional paths with [Routing Middleware](https://vercel.com/docs/routing-middleware)
  
- Review how Vercel [caches and forwards headers on rewrites to external origins](https://vercel.com/docs/routing/rewrites#rewrites-to-external-origins)
  
- Test and order [WAF custom rules](https://vercel.com/docs/vercel-firewall/vercel-waf/custom-rules) before you publish them
  
- Check the tradeoffs of [using Cloudflare and other reverse proxies with Vercel](https://vercel.com/kb/guide/can-i-use-a-proxy-on-top-of-my-vercel-deployment)
  
- Add [per-request CSP nonces to CDN-cached HTML](https://vercel.com/kb/guide/csp-nonces-with-cdn-cache)

## Related Resources

- [Using Cloudflare and other reverse proxies with Vercel](/kb/guide/can-i-use-a-proxy-on-top-of-my-vercel-deployment): General information about using an external proxy to serve a Vercel Deployment.

## More Next.js guides

- [Optimize Fast Data Transfer on Vercel](/kb/guide/optimize-fast-data-transfer): Find what drives Fast Data Transfer on Vercel, from heavy pages and bundles to bots and 404s, and reduce the bytes your project sends to visitors.
- [Identify users and control access in Next.js with Vercel Passport](/kb/guide/vercel-passport-nextjs): Use \`getIdentity()\` to read a visitor’s verified Vercel Passport identity in Next.js, then personalize pages, restrict routes by group, and log actions.
- [Using Vercel Passport with Microsoft Entra ID](/kb/guide/vercel-passport-microsoft-entra-id): Configure Microsoft Entra ID and Vercel Passport to protect a Next.js app, limit access to assigned users, and read verified visitor identities.

## Reference Architecture

Choose a stack and work through the decisions behind it, with curated documentation, guides, templates, and courses to help you build.

- [Agent stack](/kb/architecture/agents): Build and operate agents with models, tools, and durable workflows.
- [Web applications](/kb/architecture/web): Choose rendering, data, authentication, and caching approaches.
- [Backends](/kb/architecture/backends): Choose a runtime, connect services, and run background work.

[Browse all stacks](/kb/architecture)

## Build with prompts

Build an app, extend an agent, or improve your project with ready-to-use prompts for your coding agent.

[Browse the prompt library](/kb/prompts) · [Read the Markdown index](/kb/prompts.md)

## Search guides from your terminal

Search the Knowledge Base and read guides as Markdown with the Vercel CLI. No login required.

```bash
# Find guides by keyword
npx vercel@latest kb search "rewrites and redirects"
npx vercel@latest kb search "AI SDK streaming"

# Show the latest guides
npx vercel@latest kb

# Print a guide as Markdown, by slug or URL
npx vercel@latest kb inspect <guide>
```
