Platform guides
Cookie consent in React and Next.js: a practical developer guide
Load your consent script once in the root layout, render third-party scripts only after the visitor allows their category, and give visitors a way to change their mind. Here is how to do each step in the App Router, the Pages Router and plain React.
- Plain English
- Written for website owners
- Free to read
On this page
To add cookie consent to a React or Next.js app, load the consent manager's script once, as early as possible, in the HTML shell or root layout. Then render each third-party script, pixel or embed only after the visitor has allowed its category, and update the page when they change their mind. A banner on its own doesn't stop anything from loading, and in a component-based app the gating has to happen in your components.
This guide uses PrivacyQuick's snippet and JavaScript API in the examples, but the structure applies to most consent tools that expose a "has the visitor allowed X?" check and a change event.
What consent means in a React app
Under the ePrivacy Directive Art. 5(3), storing or reading anything on a visitor's device that isn't strictly necessary needs prior consent in the EU and UK. In a React codebase, that rule turns into three jobs:
- Load the consent manager first. It must run before anything that sets non-essential cookies, so it belongs in the document head, not inside a lazily rendered component.
- Gate everything non-essential. Analytics, ad pixels, chat widgets, video embeds and A/B testing tools should not mount until their category is allowed.
- React to changes. A visitor can accept on one page and withdraw later. Your components need to notice both.
The common mistake is calling an analytics init() inside a useEffect in the root component. That effect runs on every first render, before the visitor has seen the banner. If you aren't sure what your app loads today, follow the steps in checking cookies in Chrome DevTools or run a free cookie scan before you change anything.
Load the consent script in the App Router root layout
The Next.js documentation lists cookie consent managers as an example use for the beforeInteractive strategy of next/script. Scripts with this strategy are added to the initial HTML from the server, fetched before any Next.js code and always placed in the document head. They must live in a root layout, such as app/layout.tsx.
// app/layout.tsx
import Script from 'next/script'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
{children}
<Script
src="https://cdn.privacyquick.com/v1/privacy.js"
data-site-id="pq_xxxxxxxxxx"
strategy="beforeInteractive"
/>
</body>
</html>
)
}
A plain tag in the root layout's head works too, and some teams prefer it because nothing is transformed:
<html lang="en">
<head>
<script src="https://cdn.privacyquick.com/v1/privacy.js" data-site-id="pq_xxxxxxxxxx" async></script>
</head>
<body>{children}</body>
</html>
Either way, open the page with View Source (not the Elements panel) and check that the script tag and its data-site-id attribute appear in the server HTML. Scripts in the root layout run once per document load. Client-side navigations don't run them again, which is what you want: the consent manager keeps working across routes.
Pages Router and plain React
In the Pages Router, put the tag in pages/_document.tsx, which renders the HTML shell once on the server:
// pages/_document.tsx
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html lang="en">
<Head>
<script src="https://cdn.privacyquick.com/v1/privacy.js" data-site-id="pq_xxxxxxxxxx" async />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
In a client-only React app built with Vite or a similar tool, paste the snippet into index.html, high in the <head> and before any analytics tags. Don't inject the consent script from a component: that delays it until React has rendered, and anything loaded earlier escapes it.
Gate third-party scripts with a consent hook
Next, give your components a way to ask whether a category is allowed. This hook reads the current state when it mounts and listens for the pq:consent DOM event, which fires on document each time the visitor makes a choice. Because it's a plain DOM event, you can listen for it even if the consent script hasn't finished loading.
// app/consent/use-consent.ts
'use client'
import { useEffect, useState } from 'react'
export type ConsentCategory = 'analytics' | 'functional' | 'marketing'
type ConsentDetail = { categories: string[]; action: string }
declare global {
interface Window {
PrivacyQuick?: {
open(): void
has(category: string): boolean
}
}
}
export function useConsent(category: ConsentCategory): boolean {
// Start with false on the server and on the first client render,
// so the HTML matches and nothing loads before we have checked.
const [allowed, setAllowed] = useState(false)
useEffect(() => {
const check = () => {
const ok = window.PrivacyQuick?.has(category) ?? false
setAllowed(ok)
return ok
}
const onChoice = (e: Event) => {
const { categories } = (e as CustomEvent<ConsentDetail>).detail
setAllowed(categories.includes(category))
}
check()
// Re-check for a few seconds while the banner's settings load.
let tries = 0
const timer = window.setInterval(() => {
if (check() || ++tries >= 10) window.clearInterval(timer)
}, 500)
document.addEventListener('pq:consent', onChoice)
return () => {
window.clearInterval(timer)
document.removeEventListener('pq:consent', onChoice)
}
}, [category])
return allowed
}
Starting from false matters. The server can't know what the visitor chose in the browser, so the first render must assume "not allowed". If you initialized the state from window, the server and client HTML would differ and React would report a hydration mismatch.
The short re-check loop exists because of regional rules. For a visitor in an opt-out or notice region who hasn't chosen yet, categories switch on when the site settings arrive, and no change event fires for that moment. Polling has() for a few seconds after mount catches it. In an opt-in region, has() stays false until the visitor acts, and the event handles the rest.
Now render the third-party script only when it's allowed:
// app/consent/analytics.tsx
'use client'
import Script from 'next/script'
import { useEffect, useRef } from 'react'
import { useConsent } from './use-consent'
export function Analytics() {
const allowed = useConsent('analytics')
const loaded = useRef(false)
useEffect(() => {
if (allowed) loaded.current = true
// The script already ran on this page and can't be unloaded.
else if (loaded.current) window.location.reload()
}, [allowed])
if (!allowed) return null
return <Script src="https://analytics.example.com/script.js" strategy="afterInteractive" />
}
Add <Analytics /> to your root layout. It renders nothing until the visitor allows analytics.
Why the reload?
Unmounting a <Script> component doesn't undo a script that already ran. Its cookies are still set and its event listeners are still attached. If a visitor withdraws consent after the script loaded, the cleanest way to stop it is a full reload, after which the hook returns false and the script never loads. PrivacyQuick reloads the page on its own when a visitor withdraws a category whose tagged scripts it released. Scripts your React code loaded are your responsibility, which is what the effect above handles. Some vendors also offer an opt-out call you can use instead, so check their documentation.
Click-to-load embeds
Video players, maps and social posts set cookies as soon as their iframe loads. Render a placeholder until the visitor allows the category you assigned the embed to, often marketing for YouTube:
// app/consent/youtube.tsx
'use client'
import { useConsent } from './use-consent'
export function YouTube({ id, title }: { id: string; title: string }) {
const allowed = useConsent('marketing')
if (!allowed) {
return (
<div className="video-placeholder">
<p>This video is hosted by YouTube, which uses cookies when it plays.</p>
<button type="button" onClick={() => window.PrivacyQuick?.open()}>
Change cookie settings to watch
</button>
</div>
)
}
return (
<iframe
src={`https://www.youtube-nocookie.com/embed/${id}`}
title={title}
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
/>
)
}
The button opens the preferences panel rather than accepting everything. Visitors who only want the video can switch on one category. The youtube-nocookie.com domain reduces tracking but still uses browser storage, as explained in the guide to YouTube embeds and cookies.
Google tags and Consent Mode in Next.js
Google tags are a special case because Google Consent Mode v2 lets them load before consent in a restricted state. PrivacyQuick sets every Consent Mode signal to denied before other tags run and sends an update when the visitor chooses. That leaves you two options:
- Basic implementation: wrap the Google tag in the consent hook, like the analytics example above, so nothing from Google loads before consent.
- Advanced implementation: load the tag for everyone, for example with
<GoogleTagManager gtmId="GTM-XXXXXXX" />from@next/third-parties/google, and let Consent Mode keep it cookieless until the visitor agrees.
The trade-offs are covered in Consent Mode basic vs advanced. With the advanced approach, the consent script has to set its default before the Google tag loads, so check the order with Google Tag Assistant after deploying. The Consent Mode setup docs show the signals PrivacyQuick sends for each category, and the Google Consent Mode v2 explainer covers the four signals in detail.
Reading consent on the server
Sometimes you want the server to decide what to render, for example to skip a placeholder flash for visitors who have already allowed embeds. PrivacyQuick stores the choice in a first-party cookie called pq_consent, which Server Components can read:
// app/consent/server.ts
import { cookies } from 'next/headers'
export async function allowedCategories(): Promise<string[]> {
const raw = (await cookies()).get('pq_consent')?.value
if (!raw) return ['necessary']
const decoded = raw.includes('%') ? decodeURIComponent(raw) : raw
const c = new URLSearchParams(decoded).get('c')
return c ? c.split('.') : ['necessary']
}
Three caveats apply. In current Next.js versions cookies() is async and reading it makes the route render dynamically, so don't call it in pages you want statically generated. A missing cookie means the visitor hasn't chosen, so treat it as "necessary only" unless you know they're in an opt-out region. And visitors can edit their own cookies, so use the value to respect their choice, not as proof of consent. The consent log is the record.
A "Cookie settings" link
Withdrawing consent should be as easy as giving it (GDPR Art. 7(3)). Put a link in your footer that reopens the preferences panel:
// app/consent/cookie-settings-button.tsx
'use client'
export function CookieSettingsButton() {
return (
<button type="button" onClick={() => window.PrivacyQuick?.open()}>
Cookie settings
</button>
)
}
The optional chaining means the button does nothing harmful if an ad blocker stopped the consent script. PrivacyQuick also shows a floating cookie button by default, but a footer link is easier to find for many visitors.
Testing checklist
Test a production build (next build then next start), because development mode renders effects twice and can hide or create timing issues.
- Open the site in a private window. The banner appears and the Network tab shows no requests to analytics, ad or embed hosts.
- Click Reject all. Navigate between several routes. Nothing new loads, and the Application tab shows no new non-essential cookies.
- Open the preferences panel from your footer link and allow analytics. The analytics script loads without a page reload.
- Withdraw analytics. The page reloads and the script no longer loads.
- Reload and check that placeholders and embeds match the stored choice, with no hydration warnings in the console.
For a wider view of the techniques behind this, read how to block cookies and scripts until consent.
Using Vue instead? See cookie consent in Vue and Nuxt.
Next steps
- List every third-party script, pixel and embed in your app and assign each to a category.
- Add the consent script to the root layout or
_document, then confirm it's in the server HTML. - Replace direct
init()calls in effects with components gated byuseConsent. - Decide on basic or advanced Consent Mode for Google tags.
- Add a footer "Cookie settings" link and run the checklist above.
If you want a banner that already handles regional rules, Consent Mode and a consent log, PrivacyQuick's snippet is under 5 KB gzipped and its JavaScript API is the one used in the examples above. You can start on the free plan and test it on a preview deployment first.
Frequently asked questions
Should the consent script use next/script or a plain script tag?
Either works. next/script with strategy="beforeInteractive" is the documented way to load a consent manager early in the App Router, and a plain async script tag in the root layout's head is a simple alternative. Whichever you use, view the page source to confirm the tag and its data attributes are in the initial HTML.
Does a single-page app need to show the banner on every route change?
No. The consent script is loaded once per full page load and keeps running across client-side navigations. The visitor's choice is stored in a cookie, so the banner only reappears when they haven't chosen yet or when you publish a new banner version.
Can I use React context instead of a hook for consent?
Yes. A context provider that holds the allowed categories and subscribes to consent changes once at the top of the tree works well in larger apps. The hook in this guide is the same logic without the provider, which is enough when only a few components need it.
Do React Server Components change how consent works?
Server Components can read the consent cookie through cookies() and decide what to render, but they can't run browser APIs or listen for the visitor's choice. Anything that reacts to a click on the banner has to live in a Client Component.
Check your own website in 30 seconds
Our free scanner lists every cookie and tracker your site sets, sorted into categories, before you add a banner.
This guide is general information, not legal advice. Laws and regulator guidance change; check the current rules for your situation or ask a lawyer.