DEV Community

Cover image for Implementing Cookie Consent in React and Next.js: Script Loading, CMPs and Consent Mode v2
IntelligenceX
IntelligenceX

Posted on

Implementing Cookie Consent in React and Next.js: Script Loading, CMPs and Consent Mode v2

Adding a cookie banner to a React or Next.js application looks simple.

But the difficult part is not rendering the banner. It is ensuring that configured third-party scripts do not execute before the required consent is obtained.

A typical SaaS website might load:

  • Google Analytics.
  • Google Tag Manager.
  • Meta Pixel.
  • PostHog.
  • Intercom or another chat widget.
  • Embedded video services.
  • Marketing automation scripts.

A CMP needs to coordinate the visitor's choices with these services.

Here is what developers should understand before implementing cookie consent.

1. Choose a CMP with framework support

Some providers offer a generic JavaScript snippet. Others provide framework-specific SDKs.

CMP Relevant developer documentation
CookieYes React SDK, Next.js SDK and JavaScript core
Cookiebot Next.js App Router and Pages Router
Usercentrics JavaScript integration and Next.js guidance
ConsentX Hosted CMP and website integration options

Sources: CookieYes developer docs, Cookiebot Next.js guide, Usercentrics Next.js guide.

2. Next.js App Router: Install the CMP in the root layout

For a provider that requires early loading, the root layout is usually the right place.

Cookiebot's documented example uses next/script with beforeInteractive:

// app/layout.tsx

import Script from 'next/script';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <Script
          id="cookiebot"
          src="https://consent.cookiebot.com/uc.js"
          data-cbid="YOUR-DOMAIN-ID"
          data-blockingmode="auto"
          strategy="beforeInteractive"
        />

        {children}
      </body>
    </html>
  );
}
Enter fullscreen mode Exit fullscreen mode

Important points:

  • Use the actual domain ID from your CMP account.
  • Keep the script in the root layout.
  • Do not install it again in nested layouts.
  • Follow the provider's instructions for third-party scripts.

Cookiebot specifically documents that its autoblocker should be initialised before scripts that it needs to block.

3. Next.js Pages Router

For the Pages Router, Cookiebot documents a different implementation using _document.tsx.

// pages/_document.tsx

import {
  Html,
  Head,
  Main,
  NextScript
} from 'next/document';

export default function Document() {
  return (
    <Html lang="en">
      <Head>
        <script
          id="Cookiebot"
          src="https://consent.cookiebot.com/uc.js"
          data-cbid="YOUR-DOMAIN-ID"
          data-blockingmode="auto"
          type="text/javascript"
        />
      </Head>

      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}
Enter fullscreen mode Exit fullscreen mode

This is provider-specific. Do not copy the Cookiebot implementation unchanged for another CMP.

4. Why useEffect can be a problem

Consider this implementation:

useEffect(() => {
  const script = document.createElement('script');

  script.src = 'YOUR-CMP-SCRIPT-URL';

  document.head.appendChild(script);
}, []);
Enter fullscreen mode Exit fullscreen mode

This runs after the component mounts.

If analytics or advertising scripts have already executed, the CMP may not be able to prevent their earlier activity.

For early consent control, use the provider's recommended document-level integration.

React effects are useful for client-side interactions, not as a universal replacement for early script initialisation.

5. Google Consent Mode v2

Google Consent Mode allows supported Google tags to adjust behaviour according to consent signals.

The four key parameters for Consent Mode v2 are:

{
  ad_storage: 'denied',
  analytics_storage: 'denied',
  ad_user_data: 'denied',
  ad_personalization: 'denied'
}
Enter fullscreen mode Exit fullscreen mode

A custom gtag.js implementation can set default states before measurement commands:

window.dataLayer = window.dataLayer || [];

function gtag() {
  dataLayer.push(arguments);
}

gtag('consent', 'default', {
  ad_storage: 'denied',
  analytics_storage: 'denied',
  ad_user_data: 'denied',
  ad_personalization: 'denied'
});
Enter fullscreen mode Exit fullscreen mode

When the visitor makes a choice, update the consent state:

gtag('consent', 'update', {
  ad_storage: 'granted',
  analytics_storage: 'granted',
  ad_user_data: 'granted',
  ad_personalization: 'granted'
});
Enter fullscreen mode Exit fullscreen mode

The example values are illustrative. Your implementation must map the visitor's actual choices to the appropriate consent types.

If a CMP already manages these updates, do not duplicate them with a separate custom handler.

Official reference: Google Consent Mode setup.

6. Basic vs Advanced Consent Mode

Basic: Google tags remain blocked until the visitor interacts with the banner. No Google tag data is sent before consent.

Advanced: Google tags load with default consent states and can send cookieless measurement pings when the relevant storage consent is denied.

Advanced mode does not mean every third-party script can run without restriction.

7. Test the implementation

Use a clean browser profile and inspect the Network panel.

Test Expected result
Initial load CMP initialises correctly
Reject analytics Configured analytics scripts remain blocked
Reject advertising Configured advertising scripts remain blocked
Accept analytics only Only the relevant category activates
Withdraw Updated consent is applied
Reload Stored preference is handled correctly
Client navigation Consent state remains consistent

Also inspect:

  • Cookies.
  • Local storage.
  • Session storage.
  • Third-party network requests.
  • Tag Manager preview.
  • Console errors.

8. Common mistakes

  1. Loading the CMP after tracking scripts.
  2. Adding the CMP to multiple layouts.
  3. Assuming all scripts are automatically blocked.
  4. Ignoring client-side route changes.
  5. Accessing browser storage during server rendering.
  6. Sending duplicate Google consent updates.
  7. Testing only the banner's visual appearance.

Conclusion

React and Next.js cookie consent requires careful control over script loading and consent state.

CookieYes offers framework-specific SDKs, Cookiebot documents App Router and Pages Router installations, and Usercentrics provides script-based Next.js guidance. ConsentX is another platform worth evaluating for hosted consent management and evidence workflows.

The implementation should be tested at the network-request level, not just by checking whether the banner appears.

Top comments (0)