Skip to main content
Back to Guides
Compliance7 min readBy Armin Zaribaf

Next.js Cookie Banner for CCPA/CPRA: 2026 Setup

Next.js renders ad pixels inside React components, so a California opt-out has to reach into the component tree. Here's how to load the consent runtime, gate client-side pixels, and read the Sec-GPC header on the server.

California doesn't require an opt-in cookie modal. What the CCPA and its CPRA amendments actually require trips up many Next.js sites: a functioning opt-out of the sale and sharing of personal information, tags that respect that choice, and automatic handling of the Global Privacy Control browser signal. Under the CPRA, "sharing" means disclosing data for cross-context behavioral advertising even when no money changes hands, which is what most ad pixels do the moment they fire. Next.js adds its own wrinkle: advertising tags often live inside React components that mount on the client, so a consent tool has to reach into the component lifecycle to stop them.

CCPA/CPRA requirements and where they live in a Next.js app
RequirementWhat California expectsIn Next.js
Opt-out link"Do Not Sell or Share My Personal Information", or the alternative "Your Privacy Choices" link, on every pageA link in the shared layout footer, plus the consent tool's persistent link
Opt-out preference signalsTreat Global Privacy Control as a valid opt-out request, no extra clickClient side: handled by the consent tool before tags fire. Server side: read the Sec-GPC header
Sensitive dataA "Limit the Use of My Sensitive Personal Information" link if you use sensitive data beyond the permitted purposesApplies if forms or API routes collect health, financial or location data
MinorsOpt-in before selling or sharing data of consumers you know are under 16Server or API route logic; a banner can't infer age
Re-askingWait at least 12 months before asking someone who opted out to opt back inA consent-tool setting

The loader has to execute before any other script on the page. In an App Router project, put it in the root app/layout.tsx as a plain <script> tag inside the <head>. Don't use next/script for the loader: its beforeInteractive strategy still defers execution past the point where early tags can fire. A native synchronous script tag blocks the parser just long enough to establish the consent state before anything else runs. See install on Next.js.

app/layout.tsx
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <head>
        {/* Consent loader: synchronous, before every other script */}
        <script
          id="CookieBeam"
          src="https://cdn.cookiebeam.com/banner/PUBLIC_BANNER_ID/default/loader.js"
          type="text/javascript"
        />
      </head>
      <body>{children}</body>
    </html>
  )
}

Gate pixels rendered by React

Ad pixels that live inside React components need a client-side guard. Check the consent state with acceptedCategory in a useEffect, and listen for cookiebeam:consentUpdate so the component responds when a visitor changes their choice. Under the opt-out model, marketing starts granted and flips to denied once someone opts out or arrives with GPC enabled. Once a pixel's script has already executed, an opt-out stops it from reloading on later navigations, but it can't unload code that already ran in the current page session.

components/ad-pixel.tsx
'use client'

import { useEffect, useState } from 'react'

type CookieBeamApi = { acceptedCategory(category: string): boolean }

function marketingAllowed(): boolean {
  const cb = (window as unknown as { CookieBeam?: CookieBeamApi }).CookieBeam
  try {
    return cb?.acceptedCategory('marketing') === true
  } catch {
    return false // runtime not initialized yet; the consent event updates it
  }
}

export function AdPixel() {
  const [allowed, setAllowed] = useState(false)

  useEffect(() => {
    const update = () => setAllowed(marketingAllowed())
    update()
    window.addEventListener('cookiebeam:consentUpdate', update)
    return () => window.removeEventListener('cookiebeam:consentUpdate', update)
  }, [])

  if (!allowed) return null

  return (
    <script
      src="https://example.com/ad-pixel.js"
      async
    />
  )
}

GPC on the server

Browsers that have Global Privacy Control turned on send a Sec-GPC: 1 header with every request. The consent tool handles GPC on the client, but server-side code doesn't see browser-side consent. If your API routes or middleware assemble responses that include personal data used for advertising, or forward events to a conversions API, read the header there too.

Set up CookieBeam for California visitors

1

Publish your banner first

Build the banner in CookieBeam, set up your categories, and publish it to production so the loader has a configuration to serve. The quickstart walks through this.

2

Add the loader to app/layout.tsx

Place a synchronous <script> tag in the <head> of the root layout, before every other script. Don't use next/script for the loader. Don't add async or defer. See install on Next.js.

3

