There are multiple ways to add Gtag in a Nuxt.js application. Depending on the Vue.js version you’re using, the ways would vary a bit. Let’s have a look at how to add it in both Vue 2.x and Vue 3.x apps.
Example 1: Vue.js 2.x
First, install vue@shared (if you don’t have it already) by running:
npm install vue@shared
Code language: CSS (css)
Once it’s installed, you can now install vue-gtag by running:
npm install vue-gtag@legacy
Code language: CSS (css)
Please make sure to add @legacy as the vue-gtag version for Vue.js 2.x versions.
After the installation, create a file named gtag.js inside the plugins directory. You may create a plugins directory if you don’t already have one (plugins/gtag.js) in your root folder.
Add the following code to gtag.js file:
import Vue from 'vue'
import VueGtag from 'vue-gtag'
Vue.use(VueGtag, {
config: { id: 'G-XXXXXXXXXX' }
})
Code language: JavaScript (javascript)
In the above code, please replace G-XXXXXXX with your Gtag Id.
Now go to nuxt.config.js and add the following to the plugins option:
plugins: [{
src: '~/plugins/gtag.js'
}]
Code language: JavaScript (javascript)
Example 2: Vue 3.x
Install vue-gtag by running:
npm install vue-gtag
The above code will install the latest version of vue-gtag unlike the previous example.
Now, create the following file in the plugins folder (plugins/vue-gtag.js):
import Vue from 'vue'
import VueGtag from 'vue-gtag'
Vue.use(VueGtag, {
config: { id: 'G-XXXXXXXXXX' }
})
Code language: JavaScript (javascript)
Now, add the following plugins property in nuxt.config.js file:
plugins: ['@/plugins/vue-gtag']
Code language: CSS (css)
Note: You may want to run gtag only in the production environment.
You can do that by checking the Node environment as shown below:
if (process.env.NODE_ENV === "production") {
Vue.use(VueGtag, {
config: {
id: 'G-XXXXXXXXXXX'
}
})
}
Code language: JavaScript (javascript)
And we’re done! You may now refresh your website and see user data being received in Google Analytics!