React / Next.js
CookieBoss works with any React or Next.js application. The consent script is a vanilla JavaScript file — no React-specific package needed.
Next.js (App Router)
Add the script to your root layout.tsx:
app/layout.tsx tsx
import Script from 'next/script';
export default function RootLayout({ children }) {
return (
<html lang="en">
<head>
<Script
src="https://cdn.cookieboss.io/scripts/YOUR_SITE_ID/consent.js"
strategy="beforeInteractive"
/>
</head>
<body>{children}</body>
</html>
);
} beforeInteractive is important
Using strategy="beforeInteractive" ensures the consent script loads before any other scripts, including Google Analytics. This is required for script blocking and Google Consent Mode to work correctly.
Next.js (Pages Router)
Add the script to _app.tsx or _document.tsx:
pages/_app.tsx tsx
import Script from 'next/script';
export default function App({ Component, pageProps }) {
return (
<>
<Script
src="https://cdn.cookieboss.io/scripts/YOUR_SITE_ID/consent.js"
strategy="beforeInteractive"
/>
<Component {...pageProps} />
</>
);
} Listening for consent changes
Use a useEffect hook to listen for the cookieboss:update event:
hooks/useCookieConsent.ts tsx
import { useState, useEffect } from 'react';
interface ConsentCategories {
necessary: true;
analytics: boolean;
marketing: boolean;
functional: boolean;
}
export function useCookieConsent() {
const [consent, setConsent] = useState<ConsentCategories | null>(null);
useEffect(() => {
// Check existing consent on mount
if (window.__cookieboss) {
setConsent(window.__cookieboss.getConsent());
}
// Listen for changes
const handler = (e: CustomEvent) => {
setConsent(e.detail.categories);
};
document.addEventListener('cookieboss:update', handler as EventListener);
return () => {
document.removeEventListener('cookieboss:update', handler as EventListener);
};
}, []);
return consent;
} Conditional rendering
Use the hook to conditionally render components:
tsx
import { useCookieConsent } from '@/hooks/useCookieConsent';
function AnalyticsWidget() {
const consent = useCookieConsent();
if (!consent?.analytics) {
return null; // Don't render until analytics consent is given
}
return <div>Analytics dashboard widget</div>;
} Opening the consent banner
Add a “Cookie Settings” button that re-opens the banner:
tsx
function CookieSettingsButton() {
return (
<button onClick={() => window.__cookieboss?.showBanner()}>
Cookie Settings
</button>
);
} TypeScript types
Add type declarations for window.__cookieboss:
types/cookieboss.d.ts typescript
interface CookieBossSDK {
config: Record<string, unknown>;
version: number;
getConsent(): {
necessary: true;
analytics: boolean;
marketing: boolean;
functional: boolean;
};
showBanner(): void;
acceptAll(): void;
rejectAll(): void;
}
declare global {
interface Window {
__cookieboss?: CookieBossSDK;
}
}