WordPressNext.jscookie consentdevelopers
Cookie Consent in WordPress and Next.js: Implementation Guide for Developers

Cookie Consent in WordPress and Next.js: Implementation Guide for Developers

CS
ConsentScope Team
June 14, 202621 min read

Cookie consent is no longer a marketing checkbox. For developers building on WordPress or Next.js, it is a first-class engineering requirement. A single analytics script loaded before the user clicks "Accept" can turn a routine deployment into a GDPR complaint. This guide walks through cookie consent implementation for both platforms with real code, compares the practical challenges, and shows how to verify the result with ConsentScope.

Why developers still get cookie consent wrong

Most cookie violations are not caused by missing banners. They are caused by scripts that fire too early, tags loaded through Google Tag Manager before consent is stored, or localStorage writes that happen before the user interacts with the banner. The legal expectation is simple: no non-essential identifiers should be placed before a positive consent action. The technical reality is much messier.

The same mistakes appear on both WordPress and Next.js sites, but the fixes differ because of how each platform handles markup, JavaScript execution order, and third-party script loading.

Cookie consent in WordPress

Choose a consent-first plugin or build your own banner

WordPress sites typically rely on plugins. The most reliable ones let you block scripts by category and only load analytics or marketing tags after consent is recorded. If you are building a custom theme or plugin, enqueue consent-gated scripts manually.

Here is an example of enqueuing a conditional analytics script only when the user has given analytics consent. The consent preference is stored in a cookie or localStorage value by your banner.

<?php
  function consentscope_enqueue_conditional_scripts() {
      $consent = isset($_COOKIE['consent_scope']) ? sanitize_text_field($_COOKIE['consent_scope']) : '';
      $preferences = json_decode(stripslashes($consent), true);
  
      if (!empty($preferences['analytics']) && $preferences['analytics'] === true) {
          wp_enqueue_script(
              'analytics-consented',
              'https://analytics.example.com/script.js',
              [],
              '1.0.0',
              true
          );
      }
  }
  add_action('wp_enqueue_scripts', 'consentscope_enqueue_conditional_scripts');
  ?>

This server-side check works for the initial page load, but it only covers scripts you control through PHP. Many WordPress plugins inject scripts through hooks or directly into the template, so a frontend gate is also necessary.

Add a JavaScript gate for third-party scripts

Use a small helper that checks the stored consent before executing marketing or analytics code. Keep the helper in your theme or plugin and call it before any tracker initialisation.

function hasConsent(category) {
    try {
      const prefs = JSON.parse(localStorage.getItem('consent_scope') || '{}');
      return prefs[category] === true;
    } catch (e) {
      return false;
    }
  }
  
  if (hasConsent('analytics')) {
    // initialise analytics
  }
  
  if (hasConsent('marketing')) {
    // initialise retargeting pixels
  }

Make sure this helper is loaded synchronously in the document head so it is available before any third-party plugin scripts run. Otherwise a plugin lower in the page may win the race and set a cookie first.

Cookie consent in Next.js

Use the Script component with a consent gate

Next.js gives you more control than WordPress over how scripts are loaded. The built-in Script component supports strategies like beforeInteractive, afterInteractive, and lazyOnload. For consent-critical scripts you should load them conditionally based on stored consent rather than relying on the default behaviour.

The safest pattern is to keep tracking scripts out of the initial HTML entirely, then render them only after the user has consented. This avoids both server-side leakage and hydration mismatches.

// components/ConsentGatedScript.tsx
  'use client';
  
  import Script from 'next/script';
  import { useConsent } from '@/hooks/useConsent';
  
  export default function ConsentGatedScript({ category, src }) {
    const { hasConsent, isReady } = useConsent();
  
    if (!isReady || !hasConsent(category)) {
      return null;
    }
  
    return (
      <Script
        src={src}
        strategy="lazyOnload"
        onLoad={() => console.log('Consent-gated script loaded:', src)}
      />
    );
  }

The corresponding hook reads the consent record from localStorage and returns a stable state before any gated scripts are rendered.

// hooks/useConsent.ts
  'use client';
  
  import { useEffect, useState } from 'react';
  
  export function useConsent() {
    const [prefs, setPrefs] = useState({});
    const [isReady, setIsReady] = useState(false);
  
    useEffect(() => {
      try {
        const stored = localStorage.getItem('consent_scope');
        setPrefs(stored ? JSON.parse(stored) : {});
      } catch (e) {
        setPrefs({});
      }
      setIsReady(true);
    }, []);
  
    const hasConsent = (category) => prefs[category] === true;
  
    return { hasConsent, isReady, prefs };
  }

