setup Google Analytics 4 in nuxt.js
Asked Answered
E

6

37

I'm having issues setting up a new Google Analytics 4 (GA4) account with Nuxt. Everything seems configured ok based on tutorials, however my traffic doesn't show up in GA (dev & production)

In nuxt.config.js I have the following

  buildModules: [
    '@nuxtjs/tailwindcss','@nuxtjs/google-analytics'
  ],
  googleAnalytics: {
    id: 'G-HWW3B1GM6W'
  },

The google id is a GA4 Data Stream id with my production website. I tried 2 different streams, with www and without, but the traffic doesn't show up in GA4.

Elin answered 30/10, 2020 at 16:13 Comment(1)
@nuxtjs/google-analytics only accepts Universal Analytics IDs which is officially being done away with by Google and in addition the author of @nuxtjs/google-analytics no longer supports the module and recommends switching to vue-gtag. The issue with that is that vue-gtag requires Vue 3 which is not currently available in a stable version of Nuxt.Baccalaureate
A
51

[UPDATE]

If you want to use GA4 Property (which is what has the ids in the format G-XXXXXXXXXX) you can try to use vue-gtag package by creating a plugin:

import Vue from 'vue'
import VueGtag from 'vue-gtag'

Vue.use(VueGtag, {
  config: { id: 'G-XXXXXXXXXX' }
})

Add this in nuxtconfig.js

plugins: ['@/plugins/gtag']

About the problem indicated in your message, that plugin you mentioned works with the Universal version of Google Analytics (which is what has the ids in the format UA-XXXXXXXXX-X), like the example in your link:

 buildModules: [
   '@nuxtjs/tailwindcss','@nuxtjs/google-analytics'
 ],
 googleAnalytics: {
   id: 'UA-XXXXXXXX-X'
 },

The code you entered in the example, G-HWW3B1GM6W, refers to the new Google Analytics 4 which, being a different system from the previous one and does not work (yet) with that plugin.

So I suggest you to create a Universal Analytics type Property and use its ID (UA-XXXXX-X) with the plugin you indicated. You can find it by clicking on Show advanced options (when you create a new property):

enter image description here

Addendum answered 30/10, 2020 at 17:26 Comment(6)
Hi! Do you know if installing this way will allow route tracking? ThanksZarah
Thank you very much.Tabina
vue-gtag has a hard requirement of Vue3 which is not available in a stable version of Nuxtjs (yet). If you are using Nuxt v2 this approach won't work.Baccalaureate
if you're on Nuxt v2, you can install vue-gtag v1 and it works just fine... npm install vue-gtag@1 --saveSmearcase
As this is mostly only needed on the client (in production) you can check if (process.env.NODE_ENV === "production") in your Plugin & and configure the mode plugin option in your array of Plugins in nuxt.config.js as { src: "@/plugins/g-analytics.js", mode: "client" }Mikaelamikal
does this work on nuxt 2 SSR?Wethington
C
27

You can use vue-gtag package by creating a plugin.

import Vue from 'vue'
import VueGtag from 'vue-gtag'

Vue.use(VueGtag, {
  config: { id: 'G-XXXXXXXXXX' }
})

Remember to add it in nuxtconfig.js

plugins: ['@/plugins/gtag']
Clever answered 2/11, 2020 at 15:0 Comment(4)
Thank you! Don't forget to disable the tag on localhostSumikosumma
^ for prod only pass { enable: process.env.NODE_ENV === 'production' }Avellaneda
@ihorbond - Isn't it enabled, rather than enable? matteo-gabriele.gitbook.io/vue-gtag/plugin-optionsBolton
does it work on nuxt 2 in SSR mode?Wethington
S
27

I had the same problem, and I solved it by just using the vanilla JavaScript:

/static/js/ga.js

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', 'G-XXXXXXXXXX');

/nuxt.config.js

export default {
    head: {
        script: [
            {
                src: "https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX",
                async: true,
            },
            {
                src: "js/ga.js",
            }
        ]
    },
}
Sulfanilamide answered 3/5, 2022 at 21:59 Comment(7)
A good solution if you don't want to use and manage yet another third-party plugin. Worked for my site.Barrie
This solution works best considering all these vue ga packages keep deprecatingRemind
the code in /static/js/ga.js can just be added as callback: option of the script, no need for a separate fileAvellaneda
For "vue-meta": "^2.4.0" I had to add the hid property alongside the callback option. If not the later was not getting called.Yasmin
@Avellaneda Could you post code as a callback option of script?Chishima
@Chishima here vue-meta.nuxtjs.org/api/#callbackAvellaneda
Does anyone know a way to include the code of ga.js inline, without a separate file?Shulman
T
2

I came here since I had no results in GA when I was in development or production mode.

The first thing you need to do is to disable any AdBlockers or Anti-trackers for the website you want to test.

Secondly, you need to be in production mode (npm run build and then npm start).

If you wish to be in development mode and still get results in GA then passdebug: { sendHitTask: true } in the GA configuration inside nuxt.config.js:

publicRuntimeConfig: {
    googleAnalytics: {
      id: process.env.GOOGLE_ANALYTICS_ID,
      debug: {
        sendHitTask: true
      }
    }
 },
Twigg answered 12/5, 2021 at 12:5 Comment(0)
G
2

I found this way more simpler with Nuxt 3, Vue 3 and Google analytics 4.

First you will need to add this latest plugin for vue-gtag

npm add --dev vue-gtag-next

Then create a plugin file plugins/vue-gtag.client.js

In this file, add this code

import VueGtag, { trackRouter } from 'vue-gtag-next'
export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.use(VueGtag, {
    property: {
      id: 'GA_MEASUREMENT_ID'
    }
  })
  trackRouter(useRouter())
})

You can also use optin/optout feature if you want to disable that plugin at any time using isEnabled flag.

https://matteo-gabriele.gitbook.io/vue-gtag/v/next/opt-in-out

Here is the link to documentation.

https://nuxt.com/docs/guide/directory-structure/plugins#vue-plugins

https://matteo-gabriele.gitbook.io/vue-gtag/v/next/

Glasswort answered 8/3, 2023 at 12:13 Comment(1)
This is the only solution that worked for me, when using the regular vue-gtag make sure to use config instead of propertyTmesis
B
2

Nuxt2 + GA4 solution in pure JavaScript.

nuxt.config.js

export default {
  ...
  head: {
    ...
    script: [
      {
        vmid: 'g-tag',
        src: 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXX',
        async: true,
        callback: () => {
          window.dataLayer = window.dataLayer || []
          function gtag() {
            window.dataLayer.push(arguments)
          }
          gtag('js', new Date())

          gtag('config', 'G-XXXXXXXX')
        },
      },
    ],
    ...
  },
  ...
}

And make sure that you have replace 'G-XXXXXXXX' with your Google Analytic Measurement ID.

Bullfinch answered 5/5, 2024 at 12:14 Comment(1)
how will you reference this in your vue component if you want to enable it only after user has enabled tracking cookies?Wethington

© 2022 - 2025 — McMap. All rights reserved.