TIL: How to create a super simple Cookie Consent Alpine.js component

Henrik Hauge Bjørnskov
2 min readJun 28, 2023

For some time I have been searching for a simple way of creating a Cookie Consent banner.

It is super simple to just show or hide a div with some text about cookies. But in order to use analytics we have to be able to react to changes e.g. if the user accepts or declines cookies.

So I cooked up a simple Alpine component using @alpinejs/persist to save the state and then Alpine.data to do the logic and dispatch a custom event.

This is the JavaScript code for the component. It is super simple. It just shows a banner if we don’t know the state (accepted/rejected) otherwise it just hides the banner. When it is accepted/declined or initialized it will dispatch a custom event called cookieConsent which can be used with a simple document.addEventListener('cookieConsent', function () {})

import Alpine from 'alpinejs'
import persist from '@alpinejs/persist'

Alpine.plugin(persist)

document.addEventListener("DOMContentLoaded", function () {
Alpine.start()
})

document.addEventListener("alpine:init", function () {
Alpine.data('cookieConsent', () => ({
state: Alpine.$persist('unknown').as('cookieConsent'),

init() {
this.dispatchEvent()
},

dialogue: {
['x-show']() {
return this.state == 'unknown'
}
},

accept: {
['@click']() {
this.state = 'accepted'

this.dispatchEvent()
}
},

decline: {
['@click']() {
this.state = 'declined'

this.dispatchEvent()
}
},

dispatchEvent() {
document.dispatchEvent(new CustomEvent('cookieConsent', {
detail: this.state
}))
}

}))
})

We also need some HTML for this. Fortunately this is also very simple and can be customised however you see fit

<!-- Borrowed from https://tailwindflex.com/sophia-baker/cookie-consent -->

<div x-data="cookieConsent" x-cloak>
<div x-bind="dialogue" class="fixed bottom-0 p-6 w-full flex justify-center z-[2000]">
<div class="bg-white bg-opacity-95 text-xs rounded-md fade w-[450px] show">
<div class="p-4 flex items-center justify-between px-6 rounded border border-green-700">
<p>
By using XYZ, you agree to our
<a class="underline font-bold" href="#" target="_blank">Cookies Policy.</a>
</p>

<button x-bind="decline" type="button" class="px-5 py-3 rounded-lg text-white bg-red-700 hover:bg-red-800 ml-1.5 min-w-max">Decline</button>
<button x-bind="accept" type="button" class="px-5 py-3 rounded-lg text-white bg-green-700 hover:bg-green-800 ml-1.5 min-w-max">Accept</button>
</div>
</div>
</div>
</div>

Thats it!

--

--

Henrik Hauge Bjørnskov

I build stuff at Relatel A/S, vivid traveller and gear junkie.