Next.js is arguably the default React framework for production applications in 2026. It's also one of the hardest environments to get cookie consent right. The App Router's split between Server Components and Client Components, streaming SSR, and middleware layer create a set of timing and execution constraints that generic CMP documentation doesn't address.
If you've tried dropping a consent script into your Next.js app and found that it fires before hydration, doesn't work across use client boundaries, or silently skips server-side enforcement, this guide covers every layer: CMP placement, consent state management, dynamic imports, middleware, Consent Mode v2, and CookieBeam integration. All examples use TypeScript.
Place the CookieBeam loader as the first element in <head>, loaded synchronously before GTM, analytics, or other scripts. Do not add async or defer, and exclude it from script-delay optimizers.
Why the App Router Makes Cookie Consent Harder
The App Router introduced a fundamental change: components are Server Components by default. Server Components run on the server, render to HTML, and stream to the client. They can't access window, document, or any browser API. That single constraint breaks the core assumption of every CMP: that it can read and write cookies in the browser, show a banner in the DOM, and listen for user interaction.
Here's what breaks:
- Server Components can't read
document.cookie. You can read request cookies viacookies()fromnext/headers, but those are HTTP cookies from the request, not the live consent state updated client-side. - Streaming SSR sends HTML before hydration. Scripts injected into that HTML can execute before your consent wrapper has even mounted.
- Layout renders before page. If your CMP loads in a page component, the layout (and its scripts) execute first, before the CMP is ready.
'use client'boundaries need careful placement. Your consent provider must be a Client Component (it needsdocumentaccess), but it sits inside a Server Component layout.
Where to Place the Loader: the Root Layout
Place the CookieBeam loader as the first element in <head>, loaded synchronously before any other script. Exclude it from delay, async, and defer optimizers.
Use a native script element in the server-rendered root layout. Framework loading strategies such as beforeInteractive run before hydration but do not guarantee parser-blocking execution before hardcoded trackers.
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
{/* eslint-disable-next-line @next/next/no-sync-scripts */}
<script src="https://cdn.cookiebeam.com/banner/YOUR_BANNER_ID/default/loader.js"></script>
</head>
<body>{children}</body>
</html>
)
}Client Component Wrapper for Consent State
Server Components can't access browser consent state. You need a Client Component that reads consent, subscribes to changes, and exposes the current state to the rest of your app. The pattern is a React context provider marked with 'use client', placed inside your root layout.
// components/ConsentProvider.tsx
'use client'
import { createContext, useContext, useState, useEffect, useCallback } from 'react'
type ConsentState = {
analytics: boolean
marketing: boolean
preferences: boolean
loaded: boolean
}
const ConsentContext = createContext<ConsentState>({
analytics: false,
marketing: false,
preferences: false,
loaded: false,
})
export function ConsentProvider({ children }: { children: React.ReactNode }) {
const [consent, setConsent] = useState<ConsentState>({
analytics: false,
marketing: false,
preferences: false,
loaded: false,
})
useEffect(() => {
const fromCategories = (categories: string[]): ConsentState => ({
analytics: categories.includes('analytics'),
marketing: categories.includes('marketing'),
preferences: categories.includes('preferences'),
loaded: true,
})
// Read initial consent state from the CookieBeam cookie (cb_cookie by default)
const stored = document.cookie
.split('; ')
.find(row => row.startsWith('cb_cookie='))
let categories: string[] = []
if (stored) {
try {
const value = JSON.parse(decodeURIComponent(stored.slice('cb_cookie='.length)))
if (!value.isPending && Array.isArray(value.categories)) categories = value.categories
} catch {
// Unreadable cookie: treat as no consent
}
}
setConsent(fromCategories(categories))
// Listen for consent changes from CookieBeam
const handler = (e: Event) => {
const detail = (e as CustomEvent<{ categories: string[] }>).detail
setConsent(fromCategories(detail.categories))
}
window.addEventListener('cookiebeam:consentUpdate', handler)
return () => window.removeEventListener('cookiebeam:consentUpdate', handler)
}, [])
return (
<ConsentContext.Provider value={consent}>
{children}
</ConsentContext.Provider>
)
}
export function useConsent() {
return useContext(ConsentContext)
}Place <ConsentProvider> inside your root layout, wrapping {children}. The root layout is a Server Component, but it can render Client Components as children, this is the standard App Router pattern. Any descendant Client Component can now call useConsent() to check consent and react to changes in real time.
Dynamic Imports for Consent-Dependent Analytics
In a traditional multi-page site, you block a tracking script by changing its type attribute or removing its src. In Next.js, tracking is often a component, a Google Analytics wrapper, a Meta Pixel initializer, a Hotjar integration. You don't want these components to even load their JavaScript bundles until consent is granted.
next/dynamic with ssr: false is the mechanism for this. It lazy-loads a component only on the client, and you can gate the import on consent state. There's a critical constraint: next/dynamic with ssr: false must be used inside a Client Component ('use client'), not a Server Component.
// components/ConsentGatedAnalytics.tsx
'use client'
import dynamic from 'next/dynamic'
import { useConsent } from './ConsentProvider'
const GoogleAnalytics = dynamic(
() => import('./GoogleAnalytics'),
{ ssr: false }
)
const MetaPixel = dynamic(
() => import('./MetaPixel'),
{ ssr: false }
)
export function ConsentGatedAnalytics() {
const { analytics, marketing, loaded } = useConsent()
if (!loaded) return null
return (
<>
{analytics && <GoogleAnalytics />}
{marketing && <MetaPixel />}
</>
)
}This ensures the analytics bundle isn't in the server-rendered HTML, isn't downloaded until consent is true, and unmounts cleanly if consent is revoked. The underlying analytics component is straightforward:
// components/GoogleAnalytics.tsx
'use client'
import Script from 'next/script'
export default function GoogleAnalytics() {
return (
<>
<Script
src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"
strategy="afterInteractive"
/>
<Script id="ga-config" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXX');
`}
</Script>
</>
)
}afterInteractive is correct here, by the time this component renders, consent is already granted.
Middleware-Level Consent Enforcement
Next.js middleware (middleware.ts) runs on the Edge Runtime before every request. It's the only server-side layer where you can check consent before content is served. Read cookies from the NextRequest object and forward consent state as headers:
// middleware.ts
import { NextResponse, type NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
const consentCookie = request.cookies.get('cb_cookie')
const response = NextResponse.next()
if (consentCookie) {
try {
const consent = JSON.parse(consentCookie.value)
const categories: string[] =
!consent.isPending && Array.isArray(consent.categories) ? consent.categories : []
// Pass consent state to Server Components via headers
response.headers.set('x-consent-analytics', categories.includes('analytics') ? '1' : '0')
response.headers.set('x-consent-marketing', categories.includes('marketing') ? '1' : '0')
} catch {
// Invalid cookie — treat as no consent
response.headers.set('x-consent-analytics', '0')
response.headers.set('x-consent-marketing', '0')
}
} else {
// No consent cookie — first visit or expired
response.headers.set('x-consent-analytics', '0')
response.headers.set('x-consent-marketing', '0')
}
return response
}
export const config = {
matcher: [
// Run on all pages but skip static assets and API routes
'/((?!_next/static|_next/image|favicon.ico|api/).*)',
],
}Server Components can then read these headers via await headers():
// app/page.tsx
import { headers } from 'next/headers'
export default async function Page() {
const headerStore = await headers()
const analyticsConsented = headerStore.get('x-consent-analytics') === '1'
return (
<main>
{/* Only render server-side tracking pixel if consented */}
{analyticsConsented && (
<img
src="https://analytics.example.com/pixel.gif?page=/"
alt=""
width={1}
height={1}
/>
)}
</main>
)
}Caveat: middleware reads the cookie from the request, so it reflects consent at the time of navigation. If the user changes consent without navigating, the server won't see it until the next request. Server-side enforcement complements client-side blocking, it doesn't replace it.
Google Tag Manager with Consent Mode v2
Place the CookieBeam loader as the first element in <head>, loaded synchronously before any other script. Exclude it from delay, async, and defer optimizers.
Enable Consent Mode in the banner settings. The synchronous loader establishes defaults before a GTM bootstrap placed later in the document. For a GTM-template installation, use the Consent Initialization trigger and manage non-essential tags in GTM; hardcoded scripts need separate inert markup.
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
{/* eslint-disable-next-line @next/next/no-sync-scripts */}
<script src="https://cdn.cookiebeam.com/banner/YOUR_BANNER_ID/default/loader.js"></script>
</head>
<body>{children}</body>
</html>
)
}next/script Strategies for Tracking Scripts
Choosing the right next/script strategy for each tracking script directly affects compliance. Here's a decision framework:
- CMP / Consent Manager: A native synchronous script as the first element in
<head>of the rootapp/layout.tsx. - GTM container:
afterInteractive. Needs consent defaults set first by the synchronous loader, then loads after hydration. - GA4 / Google Ads:
afterInteractive, but only rendered when consent is granted (use the dynamic import pattern above). - Meta Pixel, TikTok Pixel:
afterInteractive, consent-gated. These should never load until marketing consent is given. - Hotjar, Clarity, heatmaps:
lazyOnload, consent-gated. Session recording tools are never urgent and can safely defer to idle time. - Chat widgets (Intercom, Drift):
lazyOnload. These set cookies but aren't page-critical. Gate on preferences consent if your categorization requires it.
The key rule: the CMP loader must be native, synchronous, and first in the head. Framework strategies are for other scripts and do not replace early consent initialization. Tracking scripts in beforeInteractive execute before any Client Component consent check has run. And afterInteractive without consent gating fires immediately after hydration, safe for GTM (which has Consent Mode), dangerous for standalone analytics scripts.
Server Actions and Consent Verification
Server Actions in Next.js let you run server-side code triggered by client interactions, form submissions, button clicks, data mutations. When a Server Action processes data that should only be collected with consent (like saving user behavior to an analytics database or triggering a server-side conversion event), you need to verify consent server-side.
The approach combines the middleware pattern (forwarding consent via headers) with the cookies() function inside the Server Action:
// app/actions.ts
'use server'
import { cookies } from 'next/headers'
export async function trackConversion(formData: FormData) {
const cookieStore = await cookies()
const consentCookie = cookieStore.get('cb_cookie')
let analyticsConsented = false
if (consentCookie) {
try {
const consent = JSON.parse(consentCookie.value)
analyticsConsented =
!consent.isPending &&
Array.isArray(consent.categories) &&
consent.categories.includes('analytics')
} catch {
// Invalid cookie — no consent
}
}
// Always process the form (functional requirement)
const orderId = formData.get('orderId') as string
await processOrder(orderId)
// Only track the conversion if analytics consent was given
if (analyticsConsented) {
await sendServerSideConversion({
event: 'purchase',
orderId,
value: formData.get('value') as string,
})
}
}Note that cookies() is async, you must await it. The functional logic (processing the order) should always run regardless of consent. Only tracking side-effects, sending data to analytics, firing Meta CAPI or Google Enhanced Conversions events, should be consent-gated. Without server-side verification, these APIs bypass client-side consent entirely.
How CookieBeam Integrates with Next.js
CookieBeam is built with Next.js, so this is first-party knowledge. The entire integration is a native script element as the first element in the head in your root layout:
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
{/* eslint-disable-next-line @next/next/no-sync-scripts */}
<script src="https://cdn.cookiebeam.com/banner/YOUR_BANNER_ID/default/loader.js"></script>
</head>
<body>{children}</body>
</html>
)
}Replace YOUR_BANNER_ID with your banner's public ID from the dashboard.
Manual Script Gating
The loader holds inert placeholders with type="text/plain" and data-category attributes, activating them only after consent. For manual gating, render a raw placeholder in the server layout head (or Head in Pages Router pages/_document.tsx) after the loader. Do not insert it through next/script: placeholders are scanned once at initialization.
// Server-rendered placeholder after the loader in the layout head
<script
data-src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"
type="text/plain" data-category="analytics"
></script>Consent Mode v2 Out of the Box
CookieBeam automatically sets Consent Mode defaults and pushes consent('update'...) on user choice. The boilerplate from the GTM section above is handled for you.
Combining Both Patterns
CookieBeam's auto-blocking handles DOM-level scripts (GTM, standalone pixels). The React-level dynamic import pattern from earlier handles component-level gating (React-wrapped analytics, embedded widgets). The two approaches complement each other.
Common Pitfalls
- Wrong strategy for the CMP. Using
afterInteractivefor the CMP means tracking scripts with the same strategy might fire first. Use a native synchronous loader first in the head. - CMP in a page component. If it loads in
app/page.tsxinstead of the root layout, navigating to any other route means no CMP. - Assuming
cookies()is synchronous. Current Next.js versions requireawait cookies(). Withoutawait, you get a Promise, not a cookie store. Same forheaders(). - Server-side consent as the sole check. The
cookies()value is only as fresh as the last navigation. If the user changed consent client-side without navigating, the server value is stale. Always pair server checks with client-side gating. - Missing
ssr: falseon analytics components. Without it, the tracking script's initialization code runs during SSR and gets included in streamed HTML, before any consent check.
Implementation Checklist
Use this checklist before shipping your Next.js App Router application with cookie consent:
- CMP loader is a native synchronous script first in the head in root
app/layout.tsx - Consent Mode v2 defaults are set before GTM loads (or CookieBeam handles this automatically)
- All analytics/marketing scripts use
afterInteractiveorlazyOnload, neverbeforeInteractive - Consent-dependent components use
next/dynamicwithssr: falseinside Client Components - A
ConsentProvidercontext (or CookieBeam callbacks) exposes consent state to the component tree - Server Actions that process tracking data verify consent via
await cookies() - Middleware forwards consent state as headers for Server Components that need it
- No tracking scripts render during SSR, all are client-only
- Cookie audit completed to identify all cookies your Next.js app sets
- Consent banner tested across route navigations (not just initial page load)
Further Reading
- Cookie Consent for Single-Page Apps (React, Vue, Angular), broader SPA patterns, route-change handling, and hydration timing
- Google Consent Mode v2: Complete Implementation Guide
- How to Block Scripts Until Cookie Consent, script blocking techniques across platforms
- Consent Mode v2: Advanced vs Basic
- Cookie Banner Performance & Core Web Vitals, relevant because
beforeInteractiveimpacts LCP timing - Next.js Script Component documentation






