DEV Community

Cover image for Blocking Third-Party Scripts Before Consent in React and Next.js
IntelligenceX
IntelligenceX

Posted on

Blocking Third-Party Scripts Before Consent in React and Next.js

A cookie banner can be visible on screen while analytics, advertising pixels or other third-party JavaScript has already started running.

That is the implementation problem developers need to solve.

In a React or Next.js application, consent management should control script execution, not just the banner's appearance. This guide walks through a practical architecture for consent-aware script loading.

The problem: scripts can execute before the banner interaction

Typical third-party integrations include:

  • Google Analytics
  • Google Tag Manager
  • Meta Pixel
  • Microsoft Clarity
  • Chat widgets
  • Advertising and retargeting tags
  • Embedded video and social media content

A script may create cookies, access browser storage, initialise identifiers or send network requests. The exact behaviour depends on the service.

A banner does not automatically prevent these actions. If the script is imported or inserted independently, it may run before the visitor has made a choice.

Step 1: Build a script inventory

Before changing code, list every external service and its purpose.

Integration Purpose Consent category
GA4 Measurement Analytics
Meta Pixel Advertising Marketing
Clarity Behaviour analytics Analytics
Support chat Customer support Depends on functionality
Video embed External content Depends on implementation

Do not classify services only by their names. Review what they actually do, what information they access and the rules applicable to your visitors.

Also inspect local storage, session storage, pixels, iframe requests and scripts loaded indirectly by other scripts.

Step 2: Use consent as a dependency

A useful architecture is:

Visitor opens website
        |
        v
CMP initialises
        |
        v
Default consent is applied
        |
        v
Visitor makes a choice
        |
        v
Consent state is updated
        |
        +---- Analytics approved? ---- Yes --> Load analytics
        |
        +---- Marketing approved? ---- Yes --> Load marketing tags
        |
        +---- Neither approved? ------ Yes --> Keep them blocked
Enter fullscreen mode Exit fullscreen mode

The consent manager should be the source of truth. Avoid maintaining an unrelated boolean in multiple components that can become inconsistent with the visitor's saved preferences.

Step 3: Conditional loading in React

The following example demonstrates the basic loading pattern:

import { useEffect } from "react";

export function AnalyticsLoader({ analyticsConsent }) {
  useEffect(() => {
    if (!analyticsConsent) return;

    if (document.getElementById("analytics-script")) return;

    const script = document.createElement("script");
    script.id = "analytics-script";
    script.src = "https://analytics.example.com/sdk.js";
    script.async = true;

    document.head.appendChild(script);
  }, [analyticsConsent]);

  return null;
}
Enter fullscreen mode Exit fullscreen mode

The analyticsConsent prop should come from your CMP's documented consent API or a state layer synchronised with it.

This is a minimal example, not a complete production integration. It does not implement consent persistence, service-specific shutdown, event cleanup or withdrawal handling.

One more important detail: removing a script element does not undo JavaScript that has already executed. A production integration needs the provider's supported opt-out or shutdown mechanism.

Step 4: Next.js Script strategies

Next.js provides three commonly used script strategies:

Strategy Intended use
beforeInteractive Critical scripts needed before application code
afterInteractive Scripts loaded after hydration
lazyOnload Low-priority scripts loaded during browser idle time

Example CMP placement in the App Router:

import Script from "next/script";

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        {children}

        <Script
          id="cmp"
          src="https://cmp.example.com/site-id.js"
          strategy="beforeInteractive"
        />
      </body>
    </html>
  );
}
Enter fullscreen mode Exit fullscreen mode

Use the actual installation snippet supplied by your CMP. A consent manager may need early initialisation so it can control other services.

For an analytics integration, conditional rendering is more appropriate:

"use client";

import Script from "next/script";

export function Analytics({ allowed }) {
  if (!allowed) return null;

  return (
    <Script
      id="analytics"
      src="https://analytics.example.com/sdk.js"
      strategy="afterInteractive"
    />
  );
}
Enter fullscreen mode Exit fullscreen mode

Do not confuse script timing with consent enforcement. afterInteractive does not mean that a visitor has consented. It only describes when Next.js loads the script.

Step 5: Google Consent Mode is a separate layer

Google Consent Mode adjusts the behaviour of supported Google tags according to consent signals.

Its two main approaches are:

  • Basic: Google tags remain blocked until the visitor interacts with the banner. If consent is not granted, the tags do not load.
  • Advanced: Google tags load with configured default consent states. When consent is denied, they may send cookieless pings.

Relevant Consent Mode v2 signals include:

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

The default state must be configured before the relevant Google tags process measurement commands. Update the state when the visitor makes a choice.

This code is an illustrative Google tag example. A Google Tag Manager implementation should use the appropriate consent APIs and templates.

Most importantly, Consent Mode is not a general-purpose blocker for Meta Pixel, chat tools or arbitrary third-party scripts.

Step 6: CMP integration options

You can implement script control manually, use CMP-supported automatic blocking, or combine both.

Examples of documented approaches include:

  • Cookiebot: automatic blocking and manual markup for scripts.
  • Usercentrics: auto-blocking and manual implementation options.
  • CookieYes: Next.js installation guidance and developer integrations for consent-based loading of supported tools.

For ConsentX, use the current site-specific installation code and verify the exact script-blocking functionality available for your account and plan. Do not assume that an example from another CMP is interchangeable with ConsentX.

Useful links:

Step 7: Test the implementation

A working banner is not proof of working script blocking.

Test these scenarios in a clean browser session:

No choice yet

  • Load the page.
  • Do not interact with the banner.
  • Inspect Network requests.
  • Inspect cookies and browser storage.
  • Check that non-essential services remain blocked where required.

Analytics accepted

  • Accept analytics only.
  • Confirm analytics loads.
  • Confirm marketing tags remain blocked.

Marketing rejected

  • Reject marketing.
  • Reload the page.
  • Verify that marketing requests do not appear.

Consent withdrawn

  • Grant consent.
  • Withdraw it in the preference centre.
  • Verify that future events stop and the service's supported opt-out behaviour runs.

Also test navigation between routes, page refreshes and returning visits.

Common mistakes

  1. Loading analytics directly in the root layout without a consent check.
  2. Assuming afterInteractive is consent enforcement.
  3. Treating Google Consent Mode as a universal blocker.
  4. Testing only cookies while ignoring network requests.
  5. Removing a script element and assuming that all processing has stopped.
  6. Failing to retest after adding a new plugin or integration.

Final architecture checklist

  • [ ] All external scripts inventoried.
  • [ ] Services assigned to appropriate purposes.
  • [ ] CMP initialises early enough for its blocking method.
  • [ ] Default consent is applied correctly.
  • [ ] Scripts load only after the relevant permission.
  • [ ] Google Consent Mode is configured separately where needed.
  • [ ] Consent withdrawal is handled.
  • [ ] Network requests and storage are tested.
  • [ ] New integrations are included in regression testing.

The main principle is straightforward: do not let a non-essential service initialise before the consent condition that applies to it has been satisfied.

A CMP can simplify this process, but the final implementation still needs framework-aware integration and real browser testing.

References:

Top comments (0)