Introduction
Depending on where your website visitors are coming from, you may be required to give users the option of opting into cookies before you start storing them. There are several libraries you can plug into your code to get this functionality, such as CookieYes, but this post will walk through building your own cookie consent banner from scratch.
In this example, I will be using SvelteKit to build the cookie consent banner, but the same ideas can be used to build the banner in any framework.
Google Tag Manager
The easiest way to get started is to load all your website tracking scripts via Google's Tag Manager. Then you can set the Trigger to Consent Initialization - All Pages so the scripts only load after consent has been given by the user.
Ask for permission; not forgiveness
It's important that you respect the user's right to decide whether or not they want to be served cookies. You should assume that the user doesn't consent to cookies until they've explicitly opted in via your cookie consent banner.
Add functionality to the consent banner
We'll start building out our custom consent banner by adding the functionality that will be used to set the user's consent preferences. If you're not building your consent banner with Svelte, you can still take the functions below and modify them to fit your website's needs.
consent-functions
Load the scripts from Google Tag Manager
Next, we can load the scripts you've set up in Google Tag Manager. Since I'm building a component using SvelteKit, I'm going to load this in my component using a <svelte:head>
tag. You can use whatever method makes sense to add this to the document's head tag.
The installation instructions for the Google Tag Manager script used below can be found in your Google Tag Manager's Admin section.
loading-google-tag-manager
Add the consent banner's HTML
Now that we've set up all the functionality we can add the HTML for our new consent banner. The banner I've built uses Tailwind for all the styling.
Since I'm using SvelteKit, I'm going to be using Svelte's on:click
element directive, but you can easily modify this by adding click
Event Listeners to the buttons, and calling the appropriate function when the buttons are clicked.
banner-html
Some extra styling
Below I've added a little bit of extra styling for the buttons. I have a .button
class in my CSS that I use for some default styling.
banner-styles
Was this post helpful?