SamKoucha.com

SamKoucha.com

Who am I?

Development tidbits


What I write about


Recent Posts

Google Analytics, Nuxt and Cookies (aka why I love GDPR)

You want to enable Google Analytics for a nuxt project. You also need to comply with GDPR and so you must disable it if a user wants to.

The Problem

You want to enable Google Analytics for a nuxt project. You also need to comply with GDPR and so you must disable it if a user wants to.

To make life simple you use two plugins, @nuxtjs/google-analytics to handle Google Analytics and nuxt-cookie-control to handle cookie permissions. BUT they don't work together out of the box and simple configuration won't do it either.

If someone else knows of a module or collection of modules that do this out of the box, please let me know!

So.... we need to enable or disable GA dynamically based upon the result of the cookie control dialog, which helpfully, are also cookies. To make manipulating cookies in nuxt easier I use cookie-universal-nuxt.

In our nuxt.config.js we have our modules property with nuxt-cookie-control and cookie-universal-nuxt;

modules: [
    /*Whatever else you have*/
    ['cookie-universal-nuxt', {alias: 'cookieUniversal'}],
    ['nuxt-cookie-control', { barPosition: 'bottom-left'}]
  ],

The alias for cookie-universal-nuxt is to prevent a namespace collision when using both modules. The cookie-universal-nuxt options are optional. To add the cookie control dialog, simply add the element to your layouts/default.vue as below

<template>
  <div>
    ...
    <CookieControl/>
  </div>
</template>

For @nuxtjs/google-analytics, we need two entries in our nuxt.config.json

buildModules: [
    '@nuxtjs/google-analytics'
  ],
googleAnalytics: {
    id: 'UA-123456789-1', //Your ID here
    beforeFirstHit (){
      if ($nuxt.$cookieUniversal.get('cookie_control_consent') && $nuxt.$cookieUniversal.get('cookie_control_enabled_cookies') === 'google-analytics'){
        $nuxt.$ga.enable();
      } else {
        $nuxt.$ga.disable();
      }
    }
},

buildModules is similiar to the modules entry above but offers a performance improvement over modules. Fortunately @nuxtjs/google-analytics allows us to use the buildModules. This is only available for nuxt versions > 2.9, otherwise just add it to the modules config.

The next entry is googleAnalytics which contain the settings for the GA module and the important bit. The beforeFirstHit() event handler.

The handler does as it says and enables you to call $ga.enable() or $ga.disable() to enable or disable GA for that request. One thing to note, I currently only have one value set in 'cookie_control_enabled_cookies' so that bit might need to be modified if you have multiple cookies set.

The end result at https://carcheck123.com.

Hope that helps

Sam