Adding Google Tag Manager
NO LONGER GDPR COMPLIANT from 01/07/2023
Starting from 01/07/2023, Google is sunsetting the Universal Analytics (UA) platform. This means that the current implementation of Google Tag Manager needs to use the GA4 version of Google Analytics. This version is not GDPR compliant and will need to be replaced with a different solution. For more information about the compliance issues check this article.
We upgrading to the vue-gtm library.
Introduction
The convention within Xerius is to always use Google Tag Manager. Tag manager will inject the scripts to start up Google analytics. This will make sure Marcom has full control over what is being tracked and doesn't need developer intervention to make changes. Piwik pro is used for the tracking behind the screens and expects certain events to be pushed to the Google Tag Manager. It will also take the cookie consents in account for the tracking.
Using with Vue 3
We recommend using the vue-gtm library. Make sure to check that you install the Vue 3.x version. Implementing GTM will be easier with this library, it also allows integrating with the Cookiebot implementation if this is needed.
Piwik does not expect the default page_view
event, but a custom virtual_page_view
event. This makes linking the GTM container with the Vue router to track page views automatically unneeded. You will need to fire the events manually with virtual_page_view
as event name.
Install the package with:
npm install @gtm-support/vue-gtm
Firstly, we need to setup the GTM library which can be done in the main.ts
file. Here is a example configuration, we only need to add the GTM ID since we would like to have the script injected and enabled by default.
import { createGtm } from '@gtm-support/vue-gtm'
app.use(
createGtm({
id: 'GTM-XXXXXX'
})
)
Most of the times you will need to fetch the GTM container ID from your config file. It is possible to use the fechtConfig()
function from the use-config
composable from Codey. This can also be done inside the main.ts
file. Once you have fetched the config you can use it to grab the googleTagManagerContainer
ID. Here is an example:
import { createGtm } from '@gtm-support/vue-gtm'
import { fetchConfig } from '@xerius/codey-composables/use-config'
fetchConfig()
.then((config) => {
app.use(
createGtm({
id: config.googleTagManagerContainer as string
})
)
})
.finally(() => {
app.mount('#app')
})
This will setup the GTM module but it's still required to fire events manually, since we need to use virtual_page_event
with a few params for Piwik.
We can fire events when a button is clicked for example, or when the user navigates to an other page. Firing an event can be done as following: (Note that the check if gtm is enalbed is not always necessary.)
const gtm = useGtm()
if (gtm.enabled()) {
gtm.trackEvent({
event: 'virtual_page_view',
vpp: '/<language_country>/opstart-eenmanszaak/<virtual_dom_state>/'
})
}
More information can be found in the documentation of the GTM library.
Using with Vue 2
We recommend using the vue-gtm library. Make sure to check that you install the Vue 2.x version. Implementing GTM will be easier with this library, it also allows integrating with the Cookiebot implementation if this is needed.
It is possible to have the page views automatically tracked by linking the Vue router to the initial options. But this isn't needed because Piwik will expect a different event, virutal_page_view
. More about this later on.
Install the package with:
npm install @gtm-support/vue2-gtm
Firstly, we need to setup the GTM library which can be done in the main.js
file or a seperate file like init-gtm.js
depending on your setup. Here is a example configuration, we only need to add the GTM ID since we would like to have the script injected and enabled by default.
Vue.use(VueGtm, {
id: 'GTM-XXXXX',
});
It's possible to wrap this config inside an Axios call that will fetch the GTM id from a config.
Axios.get(`${process.env.VUE_APP_PUBLIC_PATH}config.json`, {
headers: { 'Cache-Control': 'no-cache' }
}).then((res) => {
Vue.use(VueGtm, {
id: res.data.googleTagManagerContainer
});
});
This will setup the GTM module but it's still required to fire events manually, since we need to use virtual_page_event
with a few params for Piwik.
We can fire events when a button is clicked for example, or when the user navigates to an other page. Firing an event can be done as following: (Note that the check if gtm is enalbed is not always necessary.)
if (Vue.gtm?.enabled()) {
Vue.gtm.trackEvent({
event: 'virtual_page_view',
vpp: '/<language_country>/opstart-eenmanszaak/<virtual_dom_state>/'
})
}
More information can be found in the documentation of the GTM library.
Debugging
During the configuration of the GTM module, there is an option debug
which you can set to true
to display console logs debugs. This can be used to see if the GTM is setup correctly and is enabled or not. It also displays events that are pushed.
Vue.use(VueGtm, {
id: 'GTM-XXXXX',
debug: true // Whether or not display console logs debugs (optional, default = false)
});
Any events that are pushed will be pushed thanks to the dataLayer
, it's possible to look into this by using window.dataLayer
, in the console or code for example.
There is also an option to install a plugin in your Chromium based browser to debug analytic trackers, we do recommend using Analytics Debugger.
Inside the Google Tag Manager site, there is an option to preview the tags and triggers. This allows you to open your local or deployed application and see which tags are getting triggered.
When using Nuxt
No longer maintained
As we are dropping support for Nuxt from codey packages, this setup is no longer tested or maintained.
We recommend using the @nuxtjs/gtm library. This library will make it easier to integrate with the Cookiebot implementation. Page views will be automatically tracked when setting up the library.
Firstly, we need to setup the GTM module within Nuxt. Add the module under buildModules and the following option to your nuxt.config.js file.
// nuxt.config.js
import Vue from "vue";
export default {
buildModules: ["@nuxtjs/gtm"],
gtm: {
id: "GTM-XXXXXXX",
pageTracking: true,
pageViewEventName: "page_view",
autoInit: false,
scriptDefer: true,
},
};
More information on the configurable options can be found in the GTM library documentation
Integration with Cookiebot
The next step will be to initialize the GTM library when statistics cookies are accepted.
// plugins/codey-cookiebot.client.js
import { setupCookiebot } from "@xerius/codey-cookiebot";
export default ({ app, $gtm }) => {
setupCookiebot({
cbid: COOKIEBOT_CBID,
onStatisticsAccept: () => {
// now start GTM
$gtm.init();
},
});
};
Pushing Events to GTM
Events can be sent by using the global $gtm instance. More information on the events can be found here.
this.$gtm.push({ event: "myEvent", ...someAttributes });
When using Angular
We recommend using the angulartics2 library. This is the most popular choice and will be easy to setup. It's best to floow the installation instructions on this URL. Virtual page views will be automatically tracked.
import { Angulartics2GoogleTagManager } from "angulartics2/gtm";
function initGoogleTagManager() {
const containerId = GTM_CONTAINER_ID;
const windowRef = window as any;
const document = window.document;
const dataLayer = 'dataLayer';
windowRef[dataLayer] = windowRef[dataLayer] || [];
windowRef[dataLayer].push({
'gtm.start': new Date().getTime(),
event: 'gtm.js'
});
const f = document.getElementsByTagName('script')[0];
const j = document.createElement('script');
j.async = true;
j.src = `https://www.googletagmanager.com/gtm.js?id=${containerId}>m_auth=${GTM_AUTH}>m_preview=${GTM_ENV}`;
if (f.parentNode) {
f.parentNode.insertBefore(j, f);
}
const head = document.getElementsByTagName('head')[0];
head.appendChild(f);
}
setupCookiebot({
cbid: COOKIEBOT_CBID, // Xerius domain group id
autoBlockingMode: false,
onStatisticsAccept: () => {
initGoogleTagManager();
this.angulartics2GoogleTagManager.startTracking();
},
});
When using no framework
When your application does not contain a frontend framework, please follow the guide here. To account for the usage of Cookiebot, we need to mark the GTM script with attribute data-cookieconsent="ignore".
This will make sure that GTM is allowed to execute the script. Google Analytics will however still be blocked before the user accepts this category of cookies.