Giter VIP home page Giter VIP logo

nuxt-gtag's Introduction

Nuxt Google Tag module

Nuxt Google Tag

npm version

Google Tag integration for Nuxt with support for Google Analytics 4, Google Ads and more.

Features

  • 🌻 Zero dependencies except Google's gtag.js
  • 🛍️ Use Google Analytics 4, Google Ads and other products
  • 🛎️ Supports Google Consent Mode v2
  • 🤝 Manually initialize a Google tag
  • 🔢 Supports multiple tag IDs
  • 📯 Track events with composables
  • 🏷️ Fully typed gtag.js API
  • 🦾 SSR-ready

Setup

npx nuxi@latest module add gtag

Basic Usage

Add nuxt-gtag to the modules section of your Nuxt configuration and provide your Google tag ID (for multiple tag IDs, see below).

export default defineNuxtConfig({
  modules: ['nuxt-gtag'],

  gtag: {
    id: 'G-XXXXXXXXXX'
  }
})

Done! The gtag.js script will be loaded and initialized client-side with your Google tag ID when the Nuxt application starts.

Note

Ensure that the Enhanced measurement feature is enabled to allow gtag.js to automatically track page changes based on browser history events in Nuxt.

To enable this feature:

  1. Go to the GA4 reporting view and click on “Admin”
  2. Select “Data Streams” under the “Property” column.
  3. Click on your web data stream.
  4. Next, toggle the switch button near “Enhanced measurement”.

Configuration

All supported module options can be configured using the gtag key in your Nuxt configuration. An example of some of the options you can set:

export default defineNuxtConfig({
  modules: ['nuxt-gtag'],

  gtag: {
    // Your primary Google tag ID
    id: 'G-XXXXXXXXXX',
    // Additional configuration for this tag ID
    config: {
      page_title: 'My Custom Page Title'
    },
  }
})

Multiple Google Tags

If you want to send data to multiple destinations, you can add more than one Google tag ID to your Nuxt configuration in the tags module option. Pass a string (single tag ID) or an object (tag ID with additional configuration) to the tags array.

The following example shows how to load a second Google tag that is connected to a Floodlight destination:

export default defineNuxtConfig({
  modules: ['nuxt-gtag'],

  gtag: {
    tags: [
      // Google Ads and GA4, with additional configuration
      {
        id: 'G-XXXXXXXXXX',
        config: {
          page_title: 'My Custom Page Title'
        }
      },
      // Second Google tag ID for Floodlight
      'DC-ZZZZZZZZZZ'
    ]
  }
})

Runtime Config

Instead of hard-coding your Google tag ID in your Nuxt configuration, you can set your desired option in your project's .env file, leveraging automatically replaced public runtime config values by matching environment variables at runtime.

# Overwrites the `gtag.id` module option
NUXT_PUBLIC_GTAG_ID=G-XXXXXXXXXX

With this setup, you can omit the gtag key in your Nuxt configuration if you only intend to set the Google tag ID.

Google Consent Mode

Tip

Follows the Google Consent Mode v2 specification.

Set a default value for each consent type you are using. By default, no consent mode values are set.

The following example sets multiple consent mode parameters to denied by default:

export default defineNuxtConfig({
  modules: ['nuxt-gtag'],

  gtag: {
    id: 'G-XXXXXXXXXX',
    initCommands: [
      // Setup up consent mode
      ['consent', 'default', {
        ad_user_data: 'denied',
        ad_personalization: 'denied',
        ad_storage: 'denied',
        analytics_storage: 'denied',
        wait_for_update: 500,
      }]
    ]
  }
})

After a user indicates their consent choices, update relevant parameters to granted:

function allConsentGranted() {
  const { gtag } = useGtag()
  gtag('consent', 'update', {
    ad_user_data: 'granted',
    ad_personalization: 'granted',
    ad_storage: 'granted',
    analytics_storage: 'granted'
  })
}

function consentGrantedAdStorage() {
  const { gtag } = useGtag()
  gtag('consent', 'update', {
    ad_storage: 'granted'
  })
}

// Invoke the consent function when a user interacts with your banner
consentGrantedAdStorage() // Or `allConsentGranted()`

Manually Load gtag.js Script

For even more control than the consent mode, you can delay the loading of the gtag.js script until the user has granted consent to your privacy policy. Set the enabled option to false to prevent loading the gtag.js script until you manually enable it:

export default defineNuxtConfig({
  modules: ['nuxt-gtag'],

  gtag: {
    enabled: false,
    id: 'G-XXXXXXXXXX'
  }
})

