Comparisons
Build your own cookie banner or use a CMP?
The popup is the easy part of a cookie banner. A homemade setup also has to block scripts before consent, store and log choices, ask again when things change, talk to Google Consent Mode, honor Global Privacy Control and vary by region. Here's what that takes, so you can decide whether to build or buy.
- Plain English
- Written for website owners
- Free to read
On this page
You can build your own cookie banner, and for a site with one or two trackers and a single audience it can be a reasonable choice. But the popup is a small part of the job. A homemade consent setup also has to block scripts until consent, store the choice, keep proof of it, ask again when your cookies change, send Google Consent Mode signals, honor Global Privacy Control and show different banners in different regions. A consent management platform (CMP) does those for you. The decision comes down to how many of those requirements apply to you and who will maintain the code.
The banner UI is the easy part
A dialog with three buttons and a preferences panel is a few hours of HTML, CSS and JavaScript. Getting the details right takes longer than it looks: equal prominence for Reject and Accept, category switches that start off, keyboard focus that moves into the dialog and back out, readable contrast, sensible behavior on small screens and text in every language your visitors read. None of it is hard, but all of it has to be done and tested.
The rest of this guide covers the parts that are easy to underestimate.
What a DIY consent setup must handle
1. Blocking before consent
The ePrivacy Directive Art. 5(3) requires consent before non-essential storage or access on the device, so scripts must not run until the visitor chooses. The common technique is to ship tags as type="text/plain" and swap them for real scripts after consent:
function releaseCategory(category) {
var selector = 'script[type="text/plain"][data-category="' + category + '"]';
document.querySelectorAll(selector).forEach(function (old) {
var s = document.createElement('script');
for (var i = 0; i < old.attributes.length; i++) {
var a = old.attributes[i];
if (a.name !== 'type' && a.name !== 'data-category') s.setAttribute(a.name, a.value);
}
if (!old.src) s.text = old.text;
s.async = old.hasAttribute('async'); // dynamic scripts default to async
old.replaceWith(s);
});
}
Even this small function hides decisions. Dynamically inserted external scripts run as soon as they download unless you set async to false, so execution order can change. Iframes and images need a separate path using data-src. Scripts injected by other scripts or by a tag manager won't be in the DOM to tag. The guide to blocking cookies and scripts until consent covers the techniques and their gaps.
2. Storing the choice
Store the choice in a first-party cookie so your server can read it too. Decide on a format that includes the categories, a timestamp and a banner version. One browser detail matters here: Safari's Intelligent Tracking Prevention caps cookies set from JavaScript at seven days, so a consent cookie written with document.cookie may expire long before the lifetime you intended. Setting it from the server with a Set-Cookie header avoids that cap.
3. Withdrawal
GDPR Art. 7(3) requires withdrawal to be as easy as consent. You need a persistent link or button to reopen the preferences, and a plan for scripts that have already run. A script can't be unloaded from a running page, so most implementations reload the page after a withdrawal. You may also need to delete cookies the script set, which you can only do for cookies on your own domain.
4. Versioning and re-consent
When you add a new category or a significant new purpose, earlier consent doesn't cover it. Your stored choice needs a version number, and the banner needs to reappear when the stored version is older than the current one. You'll also want a maximum consent age, after which visitors are asked again. See how long cookie consent lasts for typical periods.
5. Proof of consent
GDPR Art. 7(1) requires you to be able to demonstrate consent. A cookie in the visitor's browser isn't proof, because the visitor controls it. You need a server-side log:
function logConsent(record) {
// record: { id, version, categories, action, time }
var body = JSON.stringify(record);
if (!navigator.sendBeacon || !navigator.sendBeacon('/api/consent-log', body)) {
fetch('/api/consent-log', { method: 'POST', body: body, keepalive: true });
}
}
Then build the endpoint, storage, retention and deletion, and a way to look up a record when someone asks. Decide what not to store: a random consent ID is enough to link a record to a browser, and storing full IP addresses adds personal data you probably don't need. Proof of consent records lists the fields worth keeping.
6. Google Consent Mode v2
If you use Google Analytics or Google Ads, your banner needs to send Consent Mode signals. The default must be set before any Google tag loads, and an update must follow each choice:
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('consent', 'default', {
ad_storage: 'denied',
ad_user_data: 'denied',
ad_personalization: 'denied',
analytics_storage: 'denied'
});
</script>
<!-- later, after the visitor allows analytics -->
<script>
gtag('consent', 'update', { analytics_storage: 'granted' });
</script>
You also need to map your categories to the signals, restore the stored choice on every page load before tags fire, and test with Tag Assistant. The Consent Mode v2 guide explains what each signal controls.
7. Global Privacy Control
California's regulations, and several other states' rules, treat a browser's Global Privacy Control signal as an opt-out of selling or sharing. Detecting it is one line, navigator.globalPrivacyControl === true, and the server sees a Sec-GPC: 1 header. The work is in deciding what it switches off, recording it, and showing visitors that it was honored. See Global Privacy Control explained.
8. Regional rules
EU and UK visitors need opt-in; most US visitors get an opt-out model; other countries vary. A DIY setup needs a reliable way to know the visitor's country, usually from your CDN or a server-side lookup, and a sensible default when the country is unknown. Opt-in vs opt-out consent shows how one banner can serve both models.
9. Keeping up
Your site's trackers change whenever someone adds a tool. Regulators update their guidance. Google changes its requirements. A DIY setup needs someone to rescan the site, update categories and the cookie policy, and adjust the code. That ongoing work is the cost most teams underestimate.
Testing a homemade banner
A commercial tool has been tested on many sites. Yours hasn't, so build tests in from the start. The most valuable one checks that nothing non-essential loads before consent, because that failure is invisible to anyone looking at the page. An end-to-end test with a tool such as Playwright can record network requests in a fresh browser context, which starts with no cookies:
import { test, expect } from '@playwright/test';
const TRACKERS = /google-analytics\.com|googletagmanager\.com|connect\.facebook\.net/;
test('trackers wait for consent', async ({ page }) => {
const hits = [];
page.on('request', (req) => {
if (TRACKERS.test(req.url())) hits.push(req.url());
});
await page.goto('https://staging.example.com/');
await page.waitForLoadState('networkidle');
expect(hits).toEqual([]);
await page.getByRole('button', { name: 'Accept all' }).click();
await expect.poll(() => hits.length).toBeGreaterThan(0);
});
Add similar tests for Reject all, for withdrawal, for a stored choice from an older banner version, and for a request carrying the GPC signal. Run them in your deployment pipeline so a template change that adds an untagged script fails the build instead of reaching visitors. This is also a useful habit if you use a CMP, since the tool can only block what you've told it about.
Effort compared
| Requirement | Build it yourself | Typical CMP |
|---|---|---|
| Banner and preferences UI | Hours to days, plus accessibility testing | Configure in a dashboard |
| Prior blocking | Write and test release logic | Tag scripts or use automatic blocking |
| Consent log | Build endpoint, storage, retention | Included |
| Versioning | Design and implement | Usually automatic when you change categories or text |
| Google Consent Mode v2 | Write default and update calls | Usually built in |
| GPC and regional rules | Geolocation plus custom logic | Usually configurable |
| Cookie scanning | Manual audits or your own crawler | Usually scheduled |
| IAB TCF | Not realistic for a single site | Offered by some CMPs |
When building makes sense
- Your site uses one or two non-essential tools, and that's unlikely to change.
- Your visitors come mostly from one region with one set of rules.
- You have strict policies against third-party scripts on your pages, or you need the banner deeply integrated into an app's own settings screens.
- You have developers who will own the code, the log and the updates for as long as the site runs.
A middle path is an open-source library for the front end, combined with your own logging endpoint. It saves the UI work but leaves the rest to you.
When a CMP makes sense
- You have visitors from several regions with different rules.
- Marketing adds and removes tools regularly.
- You use Google Analytics or Google Ads and need Consent Mode working reliably.
- You run several sites, or manage sites for clients.
- Nobody on the team wants to own consent code for the next few years.
Using a CMP doesn't mean giving up control. Many expose an API and a readable consent cookie, so you can still build custom UI around them. PrivacyQuick, for example, offers has(), on('change') and a pq:consent event in its JavaScript API.
Decision checklist
- Count your non-essential tools and visitor regions.
- List which of the nine requirements above apply to you.
- Estimate build time and, more importantly, yearly maintenance time.
- Name the person who will own the code and the consent log.
- If you're leaning towards a CMP, test one on staging against your own requirements before deciding.
Frequently asked questions
Is it legal to build your own cookie consent banner?
Yes. The law sets requirements for how consent is obtained and recorded, not which software you use. A homemade banner is fine if it meets the same requirements as a commercial one.
Can I build an IAB TCF banner myself?
In practice, not as a one-off project. TCF banners must come from a CMP registered with IAB Europe that follows the framework's policies and technical specifications, and Google's publisher ad products additionally require a Google-certified CMP.
How long does it take to build a cookie banner from scratch?
A basic banner with blocking can take a day or two. A setup with consent logging, versioning, Consent Mode, GPC, regional rules, translations and accessibility testing usually takes much longer, and it needs maintenance afterwards.
Should I store cookie consent in a cookie or in localStorage?
A first-party cookie is the usual choice because your server can read it and act on it before any page script runs. If you set it from JavaScript, be aware that some browsers shorten the lifetime of script-set cookies.
Check your own website in 30 seconds
Our free scanner lists every cookie and tracker your site sets, sorted into categories, before you add a banner.
This guide is general information, not legal advice. Laws and regulator guidance change; check the current rules for your situation or ask a lawyer.