How to Implement a GDPR Cookie Consent Banner on Your Website

Updated · 7 min read

If your website uses Google Analytics, advertising pixels, or any other non-essential cookie and EU or EEA residents can visit it, GDPR requires you to obtain valid consent before those cookies are set. That means a cookie banner is not optional — it is a legal obligation.

Getting it wrong is expensive. CNIL fined Google and Facebook each €150 million in January 2022 for making the reject button harder to find than the accept button. This guide walks you through what valid consent actually requires, what dark patterns to avoid, and three ways to implement a compliant banner — including a working vanilla JavaScript example.

Why GDPR requires consent before cookies fire

Cookies that identify individual users — analytics cookies that track page views across sessions, advertising cookies that build behavioural profiles — are personal data under GDPR. Processing personal data requires a lawful basis. For tracking cookies, that basis must be consent: freely given, specific, informed, and unambiguous (Article 6(1)(a), Recital 32).

Strictly necessary cookies — session tokens that keep you logged in, shopping cart cookies, load-balancing cookies — are exempt because they are essential for the service the user explicitly requested. Everything else needs opt-in consent before the cookie is set, not after.

The five GDPR consent requirements

Article 4(11) and Article 7 define what valid consent looks like. All five conditions must be met:

  1. Freely given. No cookie wall — you cannot deny access to the site if the user refuses. No bundled consent — accepting analytics and advertising cannot be a single checkbox.
  2. Specific. Each purpose must be separately controlled. Analytics, personalisation, and advertising are distinct purposes; a single “Accept all tracking” toggle does not satisfy specificity.
  3. Informed. Users must know which cookies are set, what they do, who they are shared with, and how long they persist. A vague “we use cookies to improve your experience” is not sufficient.
  4. Unambiguous. Consent must be an active, affirmative act — clicking a clearly labelled Accept button. Pre-ticked checkboxes, scrolling past a banner, or closing a pop-up are not valid consent (Recital 32).
  5. Withdrawable. Users must be able to withdraw consent as easily as they gave it. A “Cookie settings” or “Withdraw consent” link in every page footer is the standard implementation.

Dark patterns that invalidate your consent

Regulators have issued substantial fines specifically for manipulative banner design — not just for missing banners:

  • Asymmetric buttons: A large, colourful “Accept all” button next to a small grey “Reject” link. CNIL’s €150 million Google fine (January 2022) explicitly cited this pattern. The fix: buttons must be visually equivalent.
  • Buried rejection: Hiding “Reject” behind a “Manage settings” sub-menu that requires three additional clicks. Belgian APD orders required IAB Europe to redesign the TCF framework’s consent flow for this reason.
  • Pre-ticked categories: Presenting optional cookie categories with checkboxes pre-selected. Under Article 4(11), consent must be unambiguous — a pre-ticked box is a default, not an affirmative act.
  • Nudge language: Phrasing like “Accept to get the best experience” implies that rejection will degrade the site, coercing consent. This fails the freely-given requirement.
  • Infinite scroll acceptance: Claiming that scrolling past the banner counts as consent. Recital 32 is explicit: “Silence, pre-ticked boxes or inactivity should not therefore constitute consent.”

Cookie categories at a glance

Category Examples Consent required?
Strictly necessary Session token, CSRF token, load balancer cookie No
Analytics Google Analytics (_ga, _gid), Mixpanel Yes
Personalisation Saved preferences, A/B test assignment Yes
Advertising Google Ads (_gcl_au), Meta Pixel (_fbp) Yes

Cookieless analytics tools such as Plausible and Fathom do not set persistent identifiers and therefore do not require GDPR consent.

Three implementation options

Option 1: Build it yourself (DIY)

Suitable for simple sites using only Google Analytics 4. Requires blocking GA4 by default, showing a compliant banner, storing the consent choice in localStorage, and updating Google Consent Mode v2. The vanilla JS example below covers all of this. The main ongoing risk is keeping the implementation updated as your cookie inventory changes.

Option 2: Free consent management platform

