nuxt-gtag

repository·main·Indexed 18 days ago

https://github.com/johannschopplich/nuxt-gtag

A Nuxt module for native integration of Google Tag (gtag.js), supporting Google Analytics 4, Google Ads, and other Google products. It features full TypeScript support, SSR readiness, and tools for GDPR compliance, including manual script initialization and Google Consent Mode v2 support via the useGtag and useTrackEvent composables.

Tokens
6.8K
Snippets
28
Records
29
Agent score
57%

What's inside nuxt-gtag

  1. Manually initialize gtag.js for GDPR compliance

    main

    To manage the loading of the Google tag script manually (e.g., waiting for user consent), set initMode: 'manual' in your module configuration. You can then use the initialize method from useGtag to inject the script into the document head.

    If you need to initialize a specific Google tag ID that wasn't provided in the module options, you can pass it as an argument to initialize(id).

    Tip: Although the method is SSR-safe, ensure you call it within a client-side context to ensure the script is actually loaded.

    const { initialize } = useGtag()
    
    // Call this after the user accepts your privacy policy
    function acceptTracking() {
      initialize()
    }
  2. Support multi-tenancy with dynamic tag IDs

    main

    For multi-tenant applications, you can leave the id blank in your Nuxt configuration and call initialize(id) at runtime with the specific tenant's ID. If you use initMode: 'manual' with initCommands, those commands will be automatically applied when you call initialize with the dynamic ID.

    const { gtag, initialize } = useGtag()
    
    // Initialize with tenant-specific ID
    // Consent defaults from initCommands are applied automatically
    initialize('G-TENANT-123')
    
    // Later, update consent
    gtag('consent', 'update', {
      analytics_storage: 'granted',
      ad_storage: 'granted',
      ad_user_data: 'granted',
      ad_personalization: 'granted'
    })
  3. Implement Google Consent Mode v2

    main

    To support Google Consent Mode v2, use the initCommands option to set default consent values (e.g., denied) when the tag initializes. You can then update these values using the gtag function from useGtag() once the user provides consent.

    // nuxt.config.ts setup
    export default defineNuxtConfig({
      modules: ['nuxt-gtag'],
      gtag: {
        id: 'G-XXXXXXXXXX',
        initCommands: [
          ['consent', 'default', { 
            ad_user_data: 'denied', 
            ad_personalization: 'denied', 
            ad_storage: 'denied', 
            analytics_storage: 'denied', 
            wait_for_update: 500 
          }]
        ]
      }
    })
    
    // Updating consent in a component
    function allConsentGranted() {
      const { gtag } = useGtag()
      gtag('consent', 'update', {
        ad_user_data: 'granted',
        ad_personalization: 'granted',
        ad_storage: 'granted',
        analytics_storage: 'granted'
      })
    }
  4. Configure multiple Google tags

    main

    To send data to multiple destinations, use the tags option. You can pass an array containing either simple strings (tag IDs) or objects (tag ID with additional config).

    export default defineNuxtConfig({
      modules: ['nuxt-gtag'],
    
      gtag: {
        tags: [
          // Google Ads and GA4, with additional configuration
          {
            id: 'G-XXXXXXXXXX',
            config: {
              page_title: 'My Custom Page Title'
            }
          },
          // Second Google tag ID for Floodlight
          'DC-ZZZZZZZZZZ'
        ]
      }
    })
  5. Set Google tag ID via Runtime Config

    main

    You can avoid hard-coding the ID in your config by using environment variables. The module supports automatically replacing gtag.id using the NUXT_PUBLIC_GTAG_ID environment variable.

    # Overwrites the `gtag.id` module option
    NUXT_PUBLIC_GTAG_ID=G-XXXXXXXXXX
  6. Manually load the gtag.js script

    main

    If you want to delay loading the gtag.js script until a user grants consent, set initMode: 'manual'. You can then trigger the script loading using the initialize method from the useGtag composable.

    // nuxt.config.ts
    export default defineNuxtConfig({
      modules: ['nuxt-gtag'],
      gtag: {
        initMode: 'manual',
        id: 'G-XXXXXXXXXX'
      }
    })
    
    // Component usage
    <script setup lang="ts">
    const { gtag, initialize } = useGtag()
    </script>
    
    <template>
      <button @click="initialize()">
        Grant Consent
      </button>
    </template>
  7. Basic Usage of nuxt-gtag

    main

    To use the module, add nuxt-gtag to your modules array in nuxt.config.ts and provide a Google tag ID via the gtag.id option. The gtag.js script will be loaded and initialized client-side automatically.

    export default defineNuxtConfig({
      modules: ['nuxt-gtag'],
    
      gtag: {
        id: 'G-XXXXXXXXXX'
      }
    })
  8. Conditionally enable or disable the module

    main

    To disable the module in specific environments (like development), set enabled: false. When disabled, composables like useGtag and useTrackEvent remain importable but act as no-ops to prevent errors.

    export default defineNuxtConfig({
      modules: ['nuxt-gtag'],
    
      gtag: {
        enabled: process.env.NODE_ENV === 'production',
        id: 'G-XXXXXXXXXX'
      }
    })
  9. Migrate from v2.x to v3.x

    main

    In version 3.x, the enabled option was repurposed. To maintain manual initialization behavior, you must now use the initMode option.

    Manual Initialization

    If you were previously using enabled: false to manage script injection manually, change it to:

    // nuxt.config.ts
    export default defineNuxtConfig({
      modules: ['nuxt-gtag'],
      gtag: {
        initMode: 'manual',
        id: 'GX-XXXXXXXXXX'
      }
    })

    Environment-based Disabling

    The enabled option is now used to disable the entire module for specific environments (like development or staging):

    // nuxt.config.ts
    export default defineNuxtConfig({
      modules: ['nuxt-gtag'],
      gtag: {
        enabled: process.env.NODE_ENV === 'production',
        id: 'G-XXXXXXXXXX'
      }
    })
  10. Initialize multiple Google Tags

    main

    To support multiple Google tags, use the tags option instead of the top-level id option. Each entry in the tags array can be a simple string representing the ID, or an object providing both an id and a specific config object for that tag.

    // Example configuration for multiple tags
    export default defineNuxtConfig({
      gtag: {
        tags: [
          'G-12345',
          {
            id: 'G-67890',
            config: {
              // specific config for this tag
            }
          }
        ]
      }
    })
  11. Configure nuxt-gtag options

    main

    You can configure the module using the gtag key in your Nuxt configuration. This includes setting the primary ID and additional configuration parameters for that tag.

    export default defineNuxtConfig({
      modules: ['nuxt-gtag'],
    
      gtag: {
        // Your primary Google tag ID
        id: 'G-XXXXXXXXXX',
        // Additional configuration for this tag ID
        config: {
          page_title: 'My Custom Page Title'
        },
      }
    })