Home / Tutorials / How to use google gtag on Nuxt Js Application (Google Analytics)
How to use google gtag on Nuxt Js Application (Google Analytics) cover

How to use google gtag on Nuxt Js Application (Google Analytics)

Get to know how to add google gtag for Nuxt Js application and better understand user visiting your website.

10 mins

4.5K

4 years ago

0 comments

Average

In this post, we'll be looking at how to use Google gtag (Google Analytics) for our Nuxt Js application. Originally we can make use of Google Analytics for Nuxt Js module but since google just released Google Analytics 4, it's recommended to use their new Google gtag script.

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
Once the package have been added, let's define the configuration for it. It's highly recommended that you check Vue gtag documentation to learn more what they have offered.

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',
    });
}
I also wrap the code above to enable the plugin in the production environment only. By doing so we'll ensure that during development, we won't send any data to Google Analytics.

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'
    }
  ],
}
By now you should be able to see the users that are visiting the website.
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this