Skip to main content

Adding Klaro! Consent Manager to Docusaurus

· 2 min read
Stephan Hochdörfer
Head of IT Business Operations

When we migrated to Docusaurus in 2022, we were looking for options what consent management tool to use and how to integrate it into our Docusaurus setup.

We came across Klaro!, a consent management platform for third-party applications. What are Klaro's advantages? It's open-source, easy-to-use, extremely customizable, and adds a minimal footprint (37K) to Docusaurus. Also, integrating Klaro! in our Docusaurus setup was not too much effort.

First, let's add the Klaro! dependency via yarn:

yarn add klaro

Klaro! needs a configuration file to load all the settings. The configuration file is placed in src/components/assets/config.klaro.js. You can adapt the configuration to your needs:

const klaroConfig = {
version: 1,
elementID: 'klaro',
styling: {
theme: ['dark', 'right'],
green1: '#ff7300',
blue1: '#ff7300'
},
noAutoLoad: false,
htmlTexts: true,
embedded: false,
groupByPurpose: true,
storageMethod: 'cookie',
cookieName: 'klaro',
cookieExpiresAfterDays: 365,
default: false,
mustConsent: false,
acceptAll: true,
hideDeclineAll: false,
hideLearnMore: false,
noticeAsModal: false,
lang: 'en',
services: [
{
name: 'Matomo',
default: false,
title: 'Matomo',
purposes: ['analytics'],
cookies: [
[/^_pk_.*$/, '/', 'blog.bitexpert.de'],
],
callback: function(consent, service) {
// @TODO: Process consent here, e.g. load 3rd party JS
},
required: false,
optOut: false,
onlyOnce: true
}
]
};

export default klaroConfig;

The entire configuration file with all settings can be found in the Klaro! GitHub repository.

To make sure Klaro! is loaded on each Docusaurus page, we need to customize the src/theme/Layout/index.js page as follows:

  1. Add imports:
import React, {useEffect} from 'react';
import klaroConfig from "../components/assets/config.klaro";
  1. Add the useEffect() call to the LayoutWrapper function:
useEffect(() => {
const _paq = window._paq = window._paq || [];
if (window.enableTracking === true) {
_paq.push(['setCustomUrl', location.pathname]);
_paq.push(['setDocumentTitle', document.title]);
_paq.push(['trackPageView'])
}
import("klaro").then(Klaro => {
// we assign the Klaro module to the window, so that we can access it in JS
window.klaro = Klaro;
window.klaroConfig = klaroConfig;
Klaro.setup(klaroConfig);
// we set up Klaro with the config
const klaroCookie = window.document.cookie.match(new RegExp('(^| )klaro=([^;]+)'))
// if klaroCookie is set, take no further action
if (!klaroCookie) {
Klaro.show();
}
});
}, []);