How to Implement a Cookie Consent Banner in Drupal With JavaScript
A cookie consent banner gives visitors a clear choice about optional cookies before analytics, advertising, personalisation, or other tracking scripts run. In Drupal, the banner can be added as a small custom module or theme feature, while JavaScript manages the visitor’s preference and updates the page without a reload.
A reliable implementation needs more than a dismiss button. It should distinguish necessary cookies from optional categories, work with Drupal behaviours, remain usable with a keyboard and screen reader, and prevent third-party scripts from loading before consent. This approach is useful for Australian websites serving local customers in Sydney, Melbourne, Brisbane, or visitors from jurisdictions with stricter privacy requirements.
Decide What Consent Your Site Needs
Start by listing every cookie and browser storage entry created by Drupal, contributed modules, themes, and external services. Drupal may use cookies for sessions, form tokens, administration features, or language preferences. These are generally essential for the site to function. Google Analytics, Meta Pixel, embedded marketing tools, chat widgets, heatmaps, and advertising tags usually belong in optional categories.
Do not assume that a single “Accept” button provides meaningful control. A visitor should be able to accept all cookies, reject optional cookies, or open a settings panel and choose categories. The wording should explain the purpose of each category in plain English, such as “Analytics helps us understand which pages are used” rather than “We process non-essential identifiers.”
For an Australian site, review the Privacy Act 1988, the Australian Privacy Principles, and guidance from the Office of the Australian Information Commissioner. Consent requirements depend on the data and services involved, and a banner alone does not replace a privacy policy. If a Brisbane retailer also markets to people in the European Economic Area, the implementation may need to satisfy GDPR expectations as well.
Create A Drupal Library
A custom module keeps the consent banner separate from theme templates and makes it easier to reuse across several Drupal sites. Create a module directory such as web/modules/custom/cookie_consent, then add an information file and a library definition.
The following cookie_consent.libraries.yml file loads one CSS file and one JavaScript file:
banner:
version: 1.x
css:
theme:
css/cookie-consent.css: {}
js:
js/cookie-consent.js: {}
dependencies:
- core/drupal
- core/once
Attach the library globally from cookie_consent.module so the banner is available on every front-end page:
<?php
function cookie_consent_page_attachments(array &$attachments) {
$attachments['#attached']['library'][] = 'cookie_consent/banner';
}
This uses Drupal’s asset system rather than inserting a raw <script> tag into a Twig template. Drupal can aggregate, cache, and manage the files correctly. If the feature is limited to selected routes, attach the library conditionally instead of loading it across the entire site.
A small Twig template can hold the banner markup. You can render it through a block plugin, preprocess it into the page, or add it from a custom controller. A block is often the most maintainable choice because editors can place it in a region and site builders can configure visibility.
Build An Accessible Consent Interface
The banner should state what it does immediately and provide visible controls. A minimal structure might look like this:
<section
id="cookie-consent"
class="cookie-consent"
role="dialog"
aria-labelledby="cookie-consent-title"
aria-describedby="cookie-consent-description"
hidden>
<h2 id="cookie-consent-title">Cookie choices</h2>
<p id="cookie-consent-description">
We use necessary cookies to run this site and optional cookies to improve it.
</p>
<div class="cookie-consent__actions">
<button type="button" data-consent="accept">Accept optional cookies</button>
<button type="button" data-consent="reject">Reject optional cookies</button>
<button type="button" data-consent="settings">Manage preferences</button>
</div>
<div id="cookie-settings" hidden>
<label>
<input type="checkbox" name="analytics" data-consent-category="analytics">
Analytics cookies
</label>
<button type="button" data-consent="save">Save preferences</button>
</div>
</section>
Use a real <button> for every action, provide a visible focus state, and ensure that text and controls meet suitable colour contrast. The dialog should not trap a visitor in an interaction or prevent ordinary browsing. If the settings panel opens, move focus to its heading or first control and return focus to the settings button when it closes.
The visual design should work on a small mobile screen as well as a desktop monitor. A fixed panel at the bottom can be practical, but it must not cover essential navigation or obscure content on an iPhone. Australian users commonly browse through mobile connections while travelling between suburbs or regional areas, so keep the markup, CSS, and JavaScript lightweight.
| Consent category | Typical examples | Load before consent? | Recommended control |
|---|---|---|---|
| Necessary | Drupal session, security token, login state | Yes | Inform the visitor |
| Preferences | Language, display options, saved interface choices | Usually no | Optional checkbox |
| Analytics | Google Analytics, Matomo, event tracking | No | Opt-in category |
| Marketing | Advertising pixels, remarketing, campaign tags | No | Opt-in category |
| Embedded media | Video, maps, social posts | No | Load after consent or on request |
Store And Apply The Visitor’s Choice
A consent preference can be stored in a first-party cookie. Use a specific name, a version number, and an explicit value so that future changes can invalidate old choices. For example, drupal_cookie_consent=v1:analytics records that the visitor accepted analytics while leaving marketing disabled.
The JavaScript should attach through Drupal.behaviors, not through a one-time document-ready handler. This is important because Drupal may replace parts of the page through AJAX or BigPipe. The once utility prevents duplicate event listeners when the behaviour is attached again.
(function (Drupal, once) {
'use strict';
const cookieName = 'drupal_cookie_consent';
const cookieVersion = 'v1';
function readConsent() {
const match = document.cookie.match(
new RegExp('(?:^|; )' + cookieName + '=([^;]*)')
);
if (!match) {
return null;
}
const value = decodeURIComponent(match[1]);
return value.startsWith(cookieVersion + ':')
? value.substring(cookieVersion.length + 1).split(',')
: null;
}
function saveConsent(categories) {
const value = `${cookieVersion}:${categories.join(',')}`;
document.cookie =
`${cookieName}=${encodeURIComponent(value)}; Max-Age=31536000; Path=/; SameSite=Lax`;
}
Drupal.behaviors.cookieConsent = {
attach(context) {
once('cookie-consent', '#cookie-consent', context).forEach((banner) => {
const existing = readConsent();
if (!existing) {
banner.hidden = false;
}
banner.querySelector('[data-consent="accept"]')
?.addEventListener('click', () => {
saveConsent(['analytics', 'marketing']);
banner.hidden = true;
Drupal.cookieConsent?.apply(['analytics', 'marketing']);
});
banner.querySelector('[data-consent="reject"]')
?.addEventListener('click', () => {
saveConsent([]);
banner.hidden = true;
Drupal.cookieConsent?.apply([]);
});
});
}
};
Drupal.cookieConsent = {
apply(categories) {
document.dispatchEvent(new CustomEvent('cookieConsentChanged', {
detail: { categories }
}));
}
};
})(Drupal, once);
The example is intentionally small. A production version should also wire up the settings button, read checkbox values, handle malformed cookies, and expose the current state to other scripts. Set Secure when the site is served through HTTPS, and consider whether the cookie needs a more restrictive Path or Domain value.
Prevent Tracking Scripts From Loading Early
The most important technical rule is to delay optional services until consent exists. Hiding a banner after Google Analytics has already loaded does not meet that goal. Remove optional libraries from the global page attachments and load them only after the consent event is received.
One pattern is to listen for the custom event:
document.addEventListener('cookieConsentChanged', (event) => {
if (event.detail.categories.includes('analytics')) {
const script = document.createElement('script');
script.src = '/modules/custom/cookie_consent/js/analytics-loader.js';
script.async = true;
document.head.appendChild(script);
}
});
The loader should guard against duplicate insertion, especially when AJAX content is added. A stronger option is to place service configuration in data- attributes and create the script only after the visitor opts in. For embedded YouTube videos, maps, or social posts, show a placeholder with a “Load content” control instead of requesting the third-party resource immediately.
Drupal modules may attach tracking code through libraries, preprocess functions, response attachments, or tag-management integrations. Audit the complete render output and browser network requests. An Australian marketing team might add a campaign tag for a Melbourne event without realising that it bypasses the consent logic, so governance matters as much as JavaScript.
Keep a record of the consent policy, cookie names, purposes, expiry periods, and third parties involved. A practical Drupal implementation guide can help when reviewing custom integration patterns, but the final behaviour must be tested against the services actually installed on your website.
Test The Banner Across Real User Journeys
Test in a private browser window with cookies and local storage cleared. Confirm that the banner appears for a new visitor, that “Reject” prevents analytics and marketing requests, and that “Accept” loads only the approved services. Inspect the browser’s Application and Network panels rather than relying solely on the visual result.
Test an existing visitor who changes their choice later. The settings control should be available from the privacy policy, footer, or a persistent small button. When consent is withdrawn, stop future tracking and remove optional cookies where technically possible. Some third-party cookies cannot be deleted from your domain, so explain the limitation and prevent additional requests.
Check Drupal-specific paths, including cached pages, AJAX forms, BigPipe responses, multilingual versions, and authenticated sessions. A consent banner that works on the home page may fail on a Commerce checkout or an editorial preview. Test on current versions of Chrome, Safari, Firefox, and mobile browsers, including a slow connection similar to conditions sometimes experienced in regional Australia.
Use keyboard-only navigation, screen-reader testing, zoom at 200 percent, and automated checks for labels and contrast. Verify that the banner does not shift the page unexpectedly, that the close or save action has a clear name, and that focus remains understandable after the dialog disappears. Record the test date and the versions of Drupal, contributed modules, and third-party scripts.
Maintain Consent As The Site Changes
Consent is a continuing configuration task rather than a feature that can be installed once. Re-scan after adding a module, changing a CDN, embedding a new video provider, or updating a tag manager. A module update can introduce a new cookie even when the site’s visible design remains unchanged.
Version the consent policy when purposes or providers change. If the categories are materially different, use a new cookie version so returning visitors are asked again. Avoid silently treating an old “accepted everything” value as permission for a newly added advertising service.
Make the banner’s language match the privacy policy and cookie notice. State the organisation responsible for the site, explain how preferences can be changed, and provide a contact method. For Australian businesses, this information should fit the organisation’s broader privacy documentation and reflect the services used by local campaigns, ecommerce systems, and customer support tools.
Finally, monitor consent events without turning the monitoring itself into an unapproved tracking system. Server-side logs can record technical errors, while aggregated operational metrics can show whether the banner is functioning. Review the implementation whenever Drupal core, a consent-related module, or a major analytics provider changes its loading requirements.