To manually load the Google tag script, i.e. after the user has accepted your privacy policy, you can use the initialize method destructurable from useGtag:

<script setup lang="ts">
const { gtag, initialize } = useGtag()
</script>

<template>
  <button @click="initialize()">
    Grant Consent
  </button>
</template>

Multi-Tenancy Support

You can even leave the Google tag ID in your Nuxt config blank and set it dynamically later in your application by passing your ID as the first argument to initialize. This is especially useful if you want to use a custom ID for each user or if your app manages multiple tenants.

const { gtag, initialize } = useGtag()

function acceptTracking() {
  initialize('G-XXXXXXXXXX')
}

Module Options

Option Type Default Description
enabled boolean true Whether to initialize the Google tag script immediately after the page has loaded.
id string undefined The Google tag ID to initialize.
initCommands See initCommands of GoogleTagOptions [] Commands to be executed when the Google tag ID is initialized.
config See config of GoogleTagOptions {} The configuration parameters to be passed to gtag.js on initialization.
tags string[] | GoogleTagOptions[] [] Multiple Google tag IDs to initialize for sending data to different destinations.
loadingStrategy 'async' | 'defer' 'defer' The loading strategy to be used for the gtag.js script.
url string Source The URL to the gtag.js script. Use this option to load the script from a custom URL.

Composables

As with other composables in the Nuxt 3 ecosystem, they are auto-imported and can be used in your application's components.

useGtag

The SSR-safe useGtag composable provides access to:

  • The gtag.js instance
  • The initialize method
  • The disableAnalytics method
  • The enableAnalytics method

It can be used as follows:

// Each method is destructurable from the composable and can be
// used on the server and client-side
const { gtag, initialize, disableAnalytics, enableAnalytics } = useGtag()

Type Declarations

function useGtag(): {
  gtag: Gtag
  initialize: (id?: string) => void
  disableAnalytics: (id?: string) => void
  enableAnalytics: (id?: string) => void
}

gtag

The gtag function is the main interface to the gtag.js instance and can be used to run every gtag.js command.

Note

Since the gtag.js instance is available in the client only, any gtag() calls executed on the server will have no effect.

Example

The following event command fires the event screen_view with two parameters: app_name and screen_name.

const { gtag } = useGtag()

// SSR-ready
gtag('event', 'screen_view', {
  app_name: 'My App',
  screen_name: 'Home'
})

Type Declarations

interface GtagCommands {
  config: [targetId: string, config?: ControlParams | EventParams | ConfigParams | CustomParams]
  set: [targetId: string, config: CustomParams | boolean | string] | [config: CustomParams]
  js: [config: Date]
  event: [eventName: EventNames | (string & {}), eventParams?: ControlParams | EventParams | CustomParams]
  get: [
      targetId: string,
      fieldName: FieldNames | string,
      callback?: (field?: string | CustomParams) => any,
  ]
  consent: [consentArg: ConsentArg | (string & {}), consentParams: ConsentParams]
}

const gtag: {
  <Command extends keyof GtagCommands>(command: Command, ...args: GtagCommands[Command]): void
}

initialize

If you want to manually manage the initialization of the Google tag script, i.e. for GDPR compliance, you can use the initialize method to inject the gtag.js script to the document's head after the user has accepted your privacy policy. Make sure to set enabled to false in the Nuxt module for this to work.

The function accepts an optional ID in case you want to initialize a custom Google tag ID, which isn't set in the module options.

Example

const { initialize } = useGtag()

// Load the `gtag.js` script and initialize all tag IDs from the module options
initialize()

Tip

Although this method is SSR-safe, the gtag.js script will be loaded in the client only. Make sure to run this method in the client.

Type Declarations

function initialize(id?: string): void

disableAnalytics

In some cases, it may be necessary to disable Google Analytics without removing the Google tag. For example, you might want to provide users with the option to opt out of tracking.

The gtag.js library includes a window property that, toggles gtag.js from sending data to Google Analytics. When Google Analytics attempts to set a cookie or send data back to the Google Analytics servers, this property is checked to determine whether to allow the action.

Example

const { disableAnalytics } = useGtag()

disableAnalytics()

Type Declarations

function disableAnalytics(id?: string): void

enableAnalytics

The enableAnalytics method is the counterpart to disableAnalytics and can be used to re-enable Google Analytics after it has been disabled.

Example

const { enableAnalytics } = useGtag()

enableAnalytics()

Type Declarations

function enableAnalytics(id?: string): void

useTrackEvent

Track your defined goals by passing the following parameters:

  • The name of the recommended or custom event.
  • A collection of parameters that provide additional information about the event (optional).

Note