Apply the CCPA/CPRA preset

On the banner's Regional settings page, add a rule from the CCPA/CPRA framework preset. It targets California visitors with an opt-out banner in a bar inline layout at the bottom center of the page, with a preferences button that reads "Do Not Sell or Share My Personal Information" and opens the US opt-out panel. Enable the rule's Do-Not-Sell link option so a persistent link stays reachable after the first visit. If you serve visitors in other states with privacy laws, add the US Opt-Out States preset too. See regional rules.

4

Gate React-rendered pixels

Wrap ad pixels in client components that check acceptedCategory('marketing') and listen for cookiebeam:consentUpdate. For scripts not rendered by React, use inert markup (type="text/plain" with data-category). See script blocking.

5

Keep Consent Mode on

Turn on Google Consent Mode in the banner settings. It updates Google tags directly, and it's also the event that CookieBeam's vendor consent bridges listen to.

6

Check the Sec-GPC header server-side

If your API routes or middleware build responses that include data used for advertising, read request.headers.get('sec-gpc') and suppress that data when it returns '1'.

7

Save, publish and test

Click Save Settings, then Publish. Rule changes reach visitors only after a publish. Then run the California test below.

Test your Next.js site like a California visitor

  1. Open the site in a clean browser profile from California, or use a geo-simulated preview, and confirm the opt-out banner appears.
  2. Opt out of sale and sharing, reload the page, and check the Network tab. Advertising pixels shouldn't load.
  3. In a GPC-enabled browser, confirm navigator.globalPrivacyControl is true, load the site fresh, and verify that advertising tags never fire without any click.
  4. Confirm the Do-Not-Sell link is still reachable after the first choice.
  5. Navigate between routes using client-side navigation and confirm marketing scripts don't reload after an opt-out. The consent state persists across soft navigations, but a component that already mounted its pixel can't unload it retroactively.
  6. Send a request with Sec-GPC: 1 to an API route or server component that returns personalized advertising data, and confirm the server suppresses it.

The cookie banner QA checklist covers the same checks for EU and UK visitors.

Frequently Asked Questions

Why not use next/script for the consent loader?

The beforeInteractive strategy in next/script still defers execution past the point where early scripts can fire. A native synchronous <script> tag in the root layout's <head> blocks the parser just long enough to set up the consent state before anything else runs.

Does an opt-out unload a pixel that already ran?

No. Once a script has executed in the browser, its side effects (cookies set, network requests sent) can't be reversed. The opt-out prevents the pixel from loading on later navigations. That's why establishing the consent state before the first render matters.

Do I need to check Sec-GPC on the server?

The consent tool handles GPC on the client. But if your server-side code assembles responses that include data used for cross-context behavioral advertising, reading the Sec-GPC header lets you suppress that data before it reaches the browser.

What about static pages exported with next export?

Static HTML works the same way: the synchronous loader in the head runs before any other script. The consent tool operates entirely on the client, so no server component or API route is needed for basic tag gating.

Cookie consent on Next.js covers the GDPR side and the full loader setup. For the law itself, see how to build a compliant Do Not Sell or Share link, Global Privacy Control explained and CPRA enforcement in 2025-2026. If you serve other states too, the US state privacy cookie banner checklist maps them all.

Primary sources: California Attorney General CCPA page, the California Privacy Protection Agency (regulations and enforcement decisions), and the Global Privacy Control specification.

This page summarizes the law as we understand it in October 2026 for website and cookie decisions. It isn't legal advice. Statutes, regulations and attorney general guidance change, so confirm the current text with counsel before relying on any threshold or date here.

7 min read

GPP, MSPA & US State Signals: A Publisher's Guide

The US Privacy String you built for CCPA was deprecated in January 2024. GPP, the US National string, and the MSPA replaced it, and getting the signal wrong can be a misrepresentation. Here's how the new US privacy signals move through the ad stack.

5 min read

Building a TCF CMP That Passes IAB Validation

What it takes for a Consent Management Platform to pass IAB Europe's TCF checks: a registered CMP ID, a cleanly decodable TC String, event-listener delivery, and encoding against the right GVL version.

9 min read

How to Migrate Your CMP Without Losing Existing Consent Records

A step-by-step technical guide to switching consent management platforms without losing consent records, triggering mass re-consent, or breaking Consent Mode. Covers export, category mapping, parallel runs, and zero-downtime migration patterns.