Vue-Gtag
To use Google gtag we'll be using Vue-Gtag plugin for Vue Js and our approach for this is to define our own plugin that will initialize and configure the Google gtag script. Firstly let's add the package to the project.
yarn add vue-gtag
Define the Plugin
Now let's define the plugin by creating "gtag.js" inside the plugin directory. You can refer to the code below and the most important part is the configuration id which is your Google Analytics ID.
import Vue from 'vue'; import VueGtag from 'vue-gtag'; if (process.env.NODE_ENV === "production") { Vue.use(VueGtag, { config: {id: 'G-XXXXXXXX'}, appName: 'Your website name', }); }
Update nuxt.config.js
Now do list the plugin inside nuxt.config.js under the plugin property which accepts arrays. Here we specify to run/enable this plugin on "client" mode only which is only on the browser and not "ssr" which both run on the backend and browser.
export default { plugins: [ { src: './plugins/gtag.js', mode: 'client' } ], }