Cookie Banner Implementation
Step-by-step guide to implement CCPA/GDPR-compliant cookie banners in your Next.js app. Includes a ready-to-use AI prompt for quick implementation.
Quick Start: AI Implementation Prompt
Copy this prompt and paste it into Claude Code, Cursor, or your AI assistant of choice:
I need to implement a CCPA/GDPR-compliant cookie banner for my Next.js application. Please create:
1. A cookie consent management utility (lib/cookies.ts) with:
- Cookie categories: essential, functional, analytics, marketing
- Consent storage in localStorage and cookies
- Functions to get/set consent, check categories
- CCPA "Do Not Sell" functionality
- 1-year consent expiry
2. A CookieBanner component (components/cookies/CookieBanner.tsx) with:
- Sticky bottom banner with glassmorphic design
- Three options: Accept All, Reject Non-Essential, Customize
- CCPA notice with "Do Not Sell My Info" button
- Links to cookie and privacy policies
- Smooth animations (using Framer Motion if available)
- Mobile-responsive design
3. A CookiePreferences modal (components/cookies/CookiePreferences.tsx) with:
- Detailed category management with toggle switches
- Expandable cookie details per category
- Visual indicators for required vs optional
- Accept All / Reject All quick actions
4. A Cookie Policy page (app/cookies/page.tsx) with:
- Comprehensive cookie documentation
- List of all cookies by category
- CCPA/CPRA rights explanation
- Quick actions: Manage Preferences, Clear Cookies
- Links to privacy policy
5. Integration into the root layout (app/layout.tsx):
- Add <CookieBanner /> component before closing </body>
- Import the component properly
Requirements:
- Use TypeScript
- Dark theme with semi-transparent backgrounds
- Ensure CCPA compliance (California law)
- Include "Do Not Sell My Personal Information" option
- Store consent for 1 year
- Re-show banner if consent expires
- Only load analytics/marketing after consent
Color scheme:
- Primary: Orange (#FFA500 or similar)
- Secondary: Yellow (#FFD700 or similar)
- Success: Lime green
- Background: Dark with transparency (bg-black/50, bg-white/5, etc.)
Please implement all files with proper TypeScript types, error handling, and mobile responsiveness.Manual Implementation Steps
Create Cookie Management Utilities
First, create the core utilities for managing cookie consent.
// lib/cookies.ts
export type CookieCategory = 'essential' | 'functional' | 'analytics' | 'marketing';
export interface CookieConsent {
essential: boolean;
functional: boolean;
analytics: boolean;
marketing: boolean;
timestamp: number;
version: string;
}
const CONSENT_COOKIE_NAME = 'cookie_consent';
const CONSENT_VERSION = '1.0';
const CONSENT_EXPIRY_DAYS = 365;
export function getCookieConsent(): CookieConsent | null {
if (typeof window === 'undefined') return null;
try {
const stored = localStorage.getItem(CONSENT_COOKIE_NAME);
if (!stored) return null;
const consent = JSON.parse(stored) as CookieConsent;
// Check if expired
const expiryTime = consent.timestamp + (CONSENT_EXPIRY_DAYS * 24 * 60 * 60 * 1000);
if (Date.now() > expiryTime) {
localStorage.removeItem(CONSENT_COOKIE_NAME);
return null;
}
return consent;
} catch {
return null;
}
}Build the Cookie Banner Component
Create the main banner that appears on first visit.
Component Structure:
- • Sticky positioning at bottom
- • Three action buttons
- • CCPA compliance notice
- • Links to policies
Key Features:
- • Auto-show on first visit
- • Animate in/out smoothly
- • Mobile responsive
- • Accessible (ARIA labels)
Create Preferences Modal
Build a detailed preferences modal for granular control.
// Key elements to include:
- Category toggles (Essential always ON)
- Expandable cookie details per category
- Save & Cancel buttons
- Quick "Accept All" / "Reject All" options
- Visual feedback for enabled/disabled statesAdd Cookie Policy Page
Create a comprehensive cookie policy page at /cookies
Required Sections:
- • What are cookies?
- • How we use cookies
- • Cookie categories & list
- • Third-party cookies
- • Your cookie choices
- • CCPA/GDPR rights
Integrate with Your App
Add the cookie banner to your root layout.
// app/layout.tsx
import { CookieBanner } from "@/components/cookies/CookieBanner";
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>
{children}
<CookieBanner />
</body>
</html>
);
}Conditional Cookie Loading
Critical: Only load analytics and tracking after user consent.
// components/Analytics.tsx
"use client";
import { useEffect } from "react";
import { hasConsent } from "@/lib/cookies";
export function Analytics() {
useEffect(() => {
// Check for analytics consent
if (!hasConsent('analytics')) {
return;
}
// Load Google Analytics
const script = document.createElement('script');
script.src = `https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_ID}`;
script.async = true;
document.head.appendChild(script);
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', process.env.NEXT_PUBLIC_GA_ID);
// Listen for consent changes
const handleConsentChange = (e: CustomEvent) => {
if (!e.detail.analytics) {
// User revoked consent - stop tracking
gtag('consent', 'update', {
'analytics_storage': 'denied'
});
}
};
window.addEventListener('cookieConsentChange', handleConsentChange);
return () => {
window.removeEventListener('cookieConsentChange', handleConsentChange);
};
}, []);
return null;
}Testing Checklist
Test Each Scenario:
Browser Console Tests:
// Check stored consent
localStorage.getItem('cookie_consent')
// Check all cookies
document.cookie
// Trigger banner reset (for testing)
localStorage.removeItem('cookie_consent')
window.location.reload()Troubleshooting Common Issues
Banner not appearing?
- • Check if consent is already stored in localStorage
- • Verify component is added to layout.tsx
- • Check browser console for errors
- • Ensure client-side rendering with "use client"
Analytics still loading without consent?
- • Analytics must check hasConsent() before loading
- • Remove any hardcoded script tags from HTML
- • Check for third-party components loading trackers
Style conflicts?
- • Ensure high z-index (z-50 or higher)
- • Use fixed positioning, not absolute
- • Check for CSS reset affecting buttons
Final File Structure
your-app/
├── lib/
│ └── cookies.ts # Cookie consent utilities
├── components/
│ └── cookies/
│ ├── CookieBanner.tsx # Main banner component
│ └── CookiePreferences.tsx # Preferences modal
├── app/
│ ├── layout.tsx # Add <CookieBanner />
│ ├── cookies/
│ │ └── page.tsx # Cookie policy page
│ └── privacy/
│ └── page.tsx # Privacy policy (update with cookie info)Compliance Verification
CCPA Requirements ✓
- "Do Not Sell My Personal Information" link present
- Users can opt out of data collection
- Clear information about data usage
GDPR Requirements ✓
- Explicit consent before setting non-essential cookies
- Granular control over cookie categories
- Easy withdrawal of consent
- Clear cookie policy with all details
Additional Resources
Reference Implementation:
- Our Cookie Policy →See it in action
- Cookie Compliance Playbook →Understanding the why
Legal Resources:
Testing Tools:
- Cookie Scanner →Check what cookies you're setting
Implementation Time: 2-3 Hours
With the AI prompt above, you can have a compliant cookie banner running in under 30 minutes. Spend the extra time customizing the design and testing thoroughly.