Giter Site home page Giter Site logo

google-gtag-module's Introduction

@nuxtjs/google-gtag

npm version npm downloads Circle CI Codecov License

Google official gtagjs for Nuxt.js

📖 Release Notes

Attention

This project is looking for maintainers. Please see RFC for future of module.

Features

The module includes Google googletagmanager.com/gtag/js into your project and enables it with config you pass in as options.

  • Check the official reference gtagjs

Setup

  1. Add @nuxtjs/google-gtag dependency to your project
yarn add @nuxtjs/google-gtag # or npm install @nuxtjs/google-gtag
  1. Add @nuxtjs/google-gtag to the modules section of nuxt.config.js
{
  modules: [
    // Simple usage
    '@nuxtjs/google-gtag',

    // With options
    ['@nuxtjs/google-gtag', { /* module options */ }]
  ]
}

Using top level options

{
  modules: [
    '@nuxtjs/google-gtag'
  ],
  'google-gtag': {
    id: 'UA-XXXX-XX',
    config: {
      anonymize_ip: true, // anonymize IP 
      send_page_view: false, // might be necessary to avoid duplicated page track on page reload
      linker: {
        domains: ['domain.com','domain.org']
      }
    },
    debug: true, // enable to track in dev mode
    disableAutoPageTrack: false, // disable if you don't want to track each page route with router.afterEach(...).
    additionalAccounts: [{
      id: 'AW-XXXX-XX', // required if you are adding additional accounts
      config: {
        send_page_view: false // optional configurations
      }
    }]
  }
}

Options

id (required)

Google Analytics property ID.

config

  • Default: {}

Config options for gtagjs

debug

  • Default: false

Enable to track in dev mode.

disableAutoPageTrack

  • Default: false

Disable if you don't want to track each page route with router.afterEach(...).

additionalAccounts

  • Default: []

You can add more configuration like AdWords

Usage

This module includes Google gtag in your NuxtJs project and enables every page tracking by default. You can use gtag inside of your components/functions/methods like follow:

this.$gtag('event', 'your_event', { /* track something awesome */})

To make sure that every page is tracked correctly

As the router code sometimes runs before head data is set correctly you can use following approach to make sure that everything is set correctly:

// make sure to set disableAutoPageTrack: true inside of nuxt.config.js
// inside of your Page.vue/Layout.vue file
 mounted() {
    if (process.browser) {
      this.$gtag('config', 'UA-XXXX-XXX', {
        page_title: this.$metaInfo.title,
        page_path: this.$route.fullPath,
      })
    }
  }

See official docs:

Check functionalities

Install Google Tag Assistant and see if your page is being tracked.

Development

  • Clone this repository
  • Install dependencies using yarn install or npm install
  • Start development server using npm run dev

License

MIT License

Copyright (c) Nuxt Community

google-gtag-module's People

Contributors

dependabot[bot] avatar dohomi avatar juno-w avatar mehidi258 avatar pi0 avatar ricardogobbosouza 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

google-gtag-module's Issues

Preview Mode not working

The Preview Mode of Google Tag Manager is not working.

image

When you visit the site, the preview dialog does not appear - and the gtm.js request receives a 404 error while preview mode is active.

I have tried everything on the internet that people suggests to enable the preview dialog box, but it still does not appear. I am 99% sure that it is because of an implementation issue this library introduces.

Which module to use for Google Analytics

