Cookie consent for React and Next.js
Single-page apps make consent slightly trickier: scripts load through your bundler and routing happens client-side. Here is where to put the banner, how to keep analytics off until consent, and how to handle navigation.
Next.js: load it with next/script
In the App Router, add the script to your root layout using the
next/script component:
import Script from "next/script";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
{children}
<Script id="cc-config" strategy="beforeInteractive">
{`window.TheCookieShooterConfig = { siteName: "My App", lang: "auto" };`}
</Script>
<Script src="/the-cookie-shooter.js" strategy="afterInteractive" />
</body>
</html>
);
}
Put the-cookie-shooter.js in your /public folder so it
is served from the site root.
Vite or Create React App
There is no server document, so the simplest place is index.html,
before the closing body tag:
<script>
window.TheCookieShooterConfig = { siteName: "My App", lang: "auto" };
</script>
<script src="/the-cookie-shooter.js" defer></script>
This keeps the banner outside React's render tree, which is exactly what you want for a consent gate that must appear immediately.
Gate your analytics
Do not initialize analytics on mount. Initialize it only after consent. The
cleanest pattern is to start with Google Consent Mode v2 set to denied, then let
the banner flip it to granted on accept. If you load analytics manually, trigger
it from the banner's onAccept callback instead of in a
useEffect that runs on first render.
Single-page navigation
A common worry is the banner reappearing on every route change. It will not. The consent choice is stored once and read on load, so client-side navigation does not re-prompt. Visitors only see it again if you bump the consent version or they clear their storage. For a deeper walkthrough of the install and config, see the main setup guide.
Drop it into your app
One file in /public, one script tag. The Cookie Shooter has no
dependencies and adds no tracking of its own.
Frequently asked questions
Where should I load a cookie banner in Next.js?
Use next/script with the afterInteractive strategy in your root
layout, or place the script in a custom document before the closing body tag.
Does the banner re-appear on every route change?
No. The choice is stored once and persists across client-side navigation. Visitors are asked again only if you bump the consent version or they clear storage.