Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional module loading in Nuxt.js

I have a module for Google Tag Manager in my Nuxt.js config, like so:

modules: [
  [
    '@nuxtjs/google-tag-manager',
    {
      id: 'GTM-XXXXXXX'
    }
  ]
]

This is working fine but I am wondering how I can conditionally load this module based on the value of a cookie set by the site?

We have a mechanism by which the user can select certain cookies to accept or deny and a part of that is to block tracking scripts.

Is there any recommended way to do this with modules or scripts loaded via the config? Ideally, it would be possible to then load these should the values within the cookies change in the future as well.

Any help or pointers are greatly appreciated.

like image 837
Michael Giovanni Pumo Avatar asked Feb 06 '19 16:02

Michael Giovanni Pumo


1 Answers

To execute GTM conditionally you have to drop the @nuxtjs/google-tag-manager and implement it yourself as a plugin. NUXT docs are really awesome and have you covered on this too. I used this resource for implementation and ended up with this code:

// app/plugins/gtm.js

import Cookies from 'js-cookie'

const gtmKey = 'GTM-XXXXX' // <- insert your GTM key here

export default () => {
  /*
  ** Only run on client-side and only in production mode
  */
  if (process.env.NODE_ENV !== 'production') return
  /*
  ** Only run if it's not prevented by user
  */
  if (Cookies.get('disable-gtm')) return
  /*
  ** Include Google Tag Manager
  */
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
      new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
    j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
    'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
  })(window,document,'script','dataLayer', gtmKey)
}

Basically you allow the user to set a custom cookie (disable-gtm in my case) and check this cookie in the gtm.js plugin. If it's there and valid, skip everything GTM related.

like image 143
Paul Geisler Avatar answered Oct 24 '22 13:10

Paul Geisler