This composable is SSR-ready. But since the gtag.js instance is available in the client only, executing the composable on the server will have no effect.

Example

For example, the following is an event called login with a parameter method:

// Tracks the `login` event
useTrackEvent('login', {
  method: 'Google'
})

Type Declarations

function useTrackEvent(
  eventName: EventNames | (string & {}),
  eventParams?: ControlParams | EventParams | CustomParams
): void

💻 Development

  1. Clone this repository
  2. Enable Corepack using corepack enable
  3. Install dependencies using pnpm install
  4. Run pnpm run dev:prepare
  5. Start development server using pnpm run dev

Credits

License

MIT License © 2023-PRESENT Johann Schopplich

nuxt-gtag's People

Contributors

danielroe avatar johannschopplich avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

nuxt-gtag's Issues

Data not collecting in SSG mode

First off, awesome plugin - so easy to install and get started!

I installed and configured with just the basic settings. Data instantly started collecting when running my site in development mode. However, when I use static site generation to render and publish a static site, data is not collecting on the output site.

Here's what my config looks like.

import i18nConfig from './config/i18nConfig'
import svgLoader from 'vite-svg-loader'

export default defineNuxtConfig({
    app: {
        head: {
            link: [{ rel: "icon", href: "/favicon.ico", sizes: "32x32" }],
            link: [{ rel: "icon", href: "/icon.svg", type: "image/svg+xml" }],
            link: [{ rel: "apple-touch-icon", href: "/apple-touch-icon.png" }],
            link: [{ rel: "manifest", href: "/manifest.webmanifest" }],
        },
    },
    build: {
        transpile: [
            "markdown-it",
            "vuetify",
        ],
    },
    css: [
        'vuetify/lib/styles/main.sass',
    ],
    // debug: true,
    experimental: {
        // important!! inlineSSRStyles must be false to allow for custom styles to be applied to vuetify components
        // Vuetify configFile styles and Nuxt inlineSSRStyles are incompatible
        inlineSSRStyles: false,
        payloadExtraction: process.env.APP_USE_SSR == 'TRUE' ? true : false,
    },
    hooks: {
        // if needed, add hook for pre-rendering routes that crawler can't find
    },
    gtag: {
        id: 'G-xxxxxxx',
    },
    i18n: {
        /* module options */
        customRoutes: 'config',
        ...i18nConfig,
        lazy: false,
        langDir: "locales",
        strategy: "prefix_and_default",
        defaultLocale: "en",
        vueI18n: './config/nuxtVuei18nConfig',
    },
    // Modules: https://go.nuxtjs.dev/config-modules
    modules: [
        '@nuxtjs/i18n',
        '@pinia/nuxt',
        '@vueuse/nuxt',
        'nuxt-gtag',
        'vuetify-nuxt-module',
    ],
    nitro: {
        baseURL: "",
        prerender: {
            crawlLinks: false,
        },
        static: process.env.APP_USE_SSR == 'TRUE' ? true : false,
    },
    runtimeConfig: {
        public: {
            awsSettings: require(`.${process.env.APP_CONFIG_ROOT}/aws-exports.js`),
            ssr: process.env.APP_USE_SSR == 'TRUE' ? true : false,
        },
    },
    sourcemap: {
        server: true,
        client: true,
    },
    // conditionally set ssr setting depending on environment
    ssr: process.env.APP_USE_SSR == 'TRUE' ? true : false,
    vuetify: {
        moduleOptions: {
            /* module specific options */
            styles: { configFile: '/settings.scss' }
        },
        vuetifyOptions: './vuetify.config.ts',
    },
    vite: {
        plugins: [
            svgLoader({}),
        ],
    },
})

For my generated site, the environment variable APP_USE_SSR is set to TRUE

Is there something I need to configure differently in order for tracking to take place with SSG rendered pages? Do I need to turn off SSR for static generated pages?

Thanks for any help!

Persist consent state in session

Environment

  • Operating System: Linux
  • Node Version: v20.5.1
  • Nuxt Version: 3.10.3
  • CLI Version: 3.10.1
  • Nitro Version: 2.9.0
  • Package Manager: [email protected]
  • Builder: -
  • User Config: -
  • Runtime Modules: -
  • Build Modules: -

Reproduction

First consent mode default
image

Cookie banner acept partial consent
image

But when we navigate, there is a toxic consent that we havent triggered!!
image

There is a bug in the module??? Module throws this event???

Describe the bug

First consent mode default
image

Cookie banner acept partial consent
image

But when we navigate, there is a toxic consent that we havent triggered!!
image

There is a bug in the module??? Module throws this event???

Additional context

