npm package: @lliam.nan/c8c
Description: The world's least annoying cookie consent banner - GDPR compliant, performant, and invisible
Author: lliam.nan
Latest version: 0.1.0

# Cookie Consent

> The world's least annoying cookie consent banner - GDPR compliant, performant, and invisible.

## Features

✅ **GDPR Compliant** - Meets all legal requirements
✅ **Minimal & Non-intrusive** - Clean design, doesn't block content
✅ **Zero CWV Impact** - No DOM manipulation during load, optimized for performance
✅ **Granular Control** - Users can choose specific cookie categories
✅ **Easy Revocation** - Users can change preferences anytime
✅ **Next.js Optimized** - Works with Server Components, App Router, and SSR
✅ **TypeScript First** - Full type safety
✅ **No Dependencies** - Lightweight, tree-shakeable

## Installation

```bash
npm install cookie-consent
# or
pnpm add cookie-consent
# or
yarn add cookie-consent
```

## Quick Start

### 1. Initialize (shadcn-style)

```bash
npx cookie-consent init
```

This creates a `cookie-consent.json` config and sets up directories.

### 2. Add the component

```bash
npx cookie-consent add
```

This copies the component files to your project.

### 3. Add to your layout

```tsx
// app/layout.tsx
import { CookieConsent } from '@/components/cookie-consent/cookie-banner';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        <CookieConsent />
      </body>
    </html>
  );
}
```

Done! Your cookie banner is now live.

## Pre-built Integrations

Add popular analytics and tracking tools with a single command:

```bash
# Google Tag Manager
npx cookie-consent add gtm
```

Available integrations:
- **gtm** - Google Tag Manager (analytics category)

More integrations coming soon: GA4, Facebook Pixel, Plausible, PostHog

## Usage

### Basic Banner

```tsx
import { CookieConsent } from '@/components/cookie-consent/cookie-banner';

<CookieConsent />
```

### Custom Configuration

```tsx
<CookieConsent
  position="top"
  showDetailsDefault={false}
  config={{
    cookieName: 'my_consent',
    cookieExpiry: 180,
    version: '1.0',
    onPreferencesSaved: (prefs) => {
      console.log('Consent saved:', prefs);
    },
  }}
/>
```

### Settings Button (for footer/privacy page)

```tsx
import { CookieSettings } from '@/components/cookie-consent/cookie-settings';

<CookieSettings buttonText="Manage Cookies" />
```

### Google Tag Manager Integration

Use the pre-built GTM integration for automatic consent management:

```tsx
// app/layout.tsx
import { GoogleTagManager } from '@/components/cookie-consent/integrations/gtm';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        <CookieConsent />
        <GoogleTagManager id="GTM-XXXXXX" />
      </body>
    </html>
  );
}
```

The GTM integration automatically:
- Only loads after analytics consent is given
- Prevents duplicate loading
- Includes noscript fallback
- Uses proper async loading

### Conditional Scripts (Analytics, Tracking, etc.)

Load scripts only when user consents:

```tsx
import { ConditionalScript } from 'cookie-consent';

// Google Analytics - only loads if analytics consent given
<ConditionalScript
  category="analytics"
  src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"
/>

<ConditionalScript category="analytics">
  {`
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'GA_MEASUREMENT_ID');
  `}
</ConditionalScript>
```

### Using the Hook

```tsx
'use client';

import { useCookieConsent } from 'cookie-consent';

function MyComponent() {
  const { isAllowed, preferences, hasConsent } = useCookieConsent();

  useEffect(() => {
    if (isAllowed('analytics')) {
      // Initialize analytics
    }
  }, [isAllowed]);

  return <div>Analytics enabled: {isAllowed('analytics') ? 'Yes' : 'No'}</div>;
}
```

### Server-Side Consent Checking

```tsx
// app/layout.tsx (Server Component)
import { isServerAllowed } from 'cookie-consent/next/server';

export default async function RootLayout({ children }) {
  const analyticsAllowed = await isServerAllowed('analytics');

  return (
    <html>
      <body>
        {analyticsAllowed && <GoogleAnalyticsScript />}
        {children}
      </body>
    </html>
  );
}
```

## API

### Cookie Categories

- `essential` - Always enabled, required for site function
- `functional` - Enhanced features and personalization
- `analytics` - Usage statistics and analytics
- `marketing` - Advertising and tracking

### CookieManager

```tsx
import { CookieManager } from 'cookie-consent';

const manager = new CookieManager({
  cookieName: 'cookie_consent',
  cookieExpiry: 365,
  version: '1.0',
});

// Check consent
manager.hasConsent(); // boolean
manager.isAllowed('analytics'); // boolean
manager.getPreferences(); // CookiePreferences | null

// Manage consent
manager.acceptAll();
manager.rejectAll();
manager.savePreferences({ functional: true, analytics: false, marketing: false });
manager.revokeConsent();
```

## GDPR Compliance Checklist

✅ **Informed consent** - Clear description of each category
✅ **Affirmative action** - No pre-ticked boxes
✅ **Accept/Reject options** - Both clearly available
✅ **Granular control** - Per-category selection
✅ **Freely given** - No forced acceptance
✅ **Easy revocation** - CookieSettings component
✅ **Prior blocking** - Scripts only load after consent
✅ **Essential exemption** - Essential cookies always allowed

## Performance

- **No CWV impact** - Lazy loaded, doesn't block rendering
- **Minimal bundle** - ~3KB gzipped
- **No external deps** - Pure React + cookies
- **Optimized rendering** - Only shows when needed
- **Server-safe** - No hydration issues

## License

MIT