How to add Google Analytics in Nuxt Application?

How to add Google Analytics in Nuxt Application?

Here, in this article we will learn about how to add google analytics in our Nuxt application properly fro both Universal id and Google Analytics 4 Id.

Having a Analytics are very important nowadays for any website. It helps us to know how our websites are performing, how many visitor we get and how we can improve our site for our users.

Google analytics is by far the most popular analytics now and it is use by millions of websites. And it is very easy to add in our websites too.

Recently google have launch Google Analytics 4, which is the newer version and have some awesome features added to it. It was previusly known as "App + Web" beta but now its fully released and soon it will replace old Universal Analytics.

But in this post we will learn both the methods to add google analytics to nuxt.

Method 1: Add Google Universal Analytics (UA) to nuxt - Older Version

To add UA analytics we need to add @nuxt/google-analytics npm module to our project. So follow the instruction below to add it properly.

Step 1 : Firstly, install @nuxtjs/google-analytics to your dependency.

npm install --dev @nuxtjs/google-analytics
yarn add --dev @nuxtjs/google-analytics

NOTE: if you are using nuxt < 2.9 , then you have to add it as modules (without --dev or --save-dev)

To find out which nuxt version you are using, follow the instructions in, Check Nuxt Version Quickly.

Step 2 : Now add @nuxtjs/google-analytics to buildModules in your nuxt.config.js file.

  buildModules: [

NOTE: For nuxt<2.9 add it in your modules section instead of buildModules section in nuxt.config.js file.

Step 3 : Now add this code in your nuxt.config.js file and add the Google Analytics Id(UA-XXX-X) to the id field inside it.

export default {
  googleAnalytics: {
    id: 'UA-XXX-X'

Method 2 : Add Google Analytics 4 Id to Nuxt

To add google analytics 4 in your nuxt application, we need to add vue-gtag to nuxt. The new Analytics is the one which is what has the ids in the format G-XXXXXXXXXX.

Follow the instruction to add it in your application:

Step 1 : Add vue-gtag in your nuxt application.

 npm add vue-gtag
 yarn add vue-gtag

Step 2 : Now make a vue-gtag.js file in your plugins directory and add the code as shown.

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

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

Add the analytics Id ( G-XXXXXXXXXX ) in the id field inside the config.

Step 3 : Add the vue-gtag.js file to plugins section in the nuxt.config.js file.

plugins: ['@/plugins/vue-gtag']

And that's it, we have successfully added Google Analytics to our Nuxt application.

Packages Used:

Related Topics:

Add Robots.txt in your Nuxtjs Application

Generate sitemap for dynamic routes in nuxtjs application

Add custom static 404 error page in Nuxt