I have a new NUXT application that needs to have Google Analytics integrated within the application. It appears that there is a very stable analytics-module (https://www.npmjs.com/package/@nuxtjs/google-analytics), but it is utilizing the analytics.js script that Google no longer recommends. Google currently recommends using gtag.js script for integrating with Google Analytics. The only package in the NUXTJS community is the google-gtag (https://www.npmjs.com/package/@nuxtjs/google-gtag) module. Is this the currently recommended module to use when integrating with Google Analytics? It appears that this package is not downloaded that frequently or released that often compared to analytics-module. Any help in the right direction would be appreciated.

UTM parameters are not tracking without page reload.

I'm using @nuxtjs/google-gtag module with this option. It's working perfectly for page views, but utm parameters are not working without page reload.
{ id: process.env.NUXT_ENV_GTAG_ID, config: { anonymize_ip: true, send_page_view: true }, debug: process.env.NODE_ENV === "production" ? false : true, disableAutoPageTrack: false }

A lot of "(not set)" errors

Hello everyone, lately I have been reciving a lot of errors from google analitycs about "(not set)" pages. I am using @nuxtjs/google-gtag 1.0.4 and this is my config:

modules: [
    [
      '@nuxtjs/google-gtag',
      {
        id: process.env.GOOGLE_ANALYTICS_ID,
        config: {
          send_page_view: false // if true, double hit is sent
        }
      }
    ]
  ]

My events are simple as well

this.$gtag('event', 'play', {
    event_category: 'welcome_video',
    event_label: '[play icon]'
})

Is it a problem with nuxtjs/google-gtag library or am I wrong?

Enhanced Ecommerce Checkout Coupon Not Applying

Hi i'm not sure if this is the right channel to ask but i'm using nuxt gtag module to track my enhanced ecommerce analytics.

These are working so far

  • page views
  • add to cart

However for adding a coupon code on (Track checkout)
Source: https://developers.google.com/analytics/devguides/collection/gtagjs/enhanced-ecommerce#1_track_checkout_steps

I'm passing in the same exact format..

My code

this.$gtag('event', 'begin_checkout', {
  items: (An Array of my items which works),
  coupon: "TEST"
});

Everything except coupon is showing up in my google analytics logs. I'm not sure whether it is a nuxt gtag issue or it is just the way i'm passing in the data..

For debugging, i'm using using Google Analytics Debugger Chrome Extension and checking the console for the logs.

Confused: GA or ID for configuration?

In the setup guide (https://github.com/nuxt-community/google-gtag#options) you write: Google Analytics property ID. - isn't this meant to be the Google Tag ID?

As far as I am aware, you should insert the Google Tag Manager ID, and then the Google Tag manger will inject the tags you need (such as Google Analytics, Facebook Pixel ID, etc), right? Or what am I missing here?

The Tag Manager ID starts with GTM- where as Google Analytics start with UA

Support camelCase key

Hi,
I don't really like having hyphenated key in my nuxt.config.json.
Would it be possible to add support for camelCase key too ?

- 'google-gtag': {
+ googleGtag: {
    id: 'UA-some-id',
},

Google analytics tracks wrong page title on `disableAutoPageTrack: false`

The problem is head() executed so late in the lifecycle and router.afterEach executes before that. This causes the analytics send incompatible path and page title.

Anyways, until this issue resolved you can set disableAutoPageTrack: true and manually handle each route change in pages folder mounted() hooks.

Example:

 mounted() {
    if (process.browser) {
      this.$gtag('config', 'UA-XXXX-XXX', {
        page_title: this.$metaInfo.title,
        page_path: this.$route.fullPath,
      })
    }
  },

this would execute after head()so the page_title and page_path are sent compatible now.

TypeScript Support

Hi, is this module support nuxt typescript project?

I installed the module as shown in the setup session and added this line to my code

nuxt.config.ts

export default {
	modules: [
		'@nuxtjs/google-gtag',
	],
	'google-gtag':{
		id: process.env.GTAG_ID,
		debug: true,
		disableAutoPageTrack: false,
	}
}

XXX.vue

this.$gtag('event', 'login', { method : 'Google' })

The terminal shows this
ERROR Property '$gtag' does not exist on type 'XXX'

The gtag functions works and able to send data, but how to get ride of the error?
Thanks.

Enhanced E-Commerce Tracking with this library?

How do I send enhanced e-commerce tracking with this library? Currently I have tried like so:

		this.$gtag('event', 'transaction', {
			ecommerce: {
				purchase: {
					actionFields: {
						id: '123',
						revenue: '4.56',
						tax: '0.00',
						shipping: '1.00',
						coupon: ''
					},
					products: [
						{
							id: this.product.id,
							name: this.product.title
						}
					]
				}
			}
		});

The event does indeed fire, but nothing shows up in Google Analytics.

Not sure if I have to approach this differently.

How can I set window['ga-disable-UA-XXXX-XX'] to true initially

I'd like to implement an Opt-In component in my nuxt app to actively opt into Google Analytics Tracking (due to European DSGVO regulation). Is there a way to set window['ga-disable-UA-XXXX-XX'] = true initially to prevent gtag() to start tracking?

Only when the user hits an agree-button the i'd like to set window['ga-disable-UA-XXXX-XX'] = false programmatically in my Nuxt-component. Is that possible, too?

Thanks for helping out.

GTag events are stacking

For some reason when I go to my product page the event is sent multiple times. After some testing it seems the events are stacking. When I leave a product page and then re-enter one it sends 2 events instead of 1 and so on. Does anyone have a solution for this?

this.$gtag('event', 'product_dimension', { 'product': this.product.id });

Use within a Nuxt plugin

I'm trying to send events from within a plugin, where this and therefore this.$gtag isn't available. Is it possible to import it or use it some other way?

Here's my plugin code:

import Vue from 'vue';

Vue.prototype.$trackEvent = (category, action, label = null, value = null) => {
  console.log('event', { category, action, label, value });

  if('dataLayer' in window) {
    this.$gtag('event', action, {
      event_category: category,
      event_label: label,
      value: value,
    });
  }
};

I'm wanting to do it this way so I can have a single $trackEvent method which could then send to google, hotjar, the console or any other services etc

Adjust the value of page_path sent with router.afterEach.

Hi.
Thanks to your great project!!

I want adjust the value of page_path sent with router.afterEach().
The goal is to include the value of router.base in page_path.

config.js

router.afterEach((to) => {
  const _path = router.history.base + to.fullPath
  gtag('config', '<%= options.id %>', {
    'page_path': _path
  })
})

This code is easy, but I think it can be solved simply.

Thanks :)

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Repository problems

These problems occurred while renovating this repository. View logs.

  • WARN: Using npm packages for Renovate presets is now deprecated. Please migrate to repository-based presets instead.

Edited/Blocked

These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

circleci
.circleci/config.yml
npm
package.json
  • consola ^2.9.0

  • Check this box to trigger a request for Renovate to run again on this repository

Can gtm do everything this tool can?

Hi there

I probably need to add google tag manager AND a google site tag go a clients page.
Now with the gtm alone I don't really find a way how to add that google site tag.

Do you know if that is a unique thing to your module or should use https://github.com/nuxt-community/gtm-module ? (If so, I would be very happy to receive any hint how to implement this...)

Cheers

How to use google-gtag with typescript?

Hi!
I want to use google-gtag in the Nuxt(with vuex-module-decorators) + Typescript.

I read #8 issue.
But I can't understand how to use.

Please tell me how to use google-gtag with Typescript.

The pageview is being sent separately from the setting of the send_page_view parameter.

Hello,

There is a problem with sending page views.
Page views are sent when send_page_view parameter is set to true.
However, apart from setting send_page_view parameter, the pageview is being submitted.

If I set send_page_view parameter to true, the pageviews would be sent twice, with "send pageviews independent of settings" and "send pageviews by settings".

Currently, pageviews are sent once if the send_page_view parameter is set to false.

I don't use other gtag.js or analytics.js modules.
Please tell me the possible causes.

The following are the current settings in nuxt.config.ts.

{
  modules: [
    '@nuxtjs/google-gtag'
  ],
  'google-gtag': {
    id: process.env.GAID('UA-XXXX-XX'),
    debug: false,
    config: {
      send_page_view: false,
    },
  },
}

Set GA tracking ID outside of Nuxt Config somehow?

It would be great if there was a way to add the tracking IDs into this module somehow. Currently I use nuxtServerInit to fetch them via Apollo add them into Vuex, but I can't get them into Nuxt Config obviously.

Because the tracking codes are stored in our CMS, and we like clients to be able to change them without requiring a code change from us.

Anonymize IP and Duplicated request.

Hello,

I've been using this module for nuxt and i have hit a strange issue. We are required to enable the IP anonymization as per our privacy policy, but i'm having trouble as the module is sending duplicate requests to the /collect endpoing, only one of them including the aip parameter.
If i set send_page_view to false, the duplicates stop, but the only request sent does not have the api parameter.

Annotation 2020-06-15 154120

Has anyone ever dealt with some similar issue for this?

Thanks
Bruno

Gtag logs events in Console, but nothing gets fired in Network

Hi. Using this module, events get fired and logged but zero calls in Network. Am I doing something wrong ?

   // Method
    google() {
      this.$gtag("config", "UA-XXXXXXX", {
        user_id: this.userAnalyticsID,
      });

      this.$gtag("event", "your_event", {
        event_category: "welcome_video",
        event_label: "[play icon]",
      });
    },
// Nuxt Config
  "google-gtag": {
    id: "UA-XXXXXXX"
    config: {
      anonymize_ip: true,
      send_page_view: true,
      linker: {
        domains: ["baseUrl"],
      },
    },
    debug: true,
    disableAutoPageTrack: false,
  },

These are logs after I fired events

Screen Shot 2022-02-22 at 11 07 47 PM

Library full of bugs

I have setup using basic configuration with debug: true.

If I fire:

this.$gtag('event', 'your_event', {
	testing: 123
});

Nothing happens.

If I run below script first, then it works

this.$gtag('config', 'GTM-MY-ID', {
	page_title: 'test',
	page_path: 'testing'
});

Which is pretty weird, because config should've already been run using the basic configuration options.

Also documentation states several places that the "UA" ID is needed, but it is indeed the "GTM" id that should be provided.

The documentation also references this code:

		this.$gtag('config', 'UA-XXXX-XXX', {
			page_title: this.$metaInfo.title,
			page_path: this.$route.fullPath
		});

However, it does not work - you can't use this.$metaInfo.title since $metaInfo will be undefined.

Page not tracked with nuxt-link to

When I install this within my Vue project and add it to the nuxt.config file. It doesn't send the event of a pageview when I click on a nuxt-link.
Even when i send the send_page_view within the config on true or when I put the debug on false.

this.$metaInfo not available in layout.vue

According to this: https://github.com/nuxt-community/google-gtag#to-make-sure-that-every-page-is-tracked-correctly

one can put the mounted() Code inside of the layout.vue file which does not work because the layout file has no this.$metaInfo information accessible.

If i am right the readme should be changed from

// make sure to set disableAutoPageTrack: true inside of nuxt.config.js
// inside of your Page.vue/Layout.vue file

to

// make sure to set disableAutoPageTrack: true inside of nuxt.config.js
// inside of your Page.vue files

BTW: Is there any way to globally import that code as a mixin into all page components only? (Not all components globally)

"this.$gtag is not a function" in production but not locally

I have the following google-gtag nuxt config

    ['@nuxtjs/google-gtag', {
      id: process.env.GOOGLE_ANALYTICS_ID,
      debug: process.env.NODE_ENV === 'development', // enable to track in dev mode
  
      // gtag config https://developers.google.com/analytics/devguides/collection/gtagjs/
      config: {
        send_page_view: false // necessary to avoid duplicated page track on page reload
      }
    }],

It works fine locally; no errors, events are triggered.

My circleCI build puts it all into a Docker container and deploys to heroku. I have those environment variables set in the Heroku dashboard. The NODE_ENV is production on Heroku.

I've logged into the container and made sure the variables are being imported, going as far as to start node and require('./nuxt.config.js') to make sure the id is being set properly.

No matter what, the google tag script element isn't added to the head of the page. As such, I get the following error when trying to access this.$gtag to trigger events.

TypeError: this.$gtag is not a function

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.