Cookie-Einwilligung für Single-Page-Apps (React, Next.js, Vue)
Wie Sie ein Einwilligungsbanner in SPA-Frameworks integrieren — asynchrones Laden von Skripten, einwilligungsbewusstes Rendering und Event-Handling.
Veröffentlicht am
Single-page apps make cookie consent harder than it should be. The basic problem: your visitor lands on the site, the React (or Vue, or Svelte) bundle hydrates, the page re-renders, and somewhere in that sequence you need to inject a banner, hold back third-party scripts, persist the choice, and not break hydration. None of those steps are individually hard. Doing them in the right order without race conditions is the trick.
This guide covers the patterns that actually work for React, Next.js, and Vue. I'll focus on Next.js App Router because that's where I see the most active questions, but the principles transfer.
The hydration problem
With server-side rendering, the server renders the page without knowing the visitor's consent state (consent lives in the visitor's localStorage, which the server can't see). The client then hydrates, reads localStorage, and now has a different consent state than the server assumed.
If your banner's visibility depends on consent state, you get a hydration mismatch warning in the console. The page renders with the banner visible (server default), React sees that the visitor already has consent stored, hides the banner, and React complains about the markup mismatch.
The fix is to render the banner after hydration, not during SSR. The pattern looks like:
'use client';
import { useState, useEffect } from 'react';
export default function CookieBanner() {
const [mounted, setMounted] = useState(false);
const [consent, setConsent] = useState(null);
useEffect(() => {
setMounted(true);
const stored = localStorage.getItem('ct_consent');
setConsent(stored ? JSON.parse(stored) : null);
}, []);
// Don't render anything on the server or first client render.
// This avoids hydration mismatch and means the banner won't
// flicker during the initial paint.
if (!mounted) return null;
if (consent) return null;
return <BannerUI onAccept={...} onReject={...} />;
}The double-state pattern (mounted + consent) is the trick. mounted stays false during SSR and the initial client render, so server and client agree on the markup. Once the effect runs, the banner renders if needed.
Consent-aware third-party scripts in Next.js
For third-party scripts, the App Router gives you next/script with a strategy="afterInteractive" mode that loads scripts after hydration. Combined with consent state, you only mount the Script when consent is granted:
'use client';
import Script from 'next/script';
import { useConsent } from '@/hooks/useConsent';
export default function AnalyticsScripts() {
const consent = useConsent();
if (!consent.statistics) return null;
return (
<>
<Script
src="https://www.googletagmanager.com/gtag/js?id=G-XXXXX"
strategy="afterInteractive"
/>
<Script id="ga-init" strategy="afterInteractive">
{`window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXX');`}
</Script>
</>
);
}When consent is granted, React mounts the Script components and Next.js loads them. When consent is withdrawn, React unmounts them. The scripts themselves are already loaded — you can't un-load them — but the side effects (cookies set, identifiers stored) need to be cleaned up separately. See below.
The useConsent hook pattern
Your consent state needs to be reactive: when the visitor accepts in the banner, every component that depends on consent needs to re-render. A custom hook subscribed to the CMP's event API is the cleanest pattern:
'use client';
import { useEffect, useState } from 'react';
const PRE_CONSENT = {
necessary: true,
preferences: false,
statistics: false,
marketing: false,
};
export function useConsent() {
const [consent, setConsent] = useState(PRE_CONSENT);
useEffect(() => {
if (typeof window === 'undefined') return;
// Seed from CMP if already decided
const seed = window.ConsentTrustee?.getConsent?.();
if (seed) setConsent({ ...PRE_CONSENT, ...seed });
const onChange = (e) => {
if (e.detail) setConsent({ ...PRE_CONSENT, ...e.detail });
};
window.addEventListener('ct:consentChanged', onChange);
return () => window.removeEventListener('ct:consentChanged', onChange);
}, []);
return consent;
}The PRE_CONSENT defaults matter: until the CMP confirms, treat everything as denied (except necessary). Don't assume granted. The cost of incorrectly denying is some lost analytics signal. The cost of incorrectly granting is a GDPR fine.
The clean-up on withdrawal
When a visitor withdraws consent mid-session, you need to:
- Stop firing new tracking events.
- Tell the existing scripts to stop. For GA, this is the
ga-disable-G-XXXXX = truewindow flag. - Purge cookies that the scripts already set.
Unmounting the Script component covers (1). The flag covers (2). For (3), iterate the cookies you can see and expire each one. The CMP's withdrawal handler should do this automatically; if you're rolling your own, the pattern is:
function purgeGaCookies() {
const host = window.location.hostname;
const parent = host.split('.').slice(-2).join('.');
const names = ['_ga', '_gid', '_gat', '_ga_*'];
for (const name of names) {
document.cookie = `${name}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
document.cookie = `${name}=; path=/; domain=${host}; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
document.cookie = `${name}=; path=/; domain=.${parent}; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
}
}Vue 3 specifics
Vue's Composition API gives you the equivalent pattern with composables:
import { ref, onMounted, onUnmounted } from 'vue';
export function useConsent() {
const consent = ref({ necessary: true, statistics: false, marketing: false });
onMounted(() => {
const seed = window.ConsentTrustee?.getConsent?.();
if (seed) consent.value = { ...consent.value, ...seed };
const onChange = (e) => {
if (e.detail) consent.value = { ...consent.value, ...e.detail };
};
window.addEventListener('ct:consentChanged', onChange);
onUnmounted(() => window.removeEventListener('ct:consentChanged', onChange));
});
return consent;
}For Nuxt 3, the same pattern works inside a composable file. Use process.client to guard against SSR contexts, or wrap the composable usage in <ClientOnly>.
Route-change tracking in SPAs
Traditional analytics fires a pageview on the initial page load. SPAs change route without a full page reload, so your analytics needs to fire pageviews on route changes too.
In Next.js App Router:
'use client';
import { usePathname } from 'next/navigation';
import { useEffect } from 'react';
export function usePageviewTracking() {
const pathname = usePathname();
const consent = useConsent();
useEffect(() => {
if (!consent.statistics) return;
if (typeof window.gtag !== 'function') return;
window.gtag('event', 'page_view', { page_path: pathname });
}, [pathname, consent.statistics]);
}Don't depend on useSearchParams for this if you can avoid it — it forces a Suspense boundary in the App Router. Use usePathname only.
What I'd read next
For the underlying script-blocking technique, How to Block Third-Party Scripts. For the Google Consent Mode signals you'll be wiring, Google Consent Mode v2. And for the broader CMP architecture this fits into, What Is a CMP.