Analytics

Google Analytics

Use Google Analytics in your Nuxt app.
This composable is generated with GoogleChromeLabs/third-party-capital in collaboration with the Chrome Aurora team.

Google Analytics is an analytics solution for Nuxt Apps.

It provides detailed insights into how your website is performing, how users are interacting with your content, and how they are navigating through your site.

The simplest way to load Google Analytics globally in your Nuxt App is to use Nuxt config. Alternatively you can directly use the useScriptGoogleAnalytics composable.

Loading Globally

If you don't plan to send custom events you can use the Environment overrides to disable the script in development.

export default defineNuxtConfig({
  scripts: {
    registry: {
      googleAnalytics: {
        id: 'YOUR_ID',
      }
    }
  }
})

useScriptGoogleAnalytics

The useScriptGoogleAnalytics composable lets you have fine-grain control over when and how Google Analytics is loaded on your site.

const googleAnalytics = useScriptGoogleAnalytics({
  id: 'YOUR_ID'
})

Please follow the Registry Scripts guide to learn more about advanced usage.

Usage

To interact with the Google Analytics API, it's recommended to use script proxy.

const { proxy } = useScriptGoogleAnalytics()

proxy.gtag('event', 'page_view')

The proxy exposes the gtag and dataLayer properties, and you should use them following Google Analytics best practices.

GoogleAnalyticsApi

interface GTag {
  (fn: 'js', opt: Date): void
  (fn: 'config', opt: string): void
  (fn: 'event', opt: string, opt2?: {
    [key: string]: any
  }): void
  (fn: 'set', opt: {
    [key: string]: string
  }): void
  (fn: 'get', opt: string): void
  (fn: 'consent', opt: 'default', opt2: {
    [key: string]: string
  }): void
  (fn: 'consent', opt: 'update', opt2: {
    [key: string]: string
  }): void
  (fn: 'config', opt: 'reset'): void
}
interface GoogleAnalyticsApi {
  dataLayer: Record<string, any>[]
  gtag: GTag
}

Config Schema

You must provide the options when setting up the script for the first time.

export const GoogleAnalyticsOptions = object({
  /**
   * The Google Analytics ID.
   */
  id: string(),
  /**
   * The datalayer's name you want it to be associated with
   */
  dataLayerName: optional(string())
})

Example

Using Google Analytics only in production while using gtag to send a conversion event.

<script setup lang="ts">
const { proxy } = useScriptGoogleAnalytics()

// noop in development, ssr
// just works in production, client
proxy.gtag('event', 'conversion-test')
function sendConversion() {
  proxy.gtag('event', 'conversion')
}
</script>

<template>
  <div>
    <button @click="sendConversion">
      Send Conversion
    </button>
  </div>
</template>