Engineering6 min read

Cookie consent in Next.js that keeps your pages static

A consent banner for a statically generated Next.js site: ask only where the law requires it, load no tracker before an answer, and keep every page cached.

We added session replay to this site, and then noticed what we had done: a tool that records visits was now running for visitors in the EU who had never been asked. Analytics had been doing the same for years.

The fix had three requirements that pull against each other. Ask the visitors the law says must be asked. Do not put a banner in front of everyone else. And keep every page statically generated, because that is where the speed comes from. This is how the three fit together, with the code.

None of this is legal advice. It is an engineering account of one implementation.

A static page does not know where the visitor is

The banner has to appear for a visitor from Madrid and not for one from Chicago. The page they both receive is the same file, built hours ago and served from a CDN. It has no idea who is asking.

There are three ways out, and two of them are bad.

Rendering each page on the server per request gives you the country and takes away the cache. Every visitor now waits for a render so that some of them can see a banner.

Calling a geolocation API from the browser keeps the cache and adds a request before the page knows what to do. Until it returns you either show the banner to everyone, or load the trackers for everyone, and the second is the thing you were trying to stop.

The third way is middleware. It runs at the edge on every request, before the cache, and on most hosts it is handed the visitor's country in a header. It cannot change the cached page, but it can attach a cookie to the response:

function withGeo(req, res) {
  const country = req.geo?.country || req.headers.get('x-vercel-ip-country');

  if (country && req.cookies.get('su_geo')?.value !== country) {
    res.cookies.set('su_geo', country, {
      path: '/',
      sameSite: 'lax',
      secure: true,
    });
  }

  return res;
}

The page stays a cache hit. The cookie arrives with it, and by the time any script runs, the browser can read the country from document.cookie without asking anyone.

req.geo exists up to Next.js 14 and was removed in 15. The header works in both.

Two details. The cookie is rewritten only when the value changes, so most responses carry no Set-Cookie at all. And a missing country counts as "ask": when the system cannot tell, it should fail towards the banner.

Google's Consent Mode comes in two forms, and the names hide how different they are.

In the advanced form the Google tag loads for everyone. Before consent it sets no cookies, but it still sends requests to Google, so-called cookieless pings, which Google uses to model the visitors who refused.

In the basic form nothing loads until the visitor agrees. No script, no request, no ping.

We chose basic, for two reasons. The first is that it is the version that matches what a visitor believes "Reject" means. The second is that the benefit of the advanced form did not apply to us. Behavioural modelling has data thresholds: about a thousand events a day from visitors who refused, and about a thousand daily users who agreed. A site below that sends the pings and gets no model in return.

So the trackers are not configured to behave. They are not rendered.

Gating a script without a hydration mismatch

The consent state lives in cookies, which exist only in the browser. The server render cannot know it, and if the server and the first client render disagree, React reports a hydration error.

useSyncExternalStore is built for this. It takes a separate snapshot for the server, and re-renders after hydration with the real one:

export type ConsentState = 'unknown' | 'pending' | 'granted' | 'denied';

export const getConsentState = (): ConsentState => {
  const stored = readCookie('su_consent');
  if (stored === 'granted' || stored === 'denied') return stored;
  return isConsentRegion() ? 'pending' : 'granted';
};

export const useConsentState = () =>
  useSyncExternalStore(subscribeConsent, getConsentState, () => 'unknown');

Four states, not two. unknown is the server and the first client pass: render nothing. pending is a visitor who has to be asked and has not answered: show the banner, load nothing. Then the two answers.

Each tracker becomes a small client component that returns null unless the state is granted:

export const SessionReplay = () => {
  const consent = useConsentState();
  if (consent !== 'granted') return null;

  return <Script src={TAG_URL} strategy="afterInteractive" />;
};

There is no way for a tracker to load early, because before consent there is no script element for the browser to fetch.

The banner itself

Accept and Reject are the same button twice. Same size, same colour, same row. In January 2022 the French regulator fined Google 150 million euros because refusing cookies took more clicks than accepting them. A green Accept beside a grey text link is the same pattern with better manners.

The answer can be changed. A "Cookie settings" control in the footer reopens the banner for everyone, including visitors who were never asked. It shows the current state, so nobody has to guess what they chose last spring.

Withdrawal reloads the page. A script that is already running cannot be unloaded. When a visitor who had agreed changes their mind, the code deletes the trackers' cookies and reloads, and the reloaded page never requests them. The same cleanup runs on any refusal, which also clears cookies set before the banner existed.

Test the network, not the banner

A banner is an interface. Consent is what the network tab shows.

On a site we audited this month, the banner was there, it had a "Reject all" button, and three trackers kept sending data after it was pressed. Nobody had looked past the button.

The checks that matter, run on production:

  1. Before any choice: no request to the analytics or replay hosts. Not a small one. None.
  2. After Accept: the requests appear, without a reload.
  3. After withdrawing: the page reloads, the trackers' cookies are gone, and there are still no requests.
  4. The page is still served from cache. A consent layer that turned every page dynamic has solved one problem by creating another.

Run the first check from an address in a region that must be asked, and once more from one that need not be.

What a banner does not fix

The privacy policy still has to name the tools and say what they collect. A banner that asks about "analytics" while the policy mentions none of it is half the job.

Embedded third-party widgets, a booking calendar for instance, set their own cookies from their own origin. Your banner does not govern them unless you also hold back the embed until consent.

And if you run advertising, the banner needs a second question. Ours asks about analytics only, so advertising signals stay off for visitors in consent regions.

Consent that does not match what the network does is one of the things a website audit checks first, because it is the one with a regulator attached. If you want it built properly into a Next.js site, that is our front-end development work.