---
name: cookie-consent-251b488f7789
description: >-
  Implement GDPR and ePrivacy-compliant cookie consent: a banner with equal Accept and Reject
  buttons, per-category choices, stored consent records, consent-gated analytics with Google
  Consent Mode v2, and Global Privacy Control. Use when adding a cookie banner, managing marketing
  consent, achieving GDPR compliance for EU users, or integrating consent with analytics platforms.
license: Apache-2.0
compatibility: "JavaScript/TypeScript. Works with React, Next.js 13+ (App Router) and vanilla JS."
metadata:
  author: terminal-skills
  version: "1.1.0"
  category: development
  tags: "cookie-consent, gdpr, privacy, eprivacy, consent-management"
  use-cases: "Add a GDPR-compliant cookie banner to a Next.js app, Implement consent-gated Google Analytics loading, Detect and honor Global Privacy Control (GPC) signal"
  agents: "claude-code, openai-codex, gemini-cli, cursor"
---

# Cookie Consent

## Overview

The ePrivacy Directive (implemented in national law; the UK has PECR) requires prior consent before storing or reading non-essential data on a user's device, and the GDPR defines what valid consent is. GDPR fines reach EUR 20 million or 4% of global annual turnover, whichever is higher; national regulators (CNIL, the Italian Garante, the Dutch AP and others) actively fine cookie banners that make rejecting harder than accepting.

**Strictly necessary** storage needs no consent: login session, CSRF token, shopping cart, load balancing, and a preference the user explicitly set (for example a language switch they just clicked). **Everything else needs consent first**: analytics, advertising, personalization, embedded third-party media.

This skill is engineering guidance, not legal advice; have counsel check the wording and your cookie list.

| Category | Examples | Consent needed |
|----------|----------|----------------|
| Strictly necessary | Auth session, CSRF token, cart | No |
| Functional | Remembered preferences not explicitly chosen, chat widgets | Yes |
| Analytics | Google Analytics 4, Mixpanel, Hotjar | Yes |
| Marketing | Meta Pixel, Google Ads, retargeting | Yes |

## Instructions

Valid consent (GDPR Art. 4(11) and 7) is **freely given, specific, informed, unambiguous and withdrawable**. In practice:

1. Inventory every cookie, local-storage key and third-party script by category (scan with a browser's devtools or a crawler).
2. Block non-essential scripts until consent exists: no pre-ticked boxes, no "scroll means consent".
3. Show "Accept all" and "Reject all" on the first layer with equal prominence, plus "Customize".
4. Explain each category and link the privacy and cookie policies.
5. Store a consent record: version, timestamp, choices, source. Let users reopen the settings and withdraw as easily as they gave consent (a persistent "Cookie settings" link in the footer).
6. Re-ask when the policy version changes or after a fixed period (6 months is common; regulators such as the CNIL accept up to 13 months).

### Consent store (shared by everything else)

```typescript
// lib/consent.ts
export interface ConsentPreferences {
  functional: boolean;
  analytics: boolean;
  marketing: boolean;
}
export interface ConsentRecord {
  version: string;
  timestamp: string;
  preferences: ConsentPreferences;
  source: 'banner' | 'settings' | 'gpc';
}

export const CONSENT_VERSION = '2026-10-01';
const KEY = 'consent_v2';

export function getConsent(): ConsentRecord | null {
  try {
    const raw = document.cookie.split('; ').find((c) => c.startsWith(`${KEY}=`));
    return raw ? JSON.parse(decodeURIComponent(raw.slice(KEY.length + 1))) : null;
  } catch {
    return null;
  }
}

export function saveConsent(preferences: ConsentPreferences, source: ConsentRecord['source']): void {
  const record: ConsentRecord = { version: CONSENT_VERSION, timestamp: new Date().toISOString(), preferences, source };
  const maxAge = 60 * 60 * 24 * 180; // 6 months
  document.cookie = `${KEY}=${encodeURIComponent(JSON.stringify(record))}; max-age=${maxAge}; path=/; SameSite=Lax; Secure`;
  void fetch('/api/consent', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(record),
    keepalive: true,
  }).catch(() => {}); // best-effort audit trail
  applyConsent(preferences);
}

export function applyConsent(p: ConsentPreferences): void {
  window.gtag?.('consent', 'update', {
    analytics_storage: p.analytics ? 'granted' : 'denied',
    ad_storage: p.marketing ? 'granted' : 'denied',
    ad_user_data: p.marketing ? 'granted' : 'denied',
    ad_personalization: p.marketing ? 'granted' : 'denied',
  });
  if (p.analytics) loadScript('ga4', `https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_ID}`);
  // marketing pixels: load only when p.marketing is true, using the same loadScript helper
}

function loadScript(id: string, src: string): void {
  if (document.getElementById(id)) return;
  const s = document.createElement('script');
  s.id = id;
  s.async = true;
  s.src = src;
  document.head.appendChild(s);
}
```

