Loading modules conditionally in Nuxt.js

In my Nuxt.js configuration, I have included a module for Google Tag Manager like this:

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

Everything is functioning properly, but I am curious about how to potentially load this module conditionally based on the value of a cookie that has been set by the website.

We offer users the ability to choose which cookies they want to accept or decline, including the option to block tracking scripts.

Is there a recommended approach for handling this situation with modules or scripts loaded through the configuration? It would be ideal if we could dynamically adjust this based on any changes in the cookie values in the future.

Any assistance or guidance on this matter would be greatly appreciated.

Answer №1

In order to conditionally execute GTM, you'll need to remove the @nuxtjs/google-tag-manager plugin and create your own implementation as a plugin. The NUXT documentation provides comprehensive guidelines on how to do this. I followed this resource to implement it, resulting in the following 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)
}

The approach involves enabling the user to set a custom cookie (disable-gtm in my case) and then verifying its presence in the gtm.js plugin. If the cookie exists and is valid, all GTM-related actions are skipped.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using React hooks to transfer an item from one array to another and remove it

export default function ShoppingCart() { const classes = useStyle(); const { productsList, filteredProductsList, setFilteredProductsList, setProductsList, } = useContext(productsContext); const [awaitingPaymentList, setAwaitingPaymentList] = us ...

Upon being provided with a route param, the response will be

For my current project using Express, I want to implement Reddit-like functionality where appending ".json" to any URL will return JSON data instead of the rendered template. To set up the rendering engine in Express, I am using Jade. Here is how I config ...

regex execution and testing exhibiting inconsistent behavior

The regex I am using has some named groups and it seems to match perfectly fine when tested in isolation, but for some reason, it does not work as expected within my running application environment. Below is the regex code that works everywhere except in ...

Material-UI: Avoid onClick event firing when clicking on an element that is overlapped by another in a sticky Table

I have a unique setup in my table where each row, including the header row, begins with a checkbox. This header row has a sticky property. As I scroll through the table, rows start to move behind the header row. If I try to click the checkbox in the heade ...

Typescript struggling to load the hefty json file

Currently, I am attempting to load a JSON file within my program. Here's the code snippet that I have used: seed.d.ts: declare module "*.json" { const value: any; export default value; } dataset.ts: import * as data from "./my.json" ...

Transmitting an HTML file along with JSON data and enabling the browser to refresh the JSON data without reloading the entire

I'm currently working on a project involving a browser-server program where the browser sends an http get request to ''. The server is expected to return both an HTML page and a JSON response. I attempted using res.render(), passing the JSON ...

Can you explain the concept of System.register in a JavaScript file?

Can you explain the purpose of System.register in a JS file when utilizing directives in Angular 2? ...

Finding all parent IDs from a given child ID within a nested JSON structure that contains children can be achieved by recursively

function loadKendoTreeView() { if ($("#treeview").data("kendoTreeView") != null) { $("#treeview").data("kendoTreeView").destroy(); $("#treeview").empty(); } var jsonData = [{ "Id": "239297d8-5993-42c0-a6ca-38dac2d8bf9f", ...

What is the process for integrating Android Java code with Node.js code?

I have some code that I am trying to integrate with Node.js for Firebase notifications on my Android application. I found a blog post outlining the implementation here: The Node.js code listens to changes in my Firebase Database and triggers notifications ...

Material UI TreeView: Organize and present node data with multiple columns in a tree structure

const treeItems = [ { id: 1, name: 'English', country: 'US', children: [ { id: 4, name: 'Spring', country: 'Uk', ...

Tips for importing an external JavaScript file and accessing its data within a ReactJS project?

Currently, I am working on a React project using create-react-app. My objective is to load an external JavaScript file (hosted in IIS) and utilize the data it contains. To fetch this file, I am including a script in my index.html like so: <script type ...

Is it possible to track traffic using Alexa or SimilarWeb on a single-page application?

We are currently grappling with the challenge of how to effectively track traffic and user engagement within our classified sites on a single-page application built in angularJS. While we have successfully managed SEO and tracking with Google Analytics, we ...

Update: "Mui V5 - Eliminate collapse/expand icons in TreeView and reduce TreeItem indentation"

My current project involves Mui V5 and I am looking to customize the TreeView component. Specifically, I need to remove the collapse/expand icons as I want them to be integrated into the TreeItem label component on the left side instead of the right. Add ...

Using more than one submit button in an HTML form

I am attempting to include multiple buttons on a single form. I would like to perform different actions on the form depending on which submit button is clicked. <script type="text/javascript> $("#<portlet:namespace/>Form").submit(function( ...

Encountering problems with createMediaElementSource in TypeScript/React when using the Web Audio API

Currently, I am following a Web Audio API tutorial from MDN, but with a twist - I am using TypeScript and React instead of vanilla JavaScript. In my React project created with create-react-app, I am utilizing the useRef hook to reference the audio element ...

Use a dropdown menu to update the selected value

Issue with displaying drop down values in the second list, despite trying various solutions. When a user selects a country, the corresponding state should be populated from the database into the second drop-down. Any assistance would be greatly appreciated ...

Having trouble with setting up the next image configuration for graphcms' images

I've been using graphcms solely for my image assets and trying to integrate them into my Next JS (v12.0.1) frontend. However, I keep getting the error message hostname not configured in next.config.js, even though I have already specified it in my nex ...

Puppeteer throwing an error when querying selectors cannot be done (TypeError: selector.startsWith is not a supported function)

I recently installed Puppeteer and ran into an issue when trying to query a selector. I keep receiving a TypeError: selector.startsWith is not a function error. I attempted to resolve the problem by tweaking the core code and adding toString(), but unfort ...

Items that have been moved in the Vuetify Treeview are unable to be selected when clicking on the parent node

After successfully moving selected treeview items to another parent, I have encountered an issue where the moved items are no longer selectable when clicking on their new parent node. To reproduce this issue, follow these steps: Select node2_item1 Click ...

Unable to retrieve the value of a textbox located within a gridview

In my grid view, I have a textbox nested inside a TemplateField. I want to retrieve the value of this textbox when a button is clicked: This is where I create the textbox: <ItemTemplate> <asp:TextBox runat="server" ID="txtEmail" Text=&a ...