Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control Google Analytics tracking in Nuxt based on consent cookies?

I implemented Google Analytics tracking using @nuxtjs/google-analytics

I would now like to control whether or not the user is being tracked based on a consent given by the user. I found nuxt-cookie-control, which appears to allow collecting consent.

Based on the documentation for @nuxtjs/google-analytics // vue-analytics, it seems to just be a matter of calling this.$ga.disable() if a user does not give consent.

I noticed in some early fiddling efforts, however, that whenever I made a call to this.$ga.disable(), it did not seem to take effect beyond the next refresh.

The documentation also points out that "the opt-out needs to happen before trackers or queues are initialized."

I am a bit at a loss how/where in the application I would need to make the call to this.$ga.disable(). Can anyone give me pointers?

like image 340
matt_jay Avatar asked Nov 16 '22 04:11

matt_jay


1 Answers

here is my solution:

first of all i disabled google-analytics by defaut, so that no tracking takes place until the user has consented. i did this by setting the option disabled=true in nuxt.config.js. e.g.:

    googleAnalytics: {
        id: 'UA-xxxxxxxx-x',
        disabled: true,
    },

then i configured the accepted() callback in the cookies config in nuxt.config.js to enable google analytics, if consent is done:

        optional: [
            {
                name: 'Google Analytics',
                identifier: 'ga',
                description: '...',
                initialState: false,
                cookies: ['_ga', '_gat', '_gid'],
                accepted: () => {
                    window.$nuxt.$ga.enable() // Activate module
                    window.$nuxt.$ga.page(window.$nuxt.$route.path) // Track current route
                },
                declined: () => {
                    window.$nuxt.$cookies.remove('ga') // Remove any existing Google Analytics cookies
                },
            },
        ],

Finally we still need to enable google analytics on every following page refresh. I did this in the mount function of the default layout /layouts/default.vue:

import { onAnalyticsReady } from 'vue-analytics'

export default {
    mounted() {
        onAnalyticsReady().then(() => {
            const hasConsent = this.$cookies.isEnabled('ga')
            if (hasConsent) {
                this.$ga.enable() // Activate module
                this.$ga.page(this.$route.path) // Track current route
            }
        })
    },
}
</script>
like image 68
codeflorist Avatar answered Jun 18 '23 01:06

codeflorist