Tools such as Cookiebot’s free tier (up to 100 pages), CookieYes free, and Osano’s starter plan scan your site for cookies, generate a compliant banner, and maintain a consent log. Free tiers are ad-supported or limited to smaller sites but are a solid choice if you have more than one analytics or marketing tool.

Option 3: Paid CMP

Cookiebot, OneTrust, TrustArc, and Usercentrics charge monthly fees but provide full audit trails, consent receipts, IAB TCF integration for advertising networks, and automatic script blocking. Necessary if you run advertising campaigns, operate in a regulated sector, or need documented evidence of compliance during a supervisory authority inquiry.

Vanilla JavaScript implementation example

This example works with Google Analytics 4 and implements Google Consent Mode v2. Place all of it before your GA4 snippet in <head>:

/* 1. Set consent defaults BEFORE the GA4 snippet */
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('consent', 'default', {
  analytics_storage: 'denied',
  ad_storage:        'denied',
  wait_for_update:   500
});

/* 2. Check for a stored decision */
(function() {
  var stored = null;
  try { stored = JSON.parse(localStorage.getItem('ck_consent')); } catch(e){}
  if (stored && stored.version === 1) {
    if (stored.analytics) {
      gtag('consent', 'update', { analytics_storage: 'granted' });
    }
    return;
  }

  /* 3. Show banner */
  var banner = document.createElement('div');
  banner.id = 'ck-banner';
  banner.setAttribute('role', 'dialog');
  banner.setAttribute('aria-label', 'Cookie consent');
  banner.innerHTML =
    '<p>We use cookies to understand how visitors use this site.</p>' +
    '<button id="ck-accept">Accept analytics</button> ' +
    '<button id="ck-reject">Reject</button>';
  document.body.appendChild(banner);

  function saveAndClose(analytics) {
    try {
      localStorage.setItem('ck_consent', JSON.stringify({
        version: 1, analytics: analytics, ts: Date.now()
      }));
    } catch(e){}
    if (analytics) {
      gtag('consent', 'update', { analytics_storage: 'granted' });
    }
    banner.remove();
  }

  document.getElementById('ck-accept')
    .addEventListener('click', function(){ saveAndClose(true); });
  document.getElementById('ck-reject')
    .addEventListener('click', function(){ saveAndClose(false); });
})();

Style #ck-banner with a fixed bottom bar. Add a “Cookie settings” link to your footer that runs localStorage.removeItem('ck_consent'); location.reload(); so users can withdraw consent at any time — this satisfies Article 7(3).

Google Consent Mode v2

From March 2024 Google requires Consent Mode v2 for EEA, UK, and Switzerland users. Without it GA4 will not fire for those visitors at all — not even in a reduced, cookieless mode. The gtag('consent', 'default', ...) call in the example above sets the denied defaults before GA4 loads; the gtag('consent', 'update', ...) call grants analytics storage after the user accepts.

If you use Google Tag Manager, configure Consent Initialization triggers and use the built-in Consent State variable rather than the manual approach above. All major CMPs include GTM templates that handle this automatically.

Storing and versioning consent in localStorage

The object stored under ck_consent includes a version field. When you add a new cookie category to your site, increment that version in both your banner code and your cookie policy. The check at step 2 detects the stale record and re-shows the banner, so returning visitors are re-prompted without you having to clear their storage.

Keep the stored object minimal — a consent record is not personal data you need to protect, but there is no reason to store more than the version, timestamp, and per-category boolean flags.

US visitors and state opt-out laws

US federal law imposes no cookie consent requirement. However, California’s CPRA (effective 2023) requires a “Do Not Sell or Share My Personal Information” opt-out link if you sell or share personal data with third parties such as advertising networks. Colorado, Connecticut, Virginia, Texas, and Oregon have passed substantially similar laws. These are opt-out frameworks — you do not need prior consent, only a clear opt-out mechanism — so they are simpler to implement than GDPR’s opt-in regime. If your site serves both EU and US users, the GDPR banner also covers US compliance by giving all visitors equal control.

Generate your Privacy Policy and Cookie Policy

ComplyKit generates a plain-English privacy policy and cookie policy for your website — free, no account required, in under two minutes.

Generate my policy →

Related guides