Skip to documentation content

Next.js (App Router)

Add the CookieBeam loader to the root layout of a Next.js App Router site, with a CSP nonce, and read consent from Client Components.

Last updated:

In the App Router, the loader goes in the root layout, app/layout.tsx, as a native <script> element inside <head>. Every route renders inside that layout, so the tag is in the server-rendered HTML of every page. Read Install in a web framework first for the rules every framework shares.

Add the loader

Copy your production loader from Deployment → Install and put it at the top of <head> in your layout:

// app/layout.tsx
const COOKIEBEAM_LOADER =
  'https://cdn.cookiebeam.com/banner/PUBLIC_BANNER_ID/default/loader.js';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <head>
        {/* CookieBeam before any tracker or third-party script you add. */}
        {/* eslint-disable-next-line @next/next/no-sync-scripts */}
        <script src={COOKIEBEAM_LOADER} />
      </head>
      <body>{children}</body>
    </html>
  );
}

Use the plain <script> element, not next/script. Its loading strategies decide when a script runs, and even beforeInteractive doesn't guarantee that the loader runs parser-blocking before trackers hard-coded in the page. The @next/next/no-sync-scripts lint rule flags the synchronous tag; the synchronous load is deliberate here, so disable the rule on that line.

Put Google Tag Manager, gtag.js and other tags after it, also in the root layout.

With a nonce-based CSP

If your middleware.ts (named proxy.ts from Next.js 16) builds a Content-Security-Policy with a per-request nonce and passes it to the app on a request header, give the loader the same nonce. This example reads it from x-nonce:

// app/layout.tsx
import { headers } from 'next/headers';

const COOKIEBEAM_LOADER =
  'https://cdn.cookiebeam.com/banner/PUBLIC_BANNER_ID/default/loader.js';

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const nonce = (await headers()).get('x-nonce') ?? undefined;

  return (
    <html lang="en">
      <head>
        {/* eslint-disable-next-line @next/next/no-sync-scripts */}
        <script src={COOKIEBEAM_LOADER} nonce={nonce} suppressHydrationWarning />
      </head>
      <body>{children}</body>
    </html>
  );
}

suppressHydrationWarning is needed because browsers hide the nonce attribute once the page has been parsed, so the value React sees on the client differs from the one the server rendered. Reading headers() makes the layout render per request, which a per-request nonce needs anyway. Without a nonce, use the first example and the layout can stay static.

Pair the nonce with 'strict-dynamic' so the scripts CookieBeam adds are trusted too. See Content security policy.

Route changes

Navigation with next/link or router.push doesn't reload the document, so the loader runs once and the runtime, banner and consent stay in place across routes. Keep the tag in the root layout only: not in a nested layout, a page, or a template that re-renders on navigation.

Server Components can't read consent: the choice lives in the visitor's browser and changes there. Read it in a Client Component with the hasConsent and onConsentChange helpers from Read consent in your code, wrapped in a hook:

// app/use-consent.ts
'use client';

import { useEffect, useState } from 'react';
import { hasConsent, onConsentChange } from './consent';

export function useConsent(category: string): boolean {
  // false on the server and the first client render, so hydration matches.
  const [granted, setGranted] = useState(false);

  useEffect(() => {
    const update = () => setGranted(hasConsent(category));
    update();
    return onConsentChange(update);
  }, [category]);

  return granted;
}
// app/require-consent.tsx
'use client';

import { useConsent } from './use-consent';

export function RequireConsent({
  category,
  children,
}: {
  category: string;
  children: React.ReactNode;
}) {
  return useConsent(category) ? <>{children}</> : null;
}
// in any layout or page
<RequireConsent category="marketing">
  <VideoEmbed />
</RequireConsent>

To keep a vendor's code out of the bundle until consent, load the gated component with next/dynamic and ssr: false inside a Client Component, and render it only inside RequireConsent.

For the cookie settings link, use a plain button with data-cb="show-preferencesModal", not next/link. See Add a cookie settings link.

Check the installation

  1. Run a production build (next build and next start) or check the deployed site. View the page source and confirm the loader appears in <head> before any tracker or third-party script you added, with no async or defer. Next.js's own /_next/static/chunks/ scripts may appear before it. Those are application code, not trackers, so that's fine. Module-level tracker code in Client Components runs at import time, before consent. A useEffect delays it past hydration but doesn't check consent; guard it with CookieBeam.acceptedCategory('analytics') or use the RequireConsent wrapper above.
  2. Add localhost or your preview hostname under Banner domains and publish, or the banner won't appear there.
  3. With a CSP, the loader tag in the page source carries a nonce attribute, and the console shows no CSP error.
  4. Navigate with links between routes. The Network panel shows a single loader.js request.
  5. The console shows no hydration warning about the CookieBeam tag.
  6. Reject, then accept, a category and confirm gated components follow the choice without a reload.

Then work through Verify your installation.