# Consent-First GA4 in Next.js: Nothing Loads Until Visitors Agree

> GA4 in the Next.js App Router with no script, cookie or request before Accept: the code for consent, page views, clicks and scrubbing, and how to test it.

Source: https://www.derar.dev/blog/consent-first-ga4-nextjs · Published 2026-11-17 · By Derar Sattouf

Most guides to Google Analytics in Next.js load it straight away. The `GoogleAnalytics` component from `@next/third-parties` goes in the root layout and fetches gtag.js after hydration, on every page, for every visitor. Unless you add consent defaults yourself, the `_ga` cookie is set on the first page view, before any banner has had a chance to ask.

Google's consent mode comes in two shapes. In advanced mode the tag loads on every page and, while consent is denied, sends measurements without cookies. In basic mode the tag is blocked until the visitor answers the banner, and Google's documentation says that until then no data is transferred to Google at all, not even the consent status.

This site uses the basic shape, built by hand and without a consent platform. There is no Google script, no `_ga` cookie and no request to Google until someone clicks Accept. It takes two modules, `lib/consent.ts` and `lib/analytics.ts`, and two small client components, and this post walks through all of them. The code is adapted from what runs here: trimmed, with placeholder IDs, and type-checked as written. The [privacy policy](https://www.derar.dev/privacy) describes the same setup from the visitor's side.

## The rules the code enforces

Each of these is a line or two of code further down:

- **Nothing from Google is in the HTML.** gtag.js, or Google Tag Manager, is added from the browser after Accept.
- **Events before a decision are dropped, not queued.** A queue would send, after the fact, what someone did before they agreed.
- **A browser privacy signal counts as Reject.** Global Privacy Control or Do Not Track means "denied" until the visitor chooses otherwise. An explicit choice beats the signal.
- **Rejecting works at any time.** It stops every event and deletes Google's cookies, whether the visitor accepted a minute ago or a month ago.
- **Advertising features are off,** whatever the GA4 property settings say.
- **Only the production host is tracked.** Localhost and preview deployments send nothing, so test traffic never needs a filter.
- **Accept and Reject look the same.** Same size, same style, side by side.

The price is data. GA4 only sees visitors who accept, and its behavioral modeling, which estimates the others, requires tags that load before the consent dialog appears. Read the reports as a sample: trends and ratios, not totals.

## Storing the choice

`lib/consent.ts` knows nothing about Google. It answers one question (granted, denied or not asked yet) and tells subscribers when the answer changes.

```ts
// lib/consent.ts
const STORAGE_KEY = "consent:v1";
const MAX_AGE_MS = 365 * 24 * 60 * 60 * 1000;
/** Fired on this window whenever the stored choice changes. */
export const CONSENT_EVENT = "consent:change";
/** Fired to show the notice again. */
export const CONSENT_OPEN_EVENT = "consent:open";

export type ConsentState = "granted" | "denied" | "unset";
type StoredConsent = { v: 1; analytics: boolean; at: number };

/** Keeps the choice for this page if storage is blocked. */
let memoryChoice: boolean | null = null;

const readStored = (): boolean | null => {
  try {
    const raw = window.localStorage.getItem(STORAGE_KEY);
    if (!raw) return null;
    const data = JSON.parse(raw) as Partial<StoredConsent>;
    if (data.v !== 1 || typeof data.analytics !== "boolean" || typeof data.at !== "number") return null;
    if (Date.now() - data.at > MAX_AGE_MS) return null;
    return data.analytics;
  } catch {
    return null;
  }
};

export const hasPrivacySignal = () => {
  const nav = navigator as Navigator & { globalPrivacyControl?: boolean };
  return nav.globalPrivacyControl === true || nav.doNotTrack === "1";
};

export const getConsent = (): ConsentState => {
  if (typeof window === "undefined") return "unset";
  const choice = readStored() ?? memoryChoice;
  if (choice !== null) return choice ? "granted" : "denied";
  return hasPrivacySignal() ? "denied" : "unset";
};

export const setConsent = (analytics: boolean) => {
  memoryChoice = analytics;
  try {
    const value: StoredConsent = { v: 1, analytics, at: Date.now() };
    window.localStorage.setItem(STORAGE_KEY, JSON.stringify(value));
  } catch {
    // Storage is blocked: the choice still applies until the page is closed.
  }
  window.dispatchEvent(new Event(CONSENT_EVENT));
};

export const subscribeConsent = (onChange: () => void) => {
  const onStorage = (event: StorageEvent) => {
    if (event.key === STORAGE_KEY || event.key === null) onChange();
  };
  window.addEventListener(CONSENT_EVENT, onChange);
  window.addEventListener("storage", onStorage);
  return () => {
    window.removeEventListener(CONSENT_EVENT, onChange);
    window.removeEventListener("storage", onStorage);
  };
};

/** For the "Cookie settings" link in the footer. */
export const openConsentSettings = () => window.dispatchEvent(new Event(CONSENT_OPEN_EVENT));
```

The details that matter:

- **The key has a version.** When the notice starts covering something new, `consent:v2` asks everyone again, and old answers are ignored instead of misread.
- **Answers expire.** After 12 months the stored choice stops counting and the notice comes back.
- **Blocked storage still works.** Some browser settings make `localStorage` throw. The choice is then kept in memory, so it applies for the rest of the visit even though it can't be remembered.
- **The privacy signal is a default, not a lock.** It only applies when there is no stored choice. A visitor whose browser sends Global Privacy Control sees no notice, because the browser has already answered, but can still accept from the "Cookie settings" link in the footer.
- **Other tabs follow.** The `storage` event fires in every other tab of the same origin when the value changes, so rejecting in one tab turns analytics off in the rest. It does not fire in the tab that made the change, which is what the custom `consent:change` event is for. `event.key` is `null` when storage is cleared.

## The notice

The notice is a small client component. This is the site's version with its own button and text components swapped for plain elements:

```tsx
// components/site/consent-banner.tsx
"use client";

import Link from "next/link";
import { useEffect, useRef, useState, useSyncExternalStore } from "react";

import { analyticsAvailable } from "@/lib/analytics";
import { CONSENT_OPEN_EVENT, getConsent, setConsent, subscribeConsent, type ConsentState } from "@/lib/consent";

const noopSubscribe = () => () => {};

export const ConsentBanner = () => {
  const available = useSyncExternalStore(noopSubscribe, analyticsAvailable, () => false);
  const consent = useSyncExternalStore(subscribeConsent, getConsent, (): ConsentState => "unset");
  const [reopened, setReopened] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const open = available && (consent === "unset" || reopened);

  useEffect(() => {
    const reopen = () => setReopened(true);
    window.addEventListener(CONSENT_OPEN_EVENT, reopen);
    return () => window.removeEventListener(CONSENT_OPEN_EVENT, reopen);
  }, []);

  useEffect(() => {
    if (open && reopened) ref.current?.focus();
  }, [open, reopened]);

  if (!open) return null;

  const choose = (analytics: boolean) => {
    setConsent(analytics);
    setReopened(false);
  };

  return (
    <div ref={ref} tabIndex={-1} role="dialog" aria-modal="false" aria-labelledby="consent-title" data-track-ignore>
      <p id="consent-title">Analytics cookies</p>
      <p>
        I use Google Analytics to see which pages get used. It sets cookies only if you accept.{" "}
        <Link href="/privacy">Privacy policy</Link>
      </p>
      <button type="button" onClick={() => choose(false)}>Reject</button>
      <button type="button" onClick={() => choose(true)}>Accept</button>
    </div>
  );
};
```

- **The server renders nothing.** `useSyncExternalStore` takes a separate snapshot for the server, and the server snapshot for `available` is `false`, so the HTML has no notice in it. After hydration the client takes its own snapshots and shows the notice only to visitors who haven't answered. There is no hydration mismatch, and a returning visitor never sees it flash.
- **It doesn't block the page.** `aria-modal="false"` and no backdrop: someone can read the page and answer later. Until they do, nothing is tracked.
- **Reopening moves focus to it,** so a keyboard user who chose "Cookie settings" lands on the choice instead of searching for it. The footer link is one line: `<button type="button" onClick={openConsentSettings}>Cookie settings</button>`.
- **It is excluded from click tracking** through `data-track-ignore`, so the answer itself is never an event.

## Loading Google only after Accept

`enableAnalytics()` is the only place a Google script is added to the page, and it only runs when consent is granted.

```ts
// lib/analytics.ts (the gtag.js path; the GTM path comes later)
const GA_ID = process.env.NEXT_PUBLIC_GA_ID || "G-XXXXXXXXXX";
const SITE_HOST = "example.com"; // your production host

declare global {
  interface Window {
    dataLayer?: unknown[];
    gtag?: (...args: unknown[]) => void;
  }
}

let mode: "off" | "gtag" = "off";
let scriptLoaded = false;

const isTrackedHost = (hostname: string) => hostname === SITE_HOST || hostname.endsWith(`.${SITE_HOST}`);

/** True where analytics can run at all. The notice only appears there. */
export const analyticsAvailable = () => typeof window !== "undefined" && isTrackedHost(window.location.hostname);

const loadScript = (src: string) => {
  const script = document.createElement("script");
  script.async = true;
  script.src = src;
  document.head.appendChild(script);
};

export function enableAnalytics() {
  if (typeof window === "undefined" || !isTrackedHost(window.location.hostname)) return;
  if (mode !== "off") return;

  window.dataLayer = window.dataLayer || [];
  (window as unknown as Record<string, unknown>)[`ga-disable-${GA_ID}`] = false;

  if (!scriptLoaded) {
    window.gtag = function gtag() {
      // Keep Google's form: push the arguments object, not an array.
      // eslint-disable-next-line prefer-rest-params
      window.dataLayer!.push(arguments);
    };
    // Defaults before anything that measures. Analytics is granted (the visitor said yes), ads never are.
    window.gtag("consent", "default", {
      ad_storage: "denied",
      ad_user_data: "denied",
      ad_personalization: "denied",
      analytics_storage: "granted",
    });
    window.gtag("js", new Date());
    window.gtag("config", GA_ID, {
      send_page_view: false,
      allow_google_signals: false,
      allow_ad_personalization_signals: false,
    });
    loadScript(`https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(GA_ID)}`);
    scriptLoaded = true;
  }

  mode = "gtag";
  startListening(); // click tracking, below
  window.setTimeout(trackPageView, 0); // the page the visitor is on
}
```

What each part is for:

- **The stub pushes `arguments`.** That is how Google's own snippet is written, and the tag treats the `arguments` object differently from an array. Rewriting the stub as an arrow function with `...args` looks harmless and is a well-known way to break it.
- **Consent defaults come before `config`.** Google's consent guide says the default command has to run before any command that sends measurement data, or the defaults don't work. This code only runs after Accept, so `analytics_storage` is granted and the three advertising signals are denied.
- **`allow_google_signals` and `allow_ad_personalization_signals` are false.** Google documents both as overriding the property settings, so switching on Google signals in the GA4 admin later can't quietly change what this site sends.
- **`send_page_view` is false.** The App Router changes pages without a reload, so page views are sent by hand from a component in the root layout, shown further down.
- **The host check runs first.** Localhost and preview deployments return before anything happens, so development traffic never reaches the property.
- **`mode` makes it safe to call twice.** It runs on every consent change and twice on mount in development, and the script still loads once.

## Turning it off again

Rejecting, whether right away or a month after accepting, goes through one function:

```ts
export function disableAnalytics() {
  if (typeof window === "undefined") return;
  (window as unknown as Record<string, unknown>)[`ga-disable-${GA_ID}`] = true;
  stopListening();
  mode = "off";
  lastPageViewPath = "";
  expireAnalyticsCookies();
}

/** Google writes its cookies on the highest domain it can, so try every parent domain. */
function expireAnalyticsCookies() {
  const names = document.cookie
    .split(";")
    .map((entry) => entry.split("=")[0].trim())
    .filter((name) => name === "_ga" || name.startsWith("_ga_") || name === "_gid" || name.startsWith("_gat"));
  if (names.length === 0) return;

  const parts = window.location.hostname.split(".");
  const domains = new Set<string | undefined>([undefined]);
  for (let i = 0; i < parts.length - 1; i += 1) domains.add(parts.slice(i).join("."));

  for (const name of names) {
    for (const domain of domains) {
      document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/${domain ? `; domain=${domain}` : ""}; SameSite=Lax`;
    }
  }
}
```

Three things happen:

- **The site's own events stop at once.** `track()` returns early when `mode` is `"off"`, and the click listener is removed.
- **Google's opt-out flag is set.** `window['ga-disable-<ID>'] = true` is Google's documented way to stop the tag sending data. The documentation says to set it before any `gtag()` call and doesn't say whether it works once gtag.js is already running, which is the situation when someone withdraws in the middle of a visit. If you rely on events gtag.js sends by itself (more on those below), reload the page after a withdrawal to be sure.
- **The cookies are deleted on the right domain.** By default, Google tags set cookies on the highest domain possible: on `blog.example.com` they land on `example.com`. Only a write that names the same domain and path removes a cookie, so the function writes once with no domain and once for every parent domain. `_gid` and `_gat` come from older versions of Google Analytics, and deleting them costs nothing.

## Page views in the App Router

The component that ties consent to analytics goes in the root layout, inside `<body>`. On this site both root layouts render it through one shared shell, as described in the [Arabic and RTL post](https://www.derar.dev/blog/nextjs-arabic-rtl-app-router).

```tsx
// components/site/analytics.tsx
"use client";

import { usePathname, useSearchParams } from "next/navigation";
import { Suspense, useEffect } from "react";

import { ConsentBanner } from "@/components/site/consent-banner";
import { disableAnalytics, enableAnalytics, trackPageView } from "@/lib/analytics";
import { getConsent, subscribeConsent } from "@/lib/consent";

const PageViews = () => {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    // Wait a tick so the new page's <title> is in place.
    const id = window.setTimeout(trackPageView, 0);
    return () => window.clearTimeout(id);
  }, [pathname, searchParams]);

  return null;
};

export const Analytics = () => {
  useEffect(() => {
    const apply = () => (getConsent() === "granted" ? enableAnalytics() : disableAnalytics());
    apply();
    return subscribeConsent(apply);
  }, []);

  return (
    <>
      <Suspense fallback={null}>
        <PageViews />
      </Suspense>
      <ConsentBanner />
    </>
  );
};
```

And the page view itself, in `lib/analytics.ts`:

```ts
let lastPageViewPath = "";

export function trackPageView() {
  if (typeof window === "undefined" || mode === "off") return;
  const path = window.location.pathname + window.location.search;
  if (path === lastPageViewPath) return;
  lastPageViewPath = path;
  track("page_view", {
    page_location: window.location.origin + window.location.pathname,
    page_title: document.title,
  });
}
```

- **`useSearchParams` needs a `<Suspense>` boundary.** The Next.js docs say that without one, the Client Component tree up to the closest boundary is rendered on the client instead of being prerendered. Wrapping a component that renders `null` costs nothing.
- **Query-string changes count.** The effect depends on `searchParams` as well as `pathname`, and the dedupe key includes the query string, so `?tab=b` after `?tab=a` is a new page view.
- **The `setTimeout` lets the new `<title>` land** before it is read, so the event doesn't carry the previous page's title.
- **One view per address.** On a load with consent already granted, both the effect and `enableAnalytics()` schedule a page view, and Strict Mode runs effects twice in development. `lastPageViewPath` lets only the first one through.
- **The query string stays out.** `page_location` is the origin and the path, nothing else.

Two things go with this. In the GA4 web stream's enhanced measurement settings, turn off **Page changes based on browser history events**. Google's documentation says that with it on, GA4 sends its own page views on history changes even when `send_page_view` is false, so manual page views on top of those are duplicates.

The second is campaigns. GA4 reads `utm_` parameters from `page_location`, so a page view without its query string loses them. If you tag the links you share, keep those parameters and drop the rest:

```ts
const CAMPAIGN_KEYS = ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"];

const pageLocation = () => {
  const url = new URL(window.location.href);
  const kept = new URLSearchParams();
  for (const key of CAMPAIGN_KEYS) {
    const value = url.searchParams.get(key);
    if (value) kept.set(key, value);
  }
  const query = kept.toString();
  return `${url.origin}${url.pathname}${query ? `?${query}` : ""}`;
};
```

## One click listener instead of tracking code in every component

Buttons and links on this site carry no tracking code. One listener on `document` reports every click on something clickable, and the markup decides what it is called.

```ts
const CLICKABLE =
  'a, button, [role="button"], [role="tab"], [role="menuitem"], summary, [data-track], input[type="submit"], input[type="button"], label[for]';

const elementText = (el: Element) =>
  (
    el.getAttribute("data-track-label") ||
    el.getAttribute("aria-label") ||
    el.getAttribute("title") ||
    (el as HTMLElement).innerText ||
    el.textContent ||
    ""
  )
    .replace(/\s+/g, " ")
    .trim();

const sectionOf = (el: Element) =>
  el.closest("[data-track-section]")?.getAttribute("data-track-section") ||
  el.closest("header, nav, aside, footer, main, dialog, form")?.tagName.toLowerCase();

const linkType = (url: URL) => {
  if (url.protocol === "mailto:") return "email";
  if (url.protocol === "tel:") return "phone";
  if (url.protocol === "blob:" || url.protocol === "data:") return "download";
  return url.host === window.location.host ? "internal" : "outbound";
};

function onClick(event: MouseEvent) {
  if (!event.isTrusted) return; // clicks made by code are tracked where they happen
  const el = (event.target as Element | null)?.closest?.(CLICKABLE);
  if (!el || el.closest("[data-track-ignore]")) return;

  const params: AnalyticsParams = {
    element_type: el.getAttribute("role") || el.tagName.toLowerCase(),
    element_text: elementText(el),
    element_id: el.id || undefined,
    track_id: el.getAttribute("data-track") || undefined,
    section: sectionOf(el),
  };

  if (el instanceof HTMLAnchorElement && el.href) {
    try {
      const url = new URL(el.href, window.location.href);
      params.link_type = el.hasAttribute("download") ? "download" : linkType(url);
      params.link_url = url.protocol.startsWith("http") ? `${url.origin}${url.pathname}` : url.protocol.replace(":", "");
      params.link_domain = url.hostname || undefined;
    } catch {
      // ignore malformed hrefs
    }
  }

  track("ui_click", params);
}

let listening = false;

function startListening() {
  if (listening) return;
  listening = true;
  document.addEventListener("click", onClick, true);
}

function stopListening() {
  if (!listening) return;
  listening = false;
  document.removeEventListener("click", onClick, true);
}
```

- **It listens in the capture phase** (the `true` argument), so it sees a click before any component handler can stop it from bubbling.
- **`event.isTrusted` skips clicks made by code,** like the hidden link a tool clicks to start a download. Those downloads are tracked where they happen, with the file type and size and never the name.
- **The markup names things.** `data-track="signup_cta"` gives a stable ID that survives copy changes, `data-track-label` replaces the visible text, `data-track-section` names a region, and nothing inside `data-track-ignore` is ever reported. Without a `data-track-section`, the nearest landmark (`header`, `nav`, `main`, `footer`) names the section.
- **Links are typed.** Internal, outbound, email, phone and download clicks are one parameter, so they are easy to compare. This site adds a `tool_switch` type for jumps between the portfolio and a tool, so one report shows how visitors move between them.

Events a click can't describe still call `track()` directly. The PDF and image tools send `tool_run` with a status and an output format, and the resume builder sends `resume_export`.

## Scrub before you send

Every event, from the listener or from a direct `track()` call, goes through one `send()` function, and that function cleans the parameters first. It is the one place every event passes through, so it is where the rules about personal data live.

```ts
type ParamValue = string | number | boolean | null | undefined;
export type AnalyticsParams = Record<string, ParamValue>;

/** Never sent, even if a caller passes them. */
const DROPPED_KEYS = new Set(["file_name", "search_term"]);
/** Text taken from the page, scrubbed before it leaves. */
const SCRUBBED_KEYS = new Set(["element_text", "error_message", "copy_label"]);
/** GA4's value limits in a standard property: 100 characters, with three exceptions. */
const VALUE_LIMITS: Record<string, number> = { page_title: 300, page_referrer: 420, page_location: 1000 };

const FILE_NAME =
  /[^\s"'<>\\/|?*:]+\.(?:pdf|docx?|xlsx?|pptx?|txt|csv|json|xml|ya?ml|md|zip|png|jpe?g|webp|gif|avif|heic|heif|tiff?|bmp|svg|ico)\b/gi;
const EMAIL = /[^\s@]+@[^\s@]+\.[^\s@]+/g;
const LONG_NUMBER = /\+?\d(?:[\s().-]?\d){7,}/g;

export const scrubUserText = (value: string) =>
  value.replace(EMAIL, "[email]").replace(FILE_NAME, "[file]").replace(LONG_NUMBER, "[number]");

function clean(params: AnalyticsParams) {
  const out: Record<string, string | number | boolean> = {};
  for (const [key, value] of Object.entries(params)) {
    if (DROPPED_KEYS.has(key) || value === undefined || value === null || value === "") continue;
    if (typeof value !== "string") {
      out[key] = value;
      continue;
    }
    const text = SCRUBBED_KEYS.has(key) ? scrubUserText(value) : value;
    out[key] = text.slice(0, VALUE_LIMITS[key] ?? 100);
  }
  return out;
}

function send(event: string, params: AnalyticsParams) {
  const payload = clean({ site_name: sectionForPath(window.location.pathname), ...params });
  if (DEBUG || DRY_RUN) console.info("[analytics]", event, payload);
  if (DRY_RUN) return;
  window.gtag?.("event", event, payload);
}

export function track(event: string, params: AnalyticsParams = {}) {
  if (typeof window === "undefined" || mode === "off") return;
  send(event, params);
}
```

What this buys, and where it stops:

- **A careless call can't leak.** If a tool passes `file_name` next to `file_extension`, the sender drops it.
- **Every event says where it came from.** `sectionForPath` maps the path to a name such as `pdf-tools` or `portfolio`. The tools on this site used to live on subdomains, and they kept their old names as `site_name` values when they moved to paths, so the GA4 history still lines up.
- **Text from the page is scrubbed.** Button labels, error messages and copy labels can contain what a visitor typed or named. Run the scrubber on real labels before you trust it. These are its actual outputs:

```text
"Remove invoice-2026.pdf"   ->  "Remove [file]"
"Sent to jane@example.com"  ->  "Sent to [email]"
"Call +961 70 123 456"      ->  "Call [number]"
"Download Q3 report.xlsx"   ->  "Download Q3 [file]"
"Order 2026-11-16"          ->  "Order [number]"
```

The last two show its limits: a file name with spaces loses only its last word, and an ISO date looks like a long number. That is why anything showing a visitor's file names sits inside `data-track-ignore` and is never reported in the first place. The scrubber is the second line of defense, not the first.

- **Values are cut to GA4's limits.** In a standard property an event parameter value can be 100 characters, except `page_title` (300), `page_referrer` (420) and `page_location` (1,000). A single cut at 100 would chop long page addresses.
- **gtag.js's own events skip all of this.** Enhanced measurement events are sent by gtag.js, not by your code, so `clean()` never sees them. Two of them can carry exactly what the deny-list drops: file downloads send `file_name` and `link_text`, and site search sends `search_term`, read by default from the `q`, `s`, `search`, `query` and `keyword` URL parameters. Turn off the ones that could carry what visitors type or name.

## If you use Google Tag Manager, clear the last event's keys

With `NEXT_PUBLIC_GTM_ID` set, `enableAnalytics()` loads Tag Manager instead of gtag.js, and `send()` pushes to the data layer:

```ts
const GTM_ID = process.env.NEXT_PUBLIC_GTM_ID || "";

// in enableAnalytics(), in place of the gtag.js block when GTM_ID is set
window.dataLayer.push({ "gtm.start": Date.now(), event: "gtm.js" });
loadScript(`https://www.googletagmanager.com/gtm.js?id=${encodeURIComponent(GTM_ID)}`);
```

```ts
// in send(), in place of the gtag call
let lastGtmKeys: string[] = [];

function pushEvent(event: string, payload: Record<string, string | number | boolean>) {
  window.dataLayer = window.dataLayer || [];
  const stale = lastGtmKeys.filter((key) => !(key in payload));
  const reset = Object.fromEntries(stale.map((key) => [key, undefined]));
  lastGtmKeys = Object.keys(payload);
  window.dataLayer.push({ event, ...reset, ...payload });
}
```

The reset is the part that gets missed. Tag Manager keeps one data model per page. Each push merges into it, and a value stays until something overwrites it, for as long as the visitor stays on the page. In a single-page app the page is the whole visit. So if a `tool_run` event pushed `output_format: "webp"` and the next event is a click without that key, a Data Layer Variable for `output_format` still reads `"webp"`, and a GA4 event tag that forwards every parameter sends it along with the click. Setting the previous event's keys to `undefined` clears them. Google's ecommerce examples push `{ ecommerce: null }` before each event for the same reason.

Two more rules for this path:

- **Never load gtag.js and Tag Manager side by side.** Here the two paths are exclusive, so nothing is counted twice.
- **The advertising settings don't come along.** The consent defaults and the two `allow_*` flags live in the gtag.js block. In Tag Manager mode, add `allow_google_signals` and `allow_ad_personalization_signals`, both `false`, as configuration parameters on the container's Google tag.

## Testing without sending anything

Two flags make the whole flow testable:

```ts
const DEBUG = process.env.NEXT_PUBLIC_ANALYTICS_DEBUG === "true";
const DRY_RUN = process.env.NEXT_PUBLIC_ANALYTICS_DRY_RUN === "true";

const isTrackedHost = (hostname: string) =>
  DEBUG || DRY_RUN || hostname === SITE_HOST || hostname.endsWith(`.${SITE_HOST}`);
```

`send()` already logs when either is set and stops before Google in a dry run. In `enableAnalytics()`, the gtag.js block is skipped in a dry run (`if (!scriptLoaded && !DRY_RUN)`), and `debug_mode: DEBUG || undefined` goes into the `config` call.

- **`NEXT_PUBLIC_ANALYTICS_DRY_RUN=true`** treats any host as production. The notice appears and every event is logged to the console, but no Google script loads. This is how to test the consent flow and the event payloads on localhost.
- **`NEXT_PUBLIC_ANALYTICS_DEBUG=true`** runs for real on any host, logs every event and sets `debug_mode`, so events show up in GA4's DebugView. Use it on a preview deployment.

Both are `NEXT_PUBLIC_` variables, which Next.js inlines into the client bundle at build time. Changing them on a running server does nothing: set them, then build or start the dev server.

## GA4 settings this depends on

- **Enhanced measurement.** History-change page views off, as above. Then review file downloads and site search, which bypass the scrubber.
- **Custom definitions.** A parameter you don't register as a custom dimension still shows up in DebugView, but you can't report on it. Register each one you want under Admin → Custom definitions, scope Event, and register numbers as custom metrics. A standard property allows 50 event-scoped custom dimensions and 50 custom metrics. This site's tracking document lists 25 dimensions and 5 metrics.
- **Key events.** Mark the events that mean a visitor got what they came for. This site's tracking document names `resume_export`, `file_download` and `tool_run`.
- **Data retention.** Choose 14 months instead of 2. It only affects Explorations and funnel reports, but those are where you will want to compare a year.

## How to check it after a deploy

Use a private window with the developer tools open:

1. **Load any page.** In the Network panel, filter by `google`: there should be no requests. Under Application → Cookies there should be no `_ga`. From a terminal, `curl -s https://example.com/ | grep -c googletagmanager` should print `0`. For this site's home page it does.
2. **Click Reject.** Still no requests. Local storage holds `consent:v1` with `"analytics":false`.
3. **Open "Cookie settings" and click Accept.** You should see a request for `gtag/js?id=`, then a `collect` request containing `en=page_view`, and the `_ga` and `_ga_<ID>` cookies.
4. **Move around inside the app.** Each navigation adds exactly one `en=page_view`. Two per navigation means history-change page views are still on in enhanced measurement.
5. **Click a button and a link.** Look for `en=ui_click` with `ep.element_text` and `ep.section`. Custom string parameters appear in the request with an `ep.` prefix, numbers with `epn.`.
6. **Reject again.** The `_ga` cookies disappear, and clicks send nothing.
7. **Try a browser that sends Global Privacy Control.** Brave sends it by default, and Firefox has a setting for it. No notice appears, nothing loads, and "Cookie settings" still lets you opt in.

## When to use something else

- **You run ads, or several vendors need consent signals.** Use a certified consent management platform. This setup is for one analytics tool and no advertising.
- **You want modeled numbers for the visitors who decline.** GA4's behavioral modeling needs advanced consent mode, which means loading Google's tag before anyone has answered, and enough denied traffic: at least 1,000 events a day with analytics storage denied, for at least 7 days. Loading the tag early is a decision for whoever owns privacy where you work, not a code detail.
- **You need to filter or enrich events before Google sees them.** That is server-side tagging, covered in [server-side tagging with GTM and GA4](https://www.derar.dev/blog/server-side-tagging-gtm-ga4).

## If you build this on your own site

1. Write the rules down where the next developer will find them. This site keeps them, with every event and parameter, in a tracking document in the repository.
2. Store the choice with a version and an expiry, and treat Global Privacy Control as Reject until the visitor says otherwise.
3. Add gtag.js or Tag Manager from the browser after Accept, with consent defaults before `config`.
4. Send page views yourself, and turn off history-change page views in GA4.
5. Track clicks with one listener and data attributes, and clean every event in one function.
6. If you use Tag Manager, clear the previous event's keys on every push.
7. Run the checks above whenever the root layout or the analytics module changes.

A tag that loads only after Accept is also one less third-party script on the first page load for everyone who hasn't answered. The [Core Web Vitals guide](https://www.derar.dev/blog/core-web-vitals-inp-nextjs-guide#audit-third-party-scripts) covers why that matters for INP. For the rest of the metadata and crawling setup, see the [Next.js technical SEO checklist](https://www.derar.dev/blog/nextjs-technical-seo-checklist).

## Sources

- [Google: Consent mode overview](https://developers.google.com/tag-platform/security/concepts/consent-mode)
- [Google: Set up consent mode on websites](https://developers.google.com/tag-platform/security/guides/consent)
- [Google: Manage privacy settings (ga-disable, Google signals, ad personalization)](https://developers.google.com/tag-platform/security/guides/privacy)
- [Google: Measure pageviews](https://developers.google.com/analytics/devguides/collection/ga4/views?client_type=gtag)
- [Google: Customize cookie settings](https://developers.google.com/tag-platform/security/guides/customize-cookies)
- [Google Tag Manager: The data layer](https://developers.google.com/tag-platform/tag-manager/datalayer)
- [Google: Measure ecommerce (Tag Manager examples)](https://developers.google.com/analytics/devguides/collection/ga4/ecommerce?client_type=gtm)
- [Google Analytics Help: Enhanced measurement events](https://support.google.com/analytics/answer/9216061)
- [Google Analytics Help: Event collection limits](https://support.google.com/analytics/answer/9267744)
- [Google Analytics Help: Custom dimensions and metrics](https://support.google.com/analytics/answer/10075209)
- [Google Analytics Help: Data retention](https://support.google.com/analytics/answer/7667196)
- [Google Analytics Help: Behavioral modeling for consent mode](https://support.google.com/analytics/answer/11161109)
- [Next.js: useSearchParams](https://nextjs.org/docs/app/api-reference/functions/use-search-params)
- [Next.js: Third-party libraries](https://nextjs.org/docs/app/guides/third-party-libraries)
- [Next.js: Environment variables](https://nextjs.org/docs/app/guides/environment-variables)
- [MDN: Navigator.globalPrivacyControl](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/globalPrivacyControl)
