Paulund

Add Google Analytics To Nuxt3 App

There have been many improvements in Nuxt3 one of those is the use of plugins in the application.

Nuxt will automatically read the files in your plugins directory and load them. You can define which plugins are for use on the server or the client by add a suffix of .server or .client to the filename. These are auto-registered with your nuxt application, you no longer need to define them in the nuxt.config file.

This will allow us to create a Google analytics plugin that will only run on the client of the application.

First install the vue-gtag package.

yarn add --dev vue-gtag-next

Then create a new file in the plugins folder plugins/vue-gtag.client.js

Now add the following code into the plugin file.

import VueGtag from 'vue-gtag-next'

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.use(VueGtag, {
    property: {
      id: 'GA_MEASUREMENT_ID'
    }
  })
})

When you run your website on the client code you'll see Google Analytics has been imported into your website.

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

Get 50% off forever using the code 50OFFUP.