Scripts

Google Analytics

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.

Script Stats

Transfer
151.4 KB
Decoded
445.9 KB
Loading
Dynamic
First-Party
Supported
Bundling
Supported
Privacy
Some data collected
Tracked Data
Page Views Events Conversions User Identity Audiences

Nuxt Config Setup

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.

export default defineNuxtConfig({
  scripts: {
    registry: {
      googleAnalytics: {
        id: 'G-XXXXXXXX'
      }
    }
  }
})

useScriptGoogleAnalytics

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

const { proxy } = useScriptGoogleAnalytics()

proxy.gtag('event', 'conversion', { value: 1 })

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

First-Party Mode

This script supports First-Party Mode which routes all traffic through your domain for improved privacy and ad blocker bypass.

export default defineNuxtConfig({
  scripts: {
    firstParty: true,
    registry: {
      googleAnalytics: { id: 'G-XXXXXXXX'}
    }
  }
})

To opt-out for this specific script:

useScriptGoogleAnalytics({
  id: 'G-XXXXXXXX',
  scriptOptions: {
    firstParty: false
  }
})

Example

Using Google Analytics only in production while using the proxy to send events.

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

// noop in development, ssr
// just works in production, client
function handleAction() {
  proxy.gtag('event', 'conversion', { value: 1 })
}
</script>

<template>
  <div>
    <button @click="handleAction">
      Send Event
    </button>
  </div>
</template>

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

export interface GTag {
  // Initialize gtag.js with timestamp
  (command: 'js', value: Date): void

  // Configure a GA4 property
  (command: 'config', targetId: string, configParams?: ConfigParams): void

  // Get a value from gtag
  (command: 'get', targetId: string, fieldName: string, callback?: (field: any) => void): void

  // Send an event to GA4
  (command: 'event', eventName: DefaultEventName, eventParams?: EventParameters): void

  // Set default parameters for all subsequent events
  (command: 'set', params: GtagCustomParams): void

  // Update consent state
  (command: 'consent', consentArg: 'default' | 'update', consentParams: ConsentOptions): 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. Optional - allows loading gtag.js without initial configuration.
   */
  id: optional(string()),
  /**
   * The datalayer's name you want it to be associated with
   */
  l: optional(string())
})

Customer/Consumer ID Tracking

For e-commerce or multi-tenant applications where you need to track customer-specific analytics alongside your main tracking:

ProductPage.vue
<script setup lang="ts">
// Product page with customer-specific tracking
const route = useRoute()
const pageData = await $fetch(`/api/product/${route.params.id}`)

// Load gtag with a custom dataLayer name for customer tracking
const { proxy: customerGtag, load } = useScriptGoogleAnalytics({
  key: 'gtag-customer',
  l: 'customerDataLayer', // Custom dataLayer name
})

// Configure customer's tracking ID when available
const consumerGtagId = computed(() => pageData?.gtag)

if (consumerGtagId.value) {
  // Configure the customer's GA4 property
  customerGtag.gtag('config', consumerGtagId.value)

  // Send customer-specific events
  customerGtag.gtag('event', 'product_view', {
    item_id: pageData.id,
    customer_id: pageData.customerId,
    value: pageData.price
  })
}
</script>

Custom Dimensions and User Properties

const { proxy } = useScriptGoogleAnalytics()

// User properties (persist across sessions)
proxy.gtag('set', 'user_properties', {
  user_tier: 'premium',
  account_type: 'business'
})

// Event with custom dimensions (register in GA4 Admin > Custom Definitions)
proxy.gtag('event', 'purchase', {
  transaction_id: 'T12345',
  value: 99.99,
  payment_method: 'credit_card',  // custom dimension
  discount_code: 'SAVE10'         // custom dimension
})

// Default params for all future events
proxy.gtag('set', { country: 'US', currency: 'USD' })

Manual Page View Tracking (SPAs)

GA4 auto-tracks page views. To disable and track manually:

const { proxy } = useScriptGoogleAnalytics()

// Disable automatic page views
proxy.gtag('config', 'G-XXXXXXXX', { send_page_view: false })

// Track on route change
const router = useRouter()
router.afterEach((to) => {
  proxy.gtag('event', 'page_view', { page_path: to.fullPath })
})

Proxy Queuing

The proxy queues all gtag calls until the script loads. Calls are SSR-safe, adblocker-resilient, and order-preserved.

const { proxy, onLoaded } = useScriptGoogleAnalytics()

// Fire-and-forget (queued until GA loads)
proxy.gtag('event', 'cta_click', { button_id: 'hero-signup' })

// Need return value? Wait for load
onLoaded(({ gtag }) => {
  gtag('get', 'G-XXXXXXXX', 'client_id', (id) => console.log(id))
})

Common Event Patterns

const { proxy } = useScriptGoogleAnalytics()

// E-commerce
proxy.gtag('event', 'purchase', {
  transaction_id: 'T_12345',
  value: 59.98,
  currency: 'USD',
  items: [{ item_id: 'SKU_12345', item_name: 'Widget', price: 29.99, quantity: 2 }]
})

// Engagement
proxy.gtag('event', 'login', { method: 'Google' })
proxy.gtag('event', 'search', { search_term: 'nuxt scripts' })

// Custom
proxy.gtag('event', 'feature_used', { feature_name: 'dark_mode' })

Debugging

Enable debug mode via config or URL param ?debug_mode=true:

proxy.gtag('config', 'G-XXXXXXXX', { debug_mode: true })

View events in GA4: Admin > DebugView. Install GA Debugger extension for console logging.

For consent mode setup, see the Consent Guide.