Tracking
Next.js cookie consent
Wire a cookie banner in Next.js to analytics: count without cookies until the answer, and pass the saved answer on every page.
Updated
In Next.js, read your consent cookie in the root layout and tell the tag the saved answer on every page: with a yes, the tag line carries data-consent="granted"; with a no, leave the tag out. Until the visitor answers, nextanalytica counts without cookies.
How does it look?
The full walkthrough, with the Server Action that saves the answer and the banner component, is on Next.js cookies and analytics. The short version, with the package's component:
app/layout.tsx
import { cookies } from "next/headers";
import { Analytics } from "@nextanalytica/tag/next";
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const consent = (await cookies()).get("consent")?.value; // "yes", "no" or undefined
return (
<html lang="en">
<body>
{children}
{consent !== "no" && <Analytics project="na_…" {...(consent === "yes" ? { consent: "granted" } : {})} />}
</body>
</html>
);
}When the visitor clicks your banner, call consent(true) or consent(false) from @nextanalytica/tag in the client component that handles it.
What can you ask your agent?
- "How many visitors this week came before answering the banner?"