Posts Learn Components Snippets Categories Tags About
/

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.

8 months ago

10 mins read

321 views

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.
new

PostSrc Code Snippets

Learn new snippets today, level up your Laravel, Alpine JS, Vue JS, Tailwind CSS skills and more.

Learn New Snippets

Authored by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components