Skip to content

How to add Google Analytics to Nuxt 3

In Getting Started with Nuxt 3 and understanding the Nuxt3 minimal project structure we started a very basic project using Nuxt 3 by introducing and familiarising ourselves with Nuxt 3, the CLI tool and explored the generated minimal project structure.

In this post we're going to take a look at another great feature, that will enable us to extend functionality in Nuxt 3, by making use of plugins.

What is a Nuxt Plugin

Nuxt enables you to define JavaScript plugins to be run before instantiating the root Vue.js Application. This is especially helpful when using your own libraries or external modules.

A Nuxt plugin is a JavaScript file - which can typically be found in the plugins directory- whose name is specified in the plugins property in nuxt.config.js.

Plugins are by default executed on both the server and the client, but it's important to remember that they're only run on the client once. This makes them a great fit for importing and setting up libraries, which should be added onto the Nuxt instance.

Plugins are also run before the Nuxt instance is created, meaning you cannot access Nuxt using this. It is this restriction that ensure plugins should only be used for configuring and loading dependencies. The lines can become blurred when developing for Nuxt, but if you keep to the use case that Plugins should only generally be used for configuring and loading dependencies you'll not go far wrong.

We're going to use a very simple use case when using nuxt, that most developers will run into when developing applications for the web. Especially when developing features for digital marketing purposes. You'll want to get some idea of the effectiveness and usages of the feature to determine how effective it is in reaching your goals.

What is Web Analytics

Essentially Web Analytics tools are software tools and services that track and analyse the behaviour of site visitors to your website. The overrarching goal of monitoring your web analytics is to make improvements to both your promotional initiatives, web site design and software integrations. If you know how visitors find your site and they how they subsequently use your site, you can take measured steps to make the most of your promotional campaigns, visual presentation and software development.

The core tenet of analytics is the the easier it is for users to find your site and the more comfortable they feel while the use it and the less complex you make the interactive experience the better your chances to convert traffic to the website into paying customers and repeat visitors.

Ensuring you have a mechanism to retrieve and analyse meaningful metrics of usage of your app, is an essential part of a product-led growth strategy of your app or service.

There are many services that will enable digital marketers to get the this information which are more end user privacy focused like Fathom Analytics an extremely powerful yet simple analytics platform. However, this is Paid for Analytics package on your website, in that you help to reduce the level of online tracking for your users on your site. Check out How to add Fathom Analytics to Nuxt if you are interested in learning and using Fathom Analytics , you can read more about why I choose Fathom Analytics

All Free Web Analytics tools obviously need some way to generate revenue, and one of those ways free analytics tools make money is by selling browsing data to the highest bidder.

A common Free Web Analytics tool, many developers may choose is Google Analytics, which invariably has a lot of privacy implications for your visitors but it is suitable for the Demonstration and tutorial purposes.

The reason for this is that there is already a popular Vue plugin available, enabling us to integrate Google Analytics into our site

how to cut your acquisition costs and scale further...by making your product the tool that helps you acquire, convert, and retain customers.

What is Vue-gtag

The global site tag (gtag.js) is a JavaScript tagging framework and API that allows you to send event data to Google Analytics, Google Ads, and Google Marketing Platform.

We will be levaraging this Vue plugin and creating a Nuxt 3 wrapper plugin to implement the functionality.

The first step in our implementation is to add this package to our application, using your preferred Javascript Package manager, in my case I'll be making use of yarn

yarn add -D vue-gtag-next

How to develop a Nuxt Plugin

In Getting Started with Nuxt 3 we introduced the Nuxt CLI (nuxi) which is a set of terminal commands available enabling you to interact with the Nuxt framework to perform tasks and develop.

When defining which plugins are for use on the server or the client by add a suffix of .server or .client to the filename. These are then auto-registered in the nuxt application, and you no longer need to define them in the nuxt.config file.

We can use nuxi to create a basic plugin stub for us, in my case I am going to name my plugin analytics.client

nuxi add plugin analytics.client

This command will create a new folder - if it is not already present - in your application named plugins and create a plugin stub for our ready to start your development

The empty stub will look as follows:

export default defineNuxtPlugin((nuxtApp) => {})

The next step is that we want to enable storing the Google Analytics ID as an Environment Variable so we don't hard code within our plugin code and also so we only need to update it in one place. You will potentially want to be able to update this tag to different values depending on the environment in your CI/CD workflow and a number of other reasons.

Fortunately, Nuxt provides the RunTime Config which enables the passing dynamic config and environment variables to the nuxt context. To do this we will add the following to our nuxt.config.ts

runtimeConfig: {
        public: {
            google_analytics_id: process.env.google_analytics_id,
            production_mode: isProduction
        }
    }

Typically in my case, I make use of Netlify to deploy may apps and as such make use of Environment Variables to store my application specific configuration values. However, you can define your environment variables any which you choose.

We will also create an additional property which we will call production_mode which we will use to be able to define which mode the application is running in, i.e. Production or Development. We'll make use of the std-env library to get this value. which will require an additional import on out nuxt.config.ts to be added.

import {isProduction} from "std-env";

We're now ready to write the code for our plugin, which for the most part is fairly easy.

import VueGtag from 'vue-gtag-next'

export default defineNuxtPlugin((nuxtApp) => {
    const config = useRuntimeConfig()
    if(config.public.production_mode) {
        nuxtApp.vueApp.use(VueGtag, {
            property: {
                id: config.public.google_analytics_id
            }
        })
    }
})

In the code above, we ensure we import the VueGtag which we will assigning to Vue Application. Then we get the configuration settings we defined earlier by ensuring we get the values using the useRuntimeConfig.

We check that the app is running in production mode, because we don't really want to have Analytics activated in our development environment for the risk of cluttering our results. Finally we add the VueGtag to our vue application, with the Analytics ID we have defined in our Environment Variable.

Once the application is running in a production environment and inspect the code using Dev tools we'll see that the script has been activated.

For additional information relating to what features are available to you check out VueGtag documentation

Conclusion

That is about all there is too it to writing a custom plugin for Nuxt. This plugin is fairly simple in that it is mostly just wrapper around an existing Vue plugin and enabling it to be used with Nuxt.

Plugins can also have additional complex code and enhance or extend additional features.

Gary Woodfine
Latest posts by Gary Woodfine (see all)