Start

I will show you in this post how you can create a cookie consent with hugo.io framework for google analytics integration in most themes.

We will start in the directory of your hugo website and navigate to the “/theme//layouts/partials” directory.

cd /var/www/<website-name>/theme/<theme-name>/layouts/partials

In this directory, we will create a file called cookie-consent.html and in this file we put the following code.

<div id="cookie-notice">
<span>We would like to use third party cookies and scripts to improve the
functionality and user experience of this website.</span>
<a id="cookie-notice-accept" class="btn btn-primary btn-sm">Approve</a>
<a id="cookie-notice-deny" class="btn btn-primary btn-sm">Deny</a>
<a href="/about/en/privacy/" class="btn btn-primary btn-sm">More info</a></div>
<script>
    function createCookie(name,value,days) {
        var expires = "";
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days*24*60*60*1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + value + expires + "; path=/";
    }
    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    }
    function eraseCookie(name) {
        createCookie(name,"",-1);
    }

    if(readCookie('cookie-notice-option')=='true') {
        {{ if hugo.IsProduction | or (eq .Site.Params.env "production") }}
                localStorage.setItem("doNotTrack", "0");
        {{ end }}
    } else if (readCookie('cookie-notice-option')!='false'){
        document.getElementById('cookie-notice').style.display = 'block';
    }

    document.getElementById('cookie-notice-accept').addEventListener("click",function() {
        createCookie('cookie-notice-option','true',31);
        document.getElementById('cookie-notice').style.display = 'none';
        location.reload();
    });

    document.getElementById('cookie-notice-deny').addEventListener("click",function() {
        createCookie('cookie-notice-option','false',31);
        document.getElementById('cookie-notice').style.display = 'none';
        location.reload();
    });
</script>

This file will later provide the cookie consent overlay with its buttons to accept, decline or more information.

Note: you need to change the href link in this file for the “more information” button to point to your privacy policy location

This consent file makes use of the hugo.io framework internal google analytics template. We set the doNotTrack option to the state the user consent to and this option is later used in hugos internal google analytics template to check if data is allowed to sent or not.

Now that we have this file, we need to adapt our head html document to include the internal google analytics template to our body & head section, as well as our newly created consent template. We also need to default our doNotTrack option to “1”, so that tracking is deactivated by default.

For this we will edit the head html file. In my current used theme this would be the following command.

nano /var/www/<hugo-root>/theme/<theme-name>/layouts/partials/head.html

At the end of the file we will add the following to set the default doNotTrack and to implement our templates.

<!-- Google Analytics internal template -->
{{- if .Site.GoogleAnalytics }}
    <script>
      if (localStorage.getItem("doNotTrack") === null) {
        localStorage.setItem("doNotTrack", "1") // default value before any choice has been made
      }
      var doNotTrack = localStorage.getItem("doNotTrack");
    </script>
    {{ template "partials/cookie-consent.html" . }}
    {{ template "_internal/google_analytics.html" . }}
{{- end}}

Now we need some styling for our consent message in our main css file. My template uses scss, so that’s what I will use for this. To style you template, find your css file and edit it.

nano /var/www/<hugo-root>/theme/<theme-name>/assets/scss/_main.scss

Add the following style to it.

#cookie-notice {
        font-size: medium;
        padding: 0.5rem 1rem;
        display: none;
        text-align: center;
        position: fixed;
        bottom: 0;
        left: 20px;
        padding-top: 40px;
        padding-bottom: 40px;
        width: 100%;
        background: rgb(70, 70, 70);
        color: rgba(255,255,255,0.8);
        z-index: 999;
        a {
                font-weight: 600;
                display: inline-flex;
                cursor: pointer;
                margin-left: 0.5rem;
                z-index: 999;
        }
}
#cookie-notice-accept {
        color: rgb(86, 228, 58);
}
#cookie-notice-deny {
        color: rgb(243, 34, 34);
}
@media (max-width: 767px) {
        #cookie-notice {
                span {
                        display: block;
                        padding-top: 3px;
                        margin-bottom: 1rem;
                }
                a {
                        position: relative;
                        bottom: 4px;
                        z-index: 999;
                }
                left: 0px;
        }
}

Activate everything in hugo.toml

Now our templating is done and we need to add some configurations in our hugo.toml to be able to use this consent feature we built.

nano /var/www/<hugo-root>/hugo.toml

Add the following values before your [params] section.

googleAnalytics = "G-XXXXXXXXXX"
[privacy]
  [privacy.googleAnalytics]
    anonymizeIP = true
    disable = false
    respectDoNotTrack = true
    useSessionStorage = false

Make sure you change the dummy value “G-XXXXXXXXXX” to your own Google Analytics stream id.

After this you need to rebuild & deploy your application and the cookie consent message will appear and only sent data to google analytics if the user accepts the consent.

I hope this article was helpful for your cookie consent integration.