Setup Matomo Analytics with Drupal and respect “Do Not Track” header (GDPR compliant)

Drupal

Install the “EU Cookie Compliance” Module

  1. Make sure you’re using the EU Cookie Compliance module.
  2. Set the module up to your liking.
    This module will provide you with a customisable consent banner

Matomo Analytics

Matomo already provides you a setting to respect users with a “Do Not Track” (DNT) header set. But to also not bore those users with a cookie consent banner we need to do some adjustments.

Adjust the Matomo tracking code

To respect the “Do Not Track” (DNT) header we need to adjust the default Matomo tracking code snippet to check if the user is actually sending the DNT header. We can easily check this with:

navigator.doNotTrack // Returns 1 if user doesn't want to be tracked
// If browser sends DNT, automatically decline
if (navigator.doNotTrack) {
Drupal.eu_cookie_compliance.declineAction();
}
// If consent is not given
if (!Drupal.eu_cookie_compliance.hasAgreed()) {
_paq.push(['disableCookies']);
}
// If consent is given
if (Drupal.eu_cookie_compliance.hasAgreed()) {
_paq.push(['setConsentGiven']);
_paq.push(['rememberCookieConsentGiven']);
}
_paq.push(['requireCookieConsent']);
var idSite = SITEID; // Most likely ID 1
var matomoTrackingApiUrl = 'https://YOURMATOMOHOST/matomo.php';
var _paq = window._paq = window._paq || [];

_paq.push(['setTrackerUrl', matomoTrackingApiUrl]);
_paq.push(['setSiteId', idSite]);
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
_paq.push(['requireCookieConsent']);
// Check if user has given consent or not
document.addEventListener('DOMContentLoaded', function() {
// If browser sends DNT, automatically decline
if (navigator.doNotTrack) {
Drupal.eu_cookie_compliance.declineAction();
}
// If consent is not given
if (!Drupal.eu_cookie_compliance.hasAgreed()) {
_paq.push(['disableCookies']);
}
// If consent is given
if (Drupal.eu_cookie_compliance.hasAgreed()) {
_paq.push(['setConsentGiven']);
_paq.push(['rememberCookieConsentGiven']);
}
}, false);

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sascha Eggenberger

Sascha Eggenberger

Sascha Eggenberger. Senior Product Designer @GitLab. Drupal Core Maintainer. Drupal Design System, Claro, Gin. #OpenSource https://sascha.is/