Consent Mode v2 before the first ad

Register a denied Consent Mode v2 default ahead of the AdSense script in Next.js, let a certified CMP send the updates, and check the order in the browser.

Published

Updated

Reading time

12 min

A consent banner can be present, working and accurately described in the privacy notice, and the page can still send data to an ad network before anyone has clicked it. In a framework that bundles, hydrates and reorders scripts for speed, "the banner appears first" and "Google's code sees a denied state first" are different claims, and only the second one is about consent mode.

This walkthrough sets up one coherent path for a Next.js 16 App Router site that is about to serve AdSense ads: a certified consent management platform (CMP) collects the choice, a denied default is registered before any Google code runs, and consent mode carries the choice to Google's tags. It is engineering guidance, not legal advice. What counts as valid consent, who is covered and what a privacy notice must say are questions for a lawyer or data protection officer.

I built consent handling before serving a single ad, and the trigger was prose, not code. I found a statement on my own landing page about not using advertising cookies that was true only because no ad code existed yet, and I replaced it with an honest advertising disclosure before any ad script was added.

Two mechanisms that get confused#

Two separate things are involved, and a banner often implements only one.

The first is Google's EU user consent policy. For AdSense, Google states that a certified CMP integrated with the IAB Transparency and Consent Framework (TCF) is required to serve personalized ads to users in the EEA and the UK (from 16 January 2024) and in Switzerland (from 31 July 2024). Only traffic that goes through a certified CMP is eligible for personalized ads; other traffic can receive non-personalized or limited ads where supported. Google's own CMP, configured in AdSense under Privacy and messaging, is on the certified list. A banner you write yourself is not certified, so it does not meet this rule however well it is built.

The second is consent mode, which is how your page tells Google tags what the visitor allowed. Consent mode does not collect consent and does not remember it. Google's developer guide says the order of the code is vital, that defaults registered out of order will not work, and that because consent mode does not save choices, something has to persist them and call the update command on later pages. In practice that something is the CMP.

So the split of work is fixed: the CMP shows the message, stores the choice and sends consent update; your code guarantees that a consent default exists before any Google tag can read it. Everything below follows from that. Writing your own banner and cookie for ads in the EEA, UK or Switzerland is the one path this article does not take.

The four signals the default must cover#

The Google tag guide lists seven consent types. Four of them matter for ads and measurement, and the last two were added with Consent Mode v2:

SignalWhat it covers
ad_storageStorage related to advertising, such as cookies
analytics_storageStorage related to analytics, such as visit duration
ad_user_dataSending user data related to advertising to Google
ad_personalizationPersonalized advertising, such as remarketing

A default that sets only ad_storage and analytics_storage predates v2 and leaves the other two unset. The remaining three types (functionality_storage, personalization_storage, security_storage) are not needed for this setup.

Pick basic or advanced before writing code#

Consent mode has two implementation modes, described in Google's overview, and the choice decides how the scripts are loaded.

BasicAdvanced
Google tags before a choiceBlocked until the visitor interacts with the bannerLoad immediately with the default state
Data sent before a choiceNone, not even the default stateCookieless measurements while consent is denied
After consentTags send the default, then the update, and full dataTags write cookies and send full data
If the visitor declinesNothing is sent; modelling uses a general modelCookieless pings continue; modelling uses a more detailed, advertiser-specific model

Advanced mode sends something to Google from a visitor who has not consented yet, even if it is cookieless. Whether that is acceptable for your audience is a legal question. Basic mode is the conservative answer, at the price of less modelled data.

The rest of this article builds advanced mode with the Google CMP, because that is what a plain AdSense snippet does: the ad script loads on every page and the default decides what it may do. A section near the end shows the change needed for basic mode, which requires holding the ad script back until the CMP reports a state. Do not mix the two: loading the script for everyone while describing the setup as basic is how a site ends up promising more than it does.

Configure the CMP in AdSense#