Respect prior consent on every route

Next.js App Router navigations do not perform a full page reload. If a user has already given consent, your gated scripts should remain active across route changes. Store consent server-agnostically and read it in a layout or provider that wraps every route.

// app/layout.tsx
  import { ConsentProvider } from '@/components/ConsentProvider';
  
  export default function RootLayout({ children }) {
    return (
      <html lang="en">
        <body>
          <ConsentProvider>
            {children}
          </ConsentProvider>
        </body>
      </html>
    );
  }

WordPress vs Next.js: consent implementation comparison

Both platforms can be made compliant, but the path differs. WordPress is plugin-heavy and relies on PHP hooks, while Next.js gives you component-level control at the cost of writing more custom code.

AspectWordPressNext.js
Script loading controlPHP enqueue + plugin filtersScript component + conditional rendering
Initial page loadServer can block scripts based on cookieScripts excluded from SSR to avoid leakage
Third-party pluginsRisk of scripts loaded before consentFull control if you manage all scripts
Storage monitoringRequires custom JS or pluginCustom hook or middleware
Route changesFull page reload resets gate naturallyClient navigation requires persistent provider
Best fit forContent sites and agenciesSaaS and custom applications

Common edge cases to handle

  • A user rejects consent but a script still loads because it was cached by a page optimiser.
  • Google Tag Manager fires tags before the consent variable is updated.
  • An embedded video or social widget sets cookies through an iframe before the banner is shown.
  • localStorage or sessionStorage is used to store tracking identifiers even when cookies are blocked.
  • Consent preferences are lost across subdomains because the storage key is not shared.

Each of these edge cases is a real violation we have seen in production. They are easy to miss in manual QA because they often require inspecting storage and network timing at the exact moment the page loads.

Verify your implementation with ConsentScope

After you implement your banner and gated scripts, the next step is verification. ConsentScope is a Chrome extension that monitors cookies, localStorage, sessionStorage, and third-party scripts before and after the user gives consent. It flags violations such as analytics cookies set before acceptance and third-party scripts loaded outside the consent gate.

Install the free extension, open your WordPress or Next.js site in a fresh tab, and leave the banner untouched. ConsentScope will show you exactly which identifiers were written before consent. After you accept, it compares the before and after states so you can confirm your gating logic works as intended.

Test your cookie consent setup today

Install ConsentScope for free and verify that no cookies or third-party scripts fire before your users consent. Upgrade to Pro for PDF audit reports and scan history.

Get ConsentScope Free

Frequently asked questions

Do I need a cookie consent banner for a WordPress site without analytics?

If your site only uses strictly necessary cookies, such as login sessions or load balancers, you may not need a banner under GDPR. However, most WordPress sites use comment cookies, embedded videos, social buttons, or analytics, which generally require consent. Verify your actual cookies rather than assuming.

Can I load Google Tag Manager before consent in Next.js?

You can load the GTM container script before consent, but you must configure GTM to prevent tags from firing until the consent state is set. A safer approach is to load GTM itself only after consent is given, then initialise the data layer with default consent values.

How do I keep consent state across subdomains?

Store consent in a first-party cookie with the Domain attribute set to your root domain, for example .example.com. In Next.js middleware or in your WordPress PHP layer you can read this cookie and apply the same server-side gating on every subdomain.

What should I do if a WordPress plugin ignores my consent banner?

Use a script-blocking plugin that supports pattern-based blocking, or dequeue the offending plugin script until consent is granted. If the plugin provides no hooks, wrap its output in a placeholder that is only replaced after consent. Always test the result with a tool that watches storage and network activity.

Is ConsentScope useful after implementation is complete?

Yes. Websites change over time. New plugins, A/B tests, and marketing tags can reintroduce violations. ConsentScope gives you a quick way to re-audit after every deployment and to document compliance with scan history and PDF reports in the Pro version.

CS

ConsentScope Team

Verified author

Privacy Engineers & Chrome Extension Developers

We build tools that help developers, agencies and privacy advocates detect GDPR cookie violations automatically. Our team analyzes consent banners, cookie behavior and third-party scripts across thousands of websites every month.

Published: June 14, 2026Updated: June 14, 2026