No response

Logs

No response

Feature Request: Ads with Google Publisher Tag (GPT)

Firstly, I would like to express my gratitude and extend my sincerest thanks to you.

Your module for Nuxt 3 is absolutely fantastic!

Secondly, I was wondering if there is a possibility to utilize it for the integration of "Google Publisher Tag" ads within Nuxt?"

`useGtagConsent(true)` should initialize the Gtag script

Environment

Reproduction

https://stackblitz.com/edit/github-vihbux?file=app.vue

Describe the bug

Hello,

When I use the useGtagConsent() function and set it to true after clicking a button, it does not insert the script into the head which means that events aren't sent to Google Analytics. if you place the useGtagConsent(true) in onMounted of the component, it will insert the script into the head though but I only want to insert the script if the user clicks an accept button.

Additional context

No response

Logs

No response

Uncaught TypeError: `gtag` is not a function

Environment

  • Operating System: Darwin
  • Node Version: v18.13.0
  • Nuxt Version: 3.6.1
  • Nitro Version: 2.5.1
  • Package Manager: [email protected]
  • Builder: vite
  • User Config: runtimeConfig, app, modules, devtools, imports, css, postcss, auth, gtag, routeRules, build
  • Runtime Modules: @sidebase/[email protected], [email protected]
  • Build Modules: -

Reproduction

https://stackblitz.com/edit/github-j7dume?file=app.vue

Describe the bug

The module works with normal tracking events, but calling gtag() from const { gtag } = useGtag() returns 'Uncaught TypeError: gtag is not a function'

Additional context

I had a brief poke around in the module's composables, but can't see anything obvious...

Logs

Uncaught TypeError: gtag is not a function

Destructured method `gtag` is `undefined`

Environment

Nuxt 3.3.3
Nuxt-gtag: 2.0.4

Reproduction

Unfortunately I cannot. My project is big and I couldn't reproduce it with minimal example :(

Describe the bug

When trying to use gtag, it is null.

image

Thanks for the help.

Additional context

The network request looks fine:
image

modules: [
        '@vueuse/nuxt',
        ['@pinia/nuxt',
            {
                autoImports: ['defineStore', 'acceptHMRUpdate'],
            },
        ],
        '@nuxtjs/i18n',
        '@unocss/nuxt',
        '@nuxtjs/tailwindcss',
        '@formkit/nuxt',
        '@funken-studio/sitemap-nuxt-3',
        '@nuxt/image',
        'nuxt-gtag',
        (_options, nuxt) => {
            nuxt.hooks.hook('vite:extendConfig', (config) => {
                // @ts-expect-error
                config.plugins.push(vuetify({autoImport: true}))
            })
        },
    ],
    gtag: {
        id: 'G-XXXXX',
    },
"scripts": {
    "build": "nuxt build",
    "dev": "nuxt dev",
    "generate": "nuxt generate",
    "preview": "nuxt preview"
  },
"devDependencies": {
    "@iconify-json/fa": "^1.0.1",
    "@iconify-json/ic": "^1.1.3",
    "@iconify-json/logos": "^1.0.4",
    "@iconify-json/mdi": "^1.0.12",
    "@nuxtjs/i18n": "8.0.0-beta.9",
    "@nuxtjs/tailwindcss": "^6.1.3",
    "@pinia/nuxt": "0.5.1",
    "@tailwindcss/typography": "0.5.10",
    "@unocss/nuxt": "^0.58.0",
    "@unocss/transformer-variant-group": "^0.58.0",
    "nuxt": "3.3.3",
    "nuxt-gtag": "^2.0.4",
    "vite-plugin-vuetify": "^2.0.2",
    "vuetify": "^3.5.7"
  },
  "dependencies": {
    "@fawmi/vue-google-maps": "0.9.72",
    "@formkit/icons": "^1.5.9",
    "@formkit/nuxt": "^1.5.9",
    "@formkit/themes": "^1.5.9",
    "@fortawesome/fontawesome-svg-core": "^6.4.0",
    "@fortawesome/free-brands-svg-icons": "^6.4.0",
    "@fortawesome/free-solid-svg-icons": "^6.4.0",
    "@fortawesome/vue-fontawesome": "^3.0.3",
    "@funken-studio/sitemap-nuxt-3": "^4.0.4",
    "@headlessui/vue": "1.7.16",
    "@iconify-json/twemoji": "1.1.5",
    "@mdi/font": "^7.4.47",
    "@nuxt/image": "^1.1.0",
    "@tailwindcss/forms": "^0.5.7",
    "@unocss/preset-icons": "^0.58.5",
    "@unocss/preset-typography": "^0.58.5",
    "@unocss/preset-uno": "^0.58.5",
    "@vueuse/nuxt": "^10.9.0",
    "axios": "^0.26.1",
    "dayjs": "^1.11.6",
    "fast-geoip": "^1.1.59",
    "gpx-builder": "^3.4.0",
    "i18n-iso-countries": "^7.5.0",
    "idle-timeout": "^2.0.1",
    "lodash-es": "^4.17.21",
    "mande": "^2.0.1",
    "moment": "^2.29.4",
    "pinia": "^2.1.7",
    "request-ip": "^3.3.0",
    "swiper": "^8.4.4",
    "vue-loading-overlay": "^6.0.4",
    "vue-select": "^4.0.0-beta.6",
    "vue-toastification": "^2.0.0-rc.5"
  }