In AdSense, open Privacy and messaging and create the European regulations message. The same card has settings to enable consent mode for advertising purposes and, only once that is ticked, for analytics. With them on, Google's CMP translates the visitor's choices into the consent mode signals. Two details from the AdSense help pages are easy to miss:

  • Google's CMP only updates consent for visitors who are shown a message. Visitors outside the EEA, UK and Switzerland get no update from it, so the default you register decides what happens to them (see the next section).
  • If a message is reopened later, through a revocation link or your site's privacy settings, it presents all three options again (do not consent, consent, manage options). Reopening is part of the requirement that withdrawing consent be as easy as giving it, so add the link to your footer.
The default has to exist before anything that reads it. Everything after step 1 can be late; step 1 cannot.

Register the default before any Google script#

Next.js gives you the ordering primitive. In the next/script reference that ships with Next.js 16, beforeInteractive scripts are injected into the initial HTML, run before any Next.js module and in the order they appear, and they must be placed in the root layout. An inline script needs an id. The default is a short inline string:

src/lib/consent-default.tsts
// All four signals denied for every visitor.
// wait_for_update gives the CMP a short window to replay a stored choice before tags fire.
export const consentDefault = `
window.dataLayer = window.dataLayer || [];
function gtag(){ dataLayer.push(arguments); }
gtag("consent", "default", {
  ad_storage: "denied",
  ad_user_data: "denied",
  ad_personalization: "denied",
  analytics_storage: "denied",
  wait_for_update: 500
});
`;

The 500 is the figure in Google's own example for a CMP that sends its update asynchronously. It is a ceiling on how long tags wait, not a promise about how long your CMP takes.

This default has no region parameter, so it applies to every visitor, and that is the cautious choice. Google's CMP only updates visitors who are shown a message, so a visitor in, say, Canada keeps the denied state for the whole visit. That costs some measurement where no banner was required. Granting by default outside Europe is a decision about US state laws and other jurisdictions, not a performance tweak, and it belongs to whoever is legally responsible for the site.

Denied by default also fails safe under my own mistakes. If I ship a new tag and forget to wire it to consent properly, the result is data I should have had and did not, which is annoying and fixable. The opposite default would track a visitor who said no, and that is a violation, not a bug.

If that person decides to grant elsewhere, the region parameter is the tool. It takes ISO 3166-2 codes, and Google's guide recommends scoping defaults to the regions where you show banners. Two default commands then coexist, and the more specific region wins:

jsjs
gtag("consent", "default", {
  ad_storage: "denied", ad_user_data: "denied",
  ad_personalization: "denied", analytics_storage: "denied",
  wait_for_update: 500,
  region: [
    "AT","BE","BG","HR","CY","CZ","DK","EE","FI","FR","DE","GR","HU","IE",
    "IT","LV","LT","LU","MT","NL","PL","PT","RO","SK","SI","ES","SE",
    "IS","LI","NO","GB","CH"
  ]
});
// then a second default with the other four values granted and no region

That list is the 27 EU members, Iceland, Liechtenstein and Norway, the UK and Switzerland. The denied default for the rest of the world, with no region, is simply what the first snippet already does.

Wire it into the root layout#

The layout renders the default first and the ad script second. The flag comes from one config module so that with ads off, no consent, CMP or ad code is rendered at all:

src/app/layout.tsxtsx
import Script from "next/script";
import { publicEnv } from "@/config/env";
import { site } from "@/config/site";
import { consentDefault } from "@/lib/consent-default";
 
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        {publicEnv.adsEnabled ? (
          <>
            <Script id="consent-default" strategy="beforeInteractive">
              {consentDefault}
            </Script>
            <Script
              id="ad-script"
              strategy="afterInteractive"
              async
              crossOrigin="anonymous"
              src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${site.adsensePublisherId}`}
            />
          </>
        ) : null}
      </body>
    </html>
  );
}

Writing the elements in the body is fine: beforeInteractive scripts are hoisted into the head, and the afterInteractive ad script runs after hydration starts, so after the default. Copy the exact AdSense snippet from your own account, because the account is the source of the publisher ID and Google may change the snippet's shape.

There is no cookie code, banner component or applyChoice function on the site's side in this path. That is deliberate: the CMP owns persistence and the update call, and a second implementation that also calls consent update would produce two sources of truth.

My own earlier version was a hand-built layer: a set of consent flags that all start denied before any script that could set a cookie, one place holding the decision, and a small banner and a settings control on top. It took days, not weeks. I kept ad storage denied even when the visitor clicked Accept, because the system had no personalisation pipeline a visitor could meaningfully consent to, and an Accept button should grant only what the platform can honour. I built it knowing a certified CMP would replace it, so everything downstream reads the flags and nothing depends on the banner that set them.

Switching to basic mode#

For basic mode the ad script must not exist on the page until the CMP has a state. That needs a CMP whose loading you control, which in practice means a third-party certified CMP. The TCF API gives a hook: __tcfapi("addEventListener", 2, callback) reports events, and tcloaded or useractioncomplete mean a usable consent string exists. The component below inserts the ad script only then, and fails closed when there is no CMP:

src/components/ads/AdScriptGate.tsxtsx
"use client";
 
import { useEffect, useState } from "react";
import Script from "next/script";
 
type TcfData = { eventStatus?: string };
type TcfApi = (
  cmd: "addEventListener",
  version: 2,
  cb: (data: TcfData, success: boolean) => void,
) => void;
 
export function AdScriptGate({ src }: { src: string }) {
  const [ready, setReady] = useState(false);
 
  useEffect(() => {
    const api = (window as unknown as { __tcfapi?: TcfApi }).__tcfapi;
    if (!api) return; // no CMP: no ads
    api("addEventListener", 2, (data, success) => {
      if (success && (data.eventStatus === "tcloaded" || data.eventStatus === "useractioncomplete")) {
        setReady(true);
      }
    });
  }, []);
 
  return ready ? (
    <Script id="ad-script" src={src} strategy="afterInteractive" async crossOrigin="anonymous" />
  ) : null;
}

In the layout, this component replaces the second Script; the inline default stays. The gate is only as good as the vendor's stub: TCF expects the CMP to expose __tcfapi early enough to queue calls, and the effect above simply gives up if it is missing. Check how your vendor exposes it before relying on this. Note also that a visitor who declines will, in basic mode, never load the script at all, which includes the visitors who would have seen non-personalized ads.

Prove the order in the browser#

Use a clean profile every time, because a stored choice hides first-visit bugs. Three checks cover the failure modes.

  1. The dataLayer. Open DevTools, clear site data, reload and type dataLayer in the console. The first entry must be consent / default, ahead of any js, config or event entry. After you choose in the message, a consent / update entry should follow. Reload and confirm the CMP replays the choice rather than showing the message again.
  2. The Network tab. Filter by Google domains and reload before making a choice. In advanced mode you should see requests, but none that carry ad cookies. In basic mode you should see none. If the result differs from the mode you decided on, the order is wrong somewhere.
  3. Tag Assistant. Google's Tag Assistant shows the consent state each tag saw when it fired, which catches the case where a default exists but runs after the tag.

Test again with the production Content Security Policy switched on. A strict policy refuses an inline script that has no nonce or hash, and refuses the CMP's host unless it is allowed. The failure is silent and the page then behaves as if no consent code existed. The trade-offs of that policy, including what a nonce does to static rendering, are covered in a content security policy for Next.js with third-party scripts.

A banner must not move the page#

A message that inserts itself above the article after first paint is a layout shift on every first visit, on exactly the pages that carry the ads. Prefer an overlay or a reserved area, and check cumulative layout shift on a first visit with a clean profile. The same reasoning about late-arriving third-party code applies to the ad script itself; LCP, image and font loading for a content site covers what else competes with the first paint.

What stays outside this setup#

  • Other trackers. Consent mode steers Google tags. A video embed or a social widget with its own tracking is outside it and needs its own gate.
  • Tag Manager. If you use Google Tag Manager instead of raw gtag, the equivalents are the consent template APIs and the Consent Initialization trigger. Do not paste a gtag default into a container and expect the template machinery to see it.
  • Prose that drifts. I change the legal pages in the same pull request as anything that changes what the site stores, and my deploy checklist treats a broken cookie-settings button binding as a regression like any other.
  • Proof of compliance. The consent state tells Google tags how to behave. It does not audit the rest of the page, and it is not a legal opinion.

The part that transfers to any stack is short: decide the mode first, register a denied default that nothing can run ahead of, let one component own the choice and the updates, and give visitors a way to change their mind.

Share
All articles →