### Google Consent Mode v2 (default denied)

Put this inline in `<head>` before any Google tag. Since 2024, EEA advertisers using Google ads or measurement features must send all four signals (`ad_storage`, `analytics_storage`, `ad_user_data`, `ad_personalization`).

```javascript
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
window.gtag = gtag;
gtag('consent', 'default', {
  ad_storage: 'denied',
  analytics_storage: 'denied',
  ad_user_data: 'denied',
  ad_personalization: 'denied',
  wait_for_update: 500,
});
gtag('js', new Date());
gtag('config', 'G-4F7K2M9QXB');  // your GA4 measurement ID
```

GA4 does not store IP addresses, so the old `anonymize_ip` flag does nothing, and `_gid`/`_gat` are Universal Analytics cookies; GA4 sets `_ga` and `_ga_` plus the measurement ID suffix. On withdrawal, send `consent update` with `denied`, delete those cookies on your domain, and set `window['ga-disable-G-4F7K2M9QXB'] = true`.

### Banner component (React / Next.js)

```tsx
// components/CookieBanner.tsx
'use client';
import { useEffect, useState } from 'react';
import { CONSENT_VERSION, getConsent, saveConsent, applyConsent, type ConsentPreferences } from '@/lib/consent';

const NONE: ConsentPreferences = { functional: false, analytics: false, marketing: false };
const ALL: ConsentPreferences = { functional: true, analytics: true, marketing: true };

export function CookieBanner() {
  const [open, setOpen] = useState(false);
  const [custom, setCustom] = useState(false);
  const [prefs, setPrefs] = useState<ConsentPreferences>(NONE);

  useEffect(() => {
    const saved = getConsent();
    if (saved && saved.version === CONSENT_VERSION) applyConsent(saved.preferences);
    else if (navigator.globalPrivacyControl) saveConsent(NONE, 'gpc');
    else setOpen(true);
  }, []);

  const choose = (p: ConsentPreferences) => { saveConsent(p, 'banner'); setOpen(false); };
  if (!open) return null;

  return (
    <div role="dialog" aria-label="Cookie preferences" className="fixed inset-x-0 bottom-0 z-50 border-t bg-white p-6 shadow-lg">
      <p className="text-sm">We use cookies for analytics and marketing only with your consent. <a className="underline" href="/privacy">Privacy policy</a></p>
      {custom && (['functional', 'analytics', 'marketing'] as const).map((k) => (
        <label key={k} className="mt-2 flex gap-2 text-sm capitalize">
          <input type="checkbox" checked={prefs[k]} onChange={(e) => setPrefs({ ...prefs, [k]: e.target.checked })} /> {k}
        </label>
      ))}
      <div className="mt-4 flex gap-2">
        <button className="rounded border px-4 py-2" onClick={() => choose(NONE)}>Reject all</button>
        <button className="rounded border px-4 py-2" onClick={() => (custom ? choose(prefs) : setCustom(true))}>{custom ? 'Save choices' : 'Customize'}</button>
        <button className="rounded border px-4 py-2" onClick={() => choose(ALL)}>Accept all</button>
      </div>
    </div>
  );
}
```

Give "Accept all" and "Reject all" identical styling. Mount the banner once in the root layout, and add a footer link that clears the saved record and reopens it.

### Global Privacy Control

GPC is a browser signal: `navigator.globalPrivacyControl === true` on the client and the `Sec-GPC: 1` request header on the server. It is legally an opt-out of sale and sharing in several US states (California and others), so treat it as "reject marketing" there; in the EU it is not a consent mechanism, but treating it as a rejection is the safe default (the banner above does this). Server-side detection in Next.js 16+ lives in `proxy.ts` (formerly `middleware.ts`, renamed in Next 16; a codemod exists):

```typescript
// proxy.ts
import { NextResponse, type NextRequest } from 'next/server';

export function proxy(request: NextRequest) {
  const response = NextResponse.next();
  if (request.headers.get('sec-gpc') === '1') {
    response.cookies.set('gpc_optout', '1', { secure: true, sameSite: 'lax', maxAge: 60 * 60 * 24 * 180 });
  }
  return response;
}
export const config = { matcher: '/((?!api|_next/static|_next/image|favicon.ico).*)' };
```

On Next.js 15 and earlier name the file `middleware.ts` and the function `middleware`.

### Consent record endpoint

```typescript
// app/api/consent/route.ts
import { NextResponse } from 'next/server';
import { createHash } from 'node:crypto';

export async function POST(req: Request) {
  const { version, timestamp, preferences, source } = await req.json();
  const ip = req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ?? '';
  await db.consentRecords.create({
    consentVersion: version,
    consentedAt: timestamp,
    preferences,
    source,
    // Keep only what you can justify: a salted hash lets you match a dispute without storing the raw IP
    ipHash: createHash('sha256').update(ip + process.env.CONSENT_HASH_SALT).digest('hex'),
    userAgent: req.headers.get('user-agent'),
  });
  return new NextResponse(null, { status: 204 });
}
```

`db` is your data layer. Records are personal data: set a retention period and mention them in the privacy policy.

## CMP platforms (instead of building your own)

| Platform | Notes |
|----------|-------|
| Cookiebot (Usercentrics) | Automatic cookie scanning, Consent Mode integration |
| Usercentrics | Large EU customer base, TCF support |
| OneTrust | Enterprise suite |
| Osano, Termly, CookieYes | Smaller sites, hosted banner and policy generators |

Check current pricing on each site. If you serve ads through Google AdSense or Ad Manager to EEA or UK users, Google requires a CMP that is certified by Google and uses the IAB Transparency and Consent Framework. TCF is now v2.3: since 28 February 2026 consent strings without the `disclosedVendors` segment are invalid, so use a CMP that has upgraded.

## Examples

### Example 1: Banner and gated GA4 on Next.js

User: "Add a GDPR cookie banner to our Next.js site and make Google Analytics wait for consent."

Create `lib/consent.ts`, `components/CookieBanner.tsx` and `app/api/consent/route.ts` as above, put the Consent Mode default snippet in the root layout `<head>`, and mount `<CookieBanner />`. Verify in devtools: on first load no `_ga` cookie and no request to `googletagmanager.com/gtag/js`; after "Accept all" the script loads and `_ga` appears; after "Reject all" nothing is set.

### Example 2: Honor Global Privacy Control

User: "Respect the GPC signal from Brave and Firefox users."

Add the `navigator.globalPrivacyControl` check in the banner effect and the `proxy.ts` header check. Test with `curl -H "Sec-GPC: 1" -I http://localhost:3000/` and confirm `gpc_optout=1` is set; with the Brave browser (GPC on by default) confirm no banner appears and marketing stays denied.

## Guidelines

- Nothing non-essential may load or set cookies before consent: test with an empty profile and the network tab, not by reading the code.
- Reject must be as easy as accept; do not use dark patterns (hidden reject link, grayed button, cookie walls).
- Consent is per purpose; do not bundle categories.
- Keep the cookie list and policy in sync with what the scan finds; third-party tags added through a tag manager are the usual surprise.
- Withdrawal must work: deleting cookies alone is not enough, also stop the scripts and send the Consent Mode `denied` update.
- Embedded YouTube, maps and social widgets set cookies too; load them on click or use privacy-enhanced modes.
- US state laws (CCPA/CPRA and others) work on opt-out, not opt-in; geolocation-based banners need legal review.
- Test with the EU region really applying (use the region list in Consent Mode defaults or a test CMP configuration); do not rely on your own country's behaviour.


---
Source attribution: terminal-skills
Original project: https://github.com/TerminalSkills/skills/blob/8a9852d489f274538be9bf1c9121aeb403750b1c/skills/cookie-consent/SKILL.md
License: Apache-2.0
License information: https://www.apache.org/licenses/LICENSE-2.0
Original upstream instructions; downloaded from Mega AI Hub.

## Upstream license notice

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to the Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by the Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding any notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   Copyright 2025 Terminal Skills

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.



# Mega AI Hub resource metadata

Creator / publisher: terminal-skills
Original project: https://github.com/TerminalSkills/skills/blob/8a9852d489f274538be9bf1c9121aeb403750b1c/skills/cookie-consent/SKILL.md
Attribution basis: Source repository record

Fields of work: Development & Engineering, Product Management, Marketing, Data & Analytics, Design
Roles: Frontend Developer, Product Manager, Growth Marketer, Data Analyst, UX Designer
Specialties: Frontend, API
Tools: Javascript, Typescript, React, Next.Js
Country applicability: Country not specified
Classification basis: Source category, role and specialization labels
Instruction SHA-256: 7d5a9f89e86d7e288a537812f2984a027a12e5af975d7149d6a40c547803c3a9