Logs

No response

Option to exclude route(s)?

Describe the feature

I'm looking to implement GTag and am running in to issues getting vue-gtag to exclude routes (even though they supposedly have the option).

Does this library offer that sort of functionality? I'm personally only needing to exclude one single route, however I'm sure the ability to exclude wildcard paths (e.g. /blog/*) would also be helpful to others.

Thanks!

Additional information

  • Would you be willing to help implement this feature?
  • Can you think of other implementations of this feature?

Final checks

'Reduce unused JavaScript' suggestions?

Environment


  • Operating System: Linux
  • Node Version: v18.19.1
  • Nuxt Version: -
  • CLI Version: 3.11.1
  • Nitro Version: -
  • Package Manager: unknown
  • Builder: -
  • User Config: -
  • Runtime Modules: -
  • Build Modules: -

Running within Docker

Reproduction

Currently none, installed nuxt-gtag and added to the module

Describe the bug

image

Currently this shows up in lighthouse as 'Unused JavaScript', while the loadingStrategy is set to 'defer', with 'async' we're getting the same issue.

Is there any way to prevent this, as it's pulling our performance score down on mobile. Thanks!

Additional context

No response

Logs

No response

Error: `useHead` is not defined

I am getting this error on my Nuxt3 platform:

[nuxt] error caught during app initialization Refer
Screenshot 2023-05-13 at 12 27 28 PM
enceError: useHead is not defined

useTrackEvent typing improvement

Describe the feature

useTrackEvent doesn't have the same typing as the useGtag()('event', ....nicely typed args)

I tried to implement this but didn't get far with it. Not easy when I only have the GTag type to work with.

import type { Gtag } from '../types'
import { useGtag } from './useGtag'

type Event = Gtag | ((command: 'event') => never)
type OmitCommandParameter<T> = T extends (command: 'event', ...rest: infer R) => void ? (...args: R) => void : never

export function useTrackEvent(
  eventName: Parameters<OmitCommandParameter<Event>>[0],
  eventParams?: Parameters<OmitCommandParameter<Event>>[1],
) {
  const { gtag } = useGtag()
  gtag('event', eventName, eventParams)
}

Perhaps other types can be exported too?
It would make sense in case someone constructs the arguments outside of a function call.

Additional information

  • Would you be willing to help implement this feature?
  • Can you think of other implementations of this feature?

Final checks

No data collected

Environment

{
"private": true,
"scripts": {
"build": "nuxt build",
"dev": "nuxt dev",
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare"
},
"devDependencies": {
"nuxt": "^3.2.3",
"primeflex": "3.2.1",
"primeicons": "5.0.0",
"primevue": "^3.25.0"
},
"dependencies": {
"@pinia/nuxt": "^0.4.4",
"bootstrap": "^5.2.3",
"mixpanel-browser": "^2.47.0",
"nuxt-gtag": "^0.5.7",
"sass": "^1.56.1"
}
}

Reproduction

used both yarn and pnpm and yarn do to add nuxt-gtag, front renders the gtag configuration, but does not add page view script. tried to add view script manually but still no change within analytics, no data collected, source here https://calculatrices-klosup-lrm.fr/calculatrices-2023/cloture-horizontale-simple/

window.NUXT={serverRendered:false,config:{public:{gtag:{id:"G-QxxxxxxxY",config:{},initialConsent:true,loadingStrategy:"defer"}}

Describe the bug

not collecting data at all (similar to #11, except won't collect on other pages)

Additional context

No response

Logs

No response

Browser Console Error: Uncaught ReferenceError: defineNuxtPlugin is not defined

Environment


  • Operating System: Windows_NT
  • Node Version: v16.18.1
  • Nuxt Version: 3.2.3
  • Nitro Version: 2.3.1
  • Package Manager: [email protected]
  • Builder: vite
  • User Config: -
  • Runtime Modules: -
  • Build Modules: -

Reproduction

export default defineNuxtConfig({
  modules: ['nuxt-gtag'],

  gtag: {
    id: 'G-XXXXXXXXXX'
  }
})

Describe the bug

GTag doesn't work. On browser console I see this error:

Uncaught ReferenceError: defineNuxtPlugin is not defined
at plugin.client.mjs?v=54cefaf0:1:1

You should probably add this to plugin.client.ts

import { defineNuxtPlugin, useRuntimeConfig } from "#app";

Additional context

No response

Logs

No response

Nuxt 2 compatibility

Environment

Local

Reproduction

In Nuxt config:

gtag: {
  id: "AW-***************",
  initialConsent: false,

  config: {
    page_title: "********",
    pageTrackerScreenviewEnabled: true,
  },
},
modules: [
  "nuxt-gtag",
],

In Vue File (Nuxt):

const { gtag } = useGtag();

gtag("event", "conversion", {
send_to: "AW-****************/FdYvCL6qm90YEMW-v_wp",
});

Describe the bug

Error when using the nuxt-gtag.
Error is - ReferenceError: useGtag is not defined

Please, how can I use the plugin successfully? I keep getting the error.

Additional context

This is a Nuxt project. With the following version numbers:

"nuxt": "^2.15.8",
"vue": "^2.6.14",

"nuxt-gtag": "^1.1.0"

Logs

This is the long when I attempt to mount on the page where I import and use useGtag():

client.js:103 ReferenceError: useGtag is not defined
    at eval (completed-form.vue:8:1)
    at ./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./node_modules/string-replace-loader/index.js?!./pages/contact/completed-form.vue?vue&type=script&lang=js& (completed-form.js:22:1)
    at __webpack_require__ (runtime.js:854:30)
    at fn (runtime.js:151:20)
    at eval (completed-form.vue:1:1)
    at ./pages/contact/completed-form.vue?vue&type=script&lang=js& (completed-form.js:80:1)
    at __webpack_require__ (runtime.js:854:30)
    at fn (runtime.js:151:20)
    at eval (completed-form.vue:1:1)
    at ./pages/contact/completed-form.vue (completed-form.js:68:1)

Uncaught TypeError: Cannot read properties of undefined (reading 'update')

Environment

  • Operating System: Darwin
  • Node Version: v20.9.0
  • Nuxt Version: 3.10.2
  • CLI Version: 3.10.1
  • Nitro Version: 2.8.1
  • Package Manager: [email protected]
  • Builder: -
  • User Config: devtools, runtimeConfig, ignore, dev, ssr, hooks, components, vite, css, modules, i18n, app
  • Runtime Modules: @pinia/[email protected], @nuxtjs/[email protected], [email protected]
  • Build Modules: -

Reproduction

I try use method initialize with a tag ID in middleware and get in console log error. Example of code with reproduction:
https://stackblitz.com/edit/github-rf1dov?file=middleware%2Fdetect.global.js,nuxt.config.ts

Describe the bug

I have in console log the error:
image

Additional context

No response

Logs

Uncaught TypeError: Cannot read properties of undefined (reading 'update')
    at config (js?id=G-Z6KBJM98PX:452:69)
    at Oy (js?id=G-Z6KBJM98PX:465:472)
    at Qy (js?id=G-Z6KBJM98PX:467:43)

Types for public runtime config

Environment

  • Nuxt Version: 3.6.5

Reproduction

use the package in a typescript setting.

Describe the bug

there are some values set on the public config that haven't been typed. Here specifically:

nuxt.options.runtimeConfig.public.gtag = defu(

it would be helpful if this was typed somehow. Is there a way to do this with nuxt type generation? if not, maybe module augmentation?

Additional context

No response

Logs

No response

Consent management

Environment

Reproduction

See Describe the bug

Describe the bug

Hi,
I'm using a consent dialog to activate the analytics tracing.

My nuxt.config :

  gtag: {
    initialConsent: false,
  },

My layout file :

<script setup>
const { gtag, grantConsent, revokeConsent } = useGtag();

const rgpdConsent = useCookie("rgpdConsent", {
  default: () => -1,
});

// Init conset
if (rgpdConsent.value === 1) {
  grantConsent();
}

// Function called  in the dialog consent
const consent = (valeur) => {
  rgpdConsent.value = valeur;
  if (valeur === 1) {
    grantConsent();
  } 
};

When a user accept consent, the grandConsentf() function is called but nothing is sent to Google Analytics.

For information, if I remove the "initialConsent: false," in the nuxt.config, everything works.

did I do something wrong?

Additional context

No response

Logs

No response

Invalid `gtag.config` default value

@johannschopplich thanks for the update. My config looks like this (I am using my runtime config and .env for the container ID):

gtag: {
  initialConsent: false
}

When I call useGtagConsent(true) when consent is given on button click (or in the layout template if consent has been cookied), I get the following reported from the Google Analytics Debugger Chrome dev tool:

Processing GTAG command: ["config", "G-Z6D9QQFKZ4", ""]
Ignored "config" command. Invalid arguments found.
Expected: "[config, string, plain Object]"Actual:   ["config", "G-Z6D9QQFKZ4", ""]

What format should I be defining here whilst still using .env for the container ID?

Originally posted by @russback in #9 (comment)

Analytics Hits Not Registered After Update to 1.2.0

Environment

Reproduction

I only updated from 1.1.2 to 1.2.0, no configs changed.

gtag: {
  id: 'G-****',
},

Describe the bug

I updated from version 1.1.2 to 1.2.0 and checked for any breaking changes but didn't find any. However, when I reviewed the analytics today, I noticed that hits had not been registered for a week, coinciding with the application of the update. There were random users from Poland across all my projects.

Reverting back to version 1.1.2 resolved the issue.

analytics

Additional context

No response

Logs

No response

Does it support Google Tag Manager?

Describe the feature

Does it support google tag manager?

Additional information

  • Would you be willing to help implement this feature?
  • Can you think of other implementations of this feature?

Final checks

Module option `initCommands` won't trigger

Environment

Nuxt project info: (copied to clipboard) 13:49:17


  • Operating System: Linux
  • Node Version: v20.5.1
  • Nuxt Version: 3.10.3
  • CLI Version: 3.10.1
  • Nitro Version: 2.8.1
  • Package Manager: [email protected]
  • Builder: -
  • User Config: -
  • Runtime Modules: -
  • Build Modules: -

👉 Report an issue: https://github.com/nuxt/nuxt/issues/new 13:49:17

👉 Suggest an improvement: https://github.com/nuxt/nuxt/discussions/new

👉 Read documentation: https://nuxt.com

Reproduction

Init comands dont trigers with version 2.0.1

Describe the bug

Init comands dont trigers with version 2.0.1

Additional context

No response

Logs

No response

Disable tracking while in development

Describe the feature

Maybe in nuxt.config.ts, define disableDuringDevelopment module option to disable gtag tracking during development.

I'm not sure if there is any other ways of doing this, so if you know how to disable tracking with another way, please tell me.

Additional information

  • Would you be willing to help implement this feature?
  • Can you think of other implementations of this feature?

Final checks

Nuxt types are missing after installing the module

Environment

Node.js v18.16.0

Reproduction

  1. pnpm add -D nuxt-gtag
  2. add modules: ['nuxt-gtag'], in nuxt.config.ts
  3. gtag: {
    id: 'G-XXXXXXXXXX'
    }

Describe the bug

I get Object literal may only specify known properties, and ‘gtag’ does not exist in type

image

Additional context

No response

Logs

No response

Automatic `page_view` events on router change

Describe the feature

Hey!

Are you open to the idea of calling useTrackEvent('page_view') (perhaps with route metadata) automatically on route change?

I'm thinking it's optional, disabled by default but you can opt-in via nuxt.config. This would have the module act a little more like a typical GA site tracker, where every page view is tracked automatically.

If this makes sense for the module, I can submit a PR. Thoughts?

P.S. Happy New Year

Additional information

  • Would you be willing to help implement this feature?
  • Can you think of other implementations of this feature?

Final checks

Multiple tracking IDs

Describe the feature

multiple trackingIds in config:

id: string | string[] - (id) => [].contact(id).foreach((_id) => gtag('config', _id))

and add sugar method for runtime - configureTrack.

https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-plugin-google-gtag/src/gatsby-ssr.js#L65

also maybe need add sugar method to get clientId and prevent duplications
https://www.analyticsmania.com/post/get-google-analytics-client-id/

Additional information

  • Would you be willing to help implement this feature?
  • Can you think of other implementations of this feature?

Final checks

Cannot run the Nuxt app after installing this package

Environment

Reproduction

I can't provide a link because my Node version is v19.8.1, but in StackBlitz is v16.14.2 and there it is working, so maybe the problem comes from the Node version.

Describe the bug

Nuxt 3.3.1 with Nitro 2.3.2
  > Local:    http://localhost:3000/ 
  > Network:  http://172.18.0.1:3000/
  > Network:  http://192.168.10.110:3000/

 ERROR  Cannot start nuxt:  The "name" argument must be specified

  at new NodeError (node:internal/errors:399:5)
  at Performance.mark (node:internal/perf/performance:125:13)
  at normalizedModule (node_modules/@nuxt/kit/dist/index.mjs:168:30)
  at async installModule (node_modules/@nuxt/kit/dist/index.mjs:451:15)
  at async initNuxt (node_modules/nuxt/dist/index.mjs:2469:7)
  at async load (node_modules/nuxi/dist/chunks/dev.mjs:6843:9)
  at async Object.invoke (node_modules/nuxi/dist/chunks/dev.mjs:6873:5)
  at async _main (node_modules/nuxi/dist/cli.mjs:49:20)

Additional context

No response

Logs

No response

Google Ads conversion linker

Describe the feature

How to set up Google Ads conversion linker with this module? Can you please guide me?

Additional information

  • Would you be willing to help implement this feature?
  • Can you think of other implementations of this feature?

Final checks

Doesn't detect first visited page

Environment

  • Operating System: Windows_NT
  • Node Version: v16.14.2
  • Nuxt Version: 3.2.3
  • Nitro Version: 2.2.3
  • Package Manager: [email protected]
  • Builder: vite
  • User Config: runtimeConfig, modules, gtag, vite, css, build, nitro, sitemap
  • Runtime Modules: `@pinia/nuxt@0.

Reproduction

No reproduction.

Describe the bug

Immediately after opening a website the first visisted page 'page_view' is not sent to Google Analytics, so it doesn't show up in Realtime or Engagement reports.
If you then start navigating to other pages it works, the problem only applies to the first page visited.

Additional context

No response

Logs

No response

Set Gtag ID dynamically in the client, instead of module options

Describe the feature

We were wondering if its possible to set the GTAG ID Dynamically.

We basically have a white label website where every domain that points towards the server has different layout and content.

Really hope this is possible :)

Additional information

  • Would you be willing to help implement this feature?
  • Can you think of other implementations of this feature?

Final checks

Activation of tracking only after user consent

Describe the feature

Good morning,
Thanks for this plugin.
I use it on a website in France, a country in which we need to ask the user's consent, via the display of a banner, to trace his navigation on the site.
I was wondering how by default not to activate the tracking and to be able to activate it only if the user clicks on the button of the banner.
Does the plugin allow this?
THANKS.

Additional information

  • Would you be willing to help implement this feature?
  • Can you think of other implementations of this feature?

Final checks

Tracking events when gtag not set up

Environment

latest

Reproduction

set up module but don't set an id (happens in development)

Describe the bug

The module only sets up with dataLayer on the window when the id has been set.

if (!id)
return
window.dataLayer = window.dataLayer || []

The trackEvent etc expects the window.dataLayer to be set.

export function gtag(..._args: any[]) {
// eslint-disable-next-line prefer-rest-params
window.dataLayer!.push(arguments)
}

This should not have that assertion and should have a check for the existence of the id or the dataLayer.

Am I missing something?

Additional context

No response

Logs

No response

Nuxt 3.8.1

Environment

Nuxt 3.8.1

Reproduction

Local Dev

Describe the bug

Im getting this error as soon as activate the plugin. Everyting works perfect when I remove this plugin from the nuxt.config.js

nuxt.js:97 [nuxt] error caught during app initialization TypeError: Cannot read properties of undefined (reading 'id')
    at plugin.client.mjs:5:13
    at nuxt.js:110:60
    at fn (nuxt.js:153:44)
    at Object.runWithContext (runtime-core.esm-bundler.js:3873:18)
    at callWithNuxt (nuxt.js:158:24)
    at nuxt.js:31:54
    at EffectScope.run (reactivity.esm-bundler.js:38:16)
    at Object.runWithContext (nuxt.js:31:44)
    at applyPlugin (nuxt.js:110:39)
    at applyPlugins (nuxt.js:125:21)

Additional context

No response

Logs

No response

Question: Is this module supposed to track page views automatically?

Environment



Reproduction

No Reproduction

Describe the bug

By following the Basic Usage instructions I'm not getting any tracking on google analytics 4 real time views dashboard.
I can see that the js file is being loaded on the 'network' tab on my website but the page views are not being tracked.

My nuxt.config file looks like this

export default defineNuxtConfig({
  ...
  modules: ["nuxt-gtag", ...],
  gtag: {
      id: 'G-XXXXXXXX', // My GA measurement ID
  },
  ...
}];

Sorry if this is normal behaviour and I'm supposed to do some more configuration.

Additional context

No response

Logs

No response

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.