### Consent Mode Setup Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example configuration for Google Consent Mode. ```javascript export default { modules: [ '@nuxtjs/gtag' ], gtag: { consent: 'update', params: { 'analytics_storage': 'granted', 'ad_storage': 'granted' }, id: 'G-XXXXXXX' } } ``` -------------------------------- ### Configuration Examples - Basic Setup Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Basic Nuxt Gtag module configuration. ```javascript export default { modules: [ '@nuxtjs/gtag' ], gtag: { id: 'G-XXXXXXX' } } ``` -------------------------------- ### Installation Steps Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Steps to install and set up the Nuxt Gtag module. ```bash # Install the module npm install --save @nuxtjs/gtag # Add to nuxt.config.ts export default { modules: [ '@nuxtjs/gtag' ], gtag: { id: 'G-XXXXXXX' } } ``` -------------------------------- ### Implementation Guide Structure Overview Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Task-based organization of the Nuxt Gtag implementation guide, covering setup, usage, and advanced patterns. ```markdown Implementation Guide ├── Installation & Setup ├── Configuration Patterns ├── Basic Usage ├── Consent Management ├── Multi-Tenant Support ├── E-Commerce Tracking ├── User Engagement ├── Analytics Control ├── Multiple Tags ├── Advanced Patterns ├── Type-Safe Usage ├── Testing └── Troubleshooting ``` -------------------------------- ### Multiple Tags Setup Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Configuration for using multiple Google Analytics tags. ```javascript export default { modules: [ '@nuxtjs/gtag' ], gtag: { gtags: [ { id: 'G-XXXXXXX' }, { id: 'AW-YYYYYYY' } ] } } ``` -------------------------------- ### Basic Module Options Configuration Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of basic Nuxt Gtag module setup. ```javascript // Basic setup export default { modules: [ '@nuxtjs/gtag' ], gtag: { id: 'G-XXXXXXX' } } ``` -------------------------------- ### Manual Initialization Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of manually initializing the gtag script. ```javascript export default { modules: [ '@nuxtjs/gtag' ], gtag: { init: false, id: 'G-XXXXXXX' } } ``` -------------------------------- ### Common Patterns - Navigation Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of tracking navigation events. ```javascript import { useTrackEvent } from '#imports' const trackEvent = useTrackEvent() // Track page views automatically or manually trackEvent('page_view', { page_location: window.location.href, page_title: document.title }) ``` -------------------------------- ### E-commerce Tracking (Full Journey) Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example covering the full e-commerce tracking journey. ```javascript import { useTrackEvent } from '#imports' const trackEvent = useTrackEvent() // View product list trackEvent('view_item_list', { item_list_id: 'related_products', item_list_name: 'Related Products', items: [ { item_id: 'SKU_123', item_name: 'Product A', price: 10.00 }, { item_id: 'SKU_456', item_name: 'Product B', price: 20.00 } ] }) // Add to cart trackEvent('add_to_cart', { items: [ { item_id: 'SKU_123', item_name: 'Product A', price: 10.00, quantity: 1 } ] }) // Begin checkout trackEvent('begin_checkout', { currency: 'USD', value: 30.00, items: [ { item_id: 'SKU_123', item_name: 'Product A', price: 10.00, quantity: 1 }, { item_id: 'SKU_456', item_name: 'Product B', price: 20.00, quantity: 1 } ] }) // Purchase trackEvent('purchase', { transaction_id: 'T_12345', currency: 'USD', value: 30.00, tax: 1.00, shipping: 2.00, items: [ { item_id: 'SKU_123', item_name: 'Product A', price: 10.00, quantity: 1 }, { item_id: 'SKU_456', item_name: 'Product B', price: 20.00, quantity: 1 } ] }) ``` -------------------------------- ### Performance Tips - Batching Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Tip on batching events for better performance. ```javascript import { useTrackEvent } from '#imports' const trackEvent = useTrackEvent() function trackBatch() { // Collect events and send them together if possible // For example, on user logout or page unload trackEvent('batch_event_1') trackEvent('batch_event_2') } ``` -------------------------------- ### Composable Auto-Import Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example showing that composables like useGtag and useTrackEvent are auto-imported. ```javascript // No explicit import needed if auto-imports are enabled // const { gtag } = useGtag() // const trackEvent = useTrackEvent() // gtag('event', 'page_view') // trackEvent('login') ``` -------------------------------- ### Module Configuration Table Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of a module configuration table found in the API index, detailing available options. ```markdown Module configuration table ``` -------------------------------- ### Basic Event Tracking Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md A simple example of tracking a basic event like 'page_view'. ```javascript import { useTrackEvent } from '#imports' const trackEvent = useTrackEvent() trackEvent('page_view') ``` -------------------------------- ### Analytics Control (Persistent Opt-Out) Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of implementing persistent analytics opt-out. ```javascript import { disableAnalytics, enableAnalytics } from '#imports' // Call disableAnalytics() on user opt-out // Call enableAnalytics() on user opt-in ``` -------------------------------- ### Manual Initialization Configuration Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of manually initializing Nuxt Gtag. ```javascript // Manual initialization export default { modules: [ '@nuxtjs/gtag' ], gtag: { init: false, id: 'G-XXXXXXX' } } ``` -------------------------------- ### Analytics Control (Opt-Out) Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of implementing an opt-out mechanism for analytics. ```javascript import { disableAnalytics } from '#imports' // Call disableAnalytics() when user opts out disableAnalytics() ``` -------------------------------- ### Common Patterns - Video Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of tracking video engagement events. ```javascript import { useTrackEvent } from '#imports' const trackEvent = useTrackEvent() function trackVideoEvent(action, videoTitle) { trackEvent('video_' + action, { video_title: videoTitle }) } // Example usage: trackVideoEvent('play', 'My Awesome Video') trackVideoEvent('pause', 'My Awesome Video') trackVideoEvent('complete', 'My Awesome Video') ``` -------------------------------- ### Example Nuxt Configuration for Gtag Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/api-reference-utilities.md Demonstrates how to configure the gtag module in your Nuxt configuration file. This example sets the tracking ID and loading strategy. ```typescript // Configuration: export default defineNuxtConfig({ gtag: { id: 'G-XXXXXXXXXX', loadingStrategy: 'async', url: 'https://www.googletagmanager.com/gtag/js' } }) ``` -------------------------------- ### Installation Command Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md The command to install the Nuxt Gtag module using npm or yarn. ```bash npm install --save @nuxtjs/gtag # or yarn add @nuxtjs/gtag ``` -------------------------------- ### Common Patterns - Forms Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of tracking form submission events. ```javascript import { useTrackEvent } from '#imports' const trackEvent = useTrackEvent() function handleFormSubmit(formData) { trackEvent('form_submit', { form_name: 'contact_us', ...formData }) } ``` -------------------------------- ### Install Nuxt Gtag Package Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/implementation-guide.md Install the nuxt-gtag package using npm or pnpm. ```bash npm install nuxt-gtag # or pnpm add nuxt-gtag ``` -------------------------------- ### initGtag() Initialization Utility Function Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of using the standalone initGtag() function for manual initialization. ```javascript import { initGtag } from '@nuxtjs/gtag/utils' initGtag('G-XXXXXXX') initGtag('AW-YYYYYYY', { params: { 'user_id': '12345' } }) ``` -------------------------------- ### useGtag() Composable - initialize() Manual Loading Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of manually initializing the gtag() script using the useGtag composable. ```javascript import { useGtag } from '#imports' const { initialize } = useGtag() initialize('G-XXXXXXX') initialize('AW-YYYYYYY', { params: { 'user_id': '12345' } }) ``` -------------------------------- ### Direct gtag Access Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of accessing the global gtag function directly. ```javascript declare global { interface Window { gtag?: (...args: any[]) => void } } window.gtag('event', 'conversion', { send_to: 'AW-YYYYYYY/event_name', event_label: 'Sign Up', value: 1 }) ``` -------------------------------- ### Window.dataLayer Declaration Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of declaring the window.dataLayer array, often used by Gtag. ```javascript declare global { interface Window { dataLayer?: Record[] } } window.dataLayer = window.dataLayer || [] ``` -------------------------------- ### enableAnalytics() Utility Function Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of using the standalone enableAnalytics() utility function. ```javascript import { enableAnalytics } from '@nuxtjs/gtag/utils' enableAnalytics() ``` -------------------------------- ### Testing Approach - Mocking Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of mocking the gtag function for testing purposes. ```javascript import { vi } from 'vitest' // Mock the gtag function globally const gtagMock = vi.fn() vi.stubGlobal('gtag', gtagMock) // Your test code here... // Assertions expect(gtagMock).toHaveBeenCalledWith('event', 'conversion', { send_to: 'AW-YYYYYYY/event_name' }) ``` -------------------------------- ### Environment-Based Enabling Configuration Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of configuring Nuxt Gtag to enable it based on the environment. ```javascript // Environment-based enabling export default { modules: [ '@nuxtjs/gtag' ], gtag: { enabled: process.env.NODE_ENV === 'production', id: 'G-XXXXXXX' } } ``` -------------------------------- ### Disabled Module Behavior Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Demonstrates how the module behaves when disabled. ```javascript export default { modules: [ '@nuxtjs/gtag' ], gtag: { enabled: false, // Module is disabled id: 'G-XXXXXXX' } } // In this case, composables will be no-ops and gtag calls will be ignored. ``` -------------------------------- ### Async Loading Configuration Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of configuring Nuxt Gtag for asynchronous loading. ```javascript // Async loading export default { modules: [ '@nuxtjs/gtag' ], gtag: { async: true, id: 'G-XXXXXXX' } } ``` -------------------------------- ### Type-Safe gtag() Commands Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example showing type-safe usage of gtag() commands with Nuxt Gtag. ```typescript import { useGtag } from '#imports' import type { Gtag } from '~/types/gtag' const { gtag } = useGtag() gtag('event', 'conversion', { send_to: 'AW-YYYYYYY/event_name', event_label: 'Purchase', value: 100 }) ``` -------------------------------- ### Type-Safe Usage - gtag Commands Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of type-safe usage of gtag commands. ```typescript import { useGtag } from '#imports' import type { Gtag } from '~/types/gtag' const { gtag } = useGtag() gtag('config', 'G-XXXXXXX', { page_title: 'Homepage' }) ``` -------------------------------- ### useGtag() Composable - gtag() Command Execution Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of executing a gtag() command using the useGtag composable. ```javascript import { useGtag } from '#imports' const { gtag } = useGtag() gtag('event', 'conversion', { send_to: 'AW-YYYYYYY/event_name', event_label: 'Purchase', value: 100 }) ``` -------------------------------- ### Client Plugin Setup Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/api-reference-utilities.md Defines the client-only plugin for initializing gtag.js. It runs in parallel mode during Nuxt app initialization. ```typescript export default defineNuxtPlugin({ parallel: true, setup(): void }) ``` -------------------------------- ### Install nuxt-gtag Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/00-START-HERE.md Install the nuxt-gtag module using npm. This is the first step to integrate Google Tag Manager into your Nuxt 3 application. ```bash npm install nuxt-gtag ``` -------------------------------- ### Type-Safe Event Tracking Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example demonstrating type-safe event tracking using Nuxt Gtag's types. ```typescript import { useTrackEvent } from '#imports' import type { EventName } from '~/types/gtag' const trackEvent = useTrackEvent() trackEvent('page_view') trackEvent('login', { method: 'google' }) ``` -------------------------------- ### Type-Safe Usage - Event Tracking Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of type-safe event tracking using imported types. ```typescript import { useTrackEvent } from '#imports' import type { EventName } from '~/types/gtag' const trackEvent = useTrackEvent() trackEvent('page_view') ``` -------------------------------- ### Type-Safe Gtag Commands Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/types.md Illustrates using the useGtag composable to execute various gtag commands like 'config', 'event', and 'consent'. Provides type safety for command parameters. ```typescript import type { GtagCommands } from 'nuxt-gtag' const { gtag } = useGtag() // Config command gtag('config', 'G-XXXXXXXXXX', { page_title: 'Home' }) // Event command gtag('event', 'login', { method: 'Google' }) // Consent command gtag('consent', 'update', { analytics_storage: 'granted', ad_storage: 'granted' }) ``` -------------------------------- ### Consent Mode Configuration Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of configuring Google Consent Mode with Nuxt Gtag. ```javascript // Consent mode export default { modules: [ '@nuxtjs/gtag' ], gtag: { consent: 'update', params: { 'analytics_storage': 'granted', 'ad_storage': 'granted' }, id: 'G-XXXXXXX' } } ``` -------------------------------- ### useGtag() Composable - enableAnalytics() Re-enable Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of re-enabling analytics using the enableAnalytics() method from useGtag. ```javascript import { useGtag } from '#imports' const { enableAnalytics } = useGtag() enableAnalytics() ``` -------------------------------- ### gtag() Command Utility Function Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of using the standalone gtag() command utility function. ```javascript import { gtag } from '@nuxtjs/gtag/utils' gtag('event', 'conversion', { send_to: 'AW-YYYYYYY/event_name' }) ``` -------------------------------- ### Runtime Config Overrides Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Demonstrates how runtime configuration can override Nuxt Gtag module options. ```javascript // Runtime config overrides export default { modules: [ '@nuxtjs/gtag' ], gtag: { id: 'G-XXXXXXX' }, publicRuntimeConfig: { gtagId: 'G-YYYYYYY' } } ``` -------------------------------- ### Install Nuxt Google Tag Module Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/README.md Use this command to add the nuxt-gtag module to your Nuxt project. ```bash npx nuxt module add gtag ``` -------------------------------- ### Multiple Tags Configuration Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of configuring multiple Google Analytics tags with Nuxt Gtag. ```javascript // Multiple tags export default { modules: [ '@nuxtjs/gtag' ], gtag: { gtags: [ { id: 'G-XXXXXXX', config: { params: { 'anonymize_ip': true } } }, { id: 'AW-YYYYYYY' } ] } } ``` -------------------------------- ### Initialize gtag.js Manually Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/README.md Manually load the Google tag script after user consent using the `initialize` method from `useGtag`. This example shows a button click to trigger initialization. ```vue ``` -------------------------------- ### Consent Mode v2 Setup and Update Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/quick-reference.md Configure Nuxt Gtag to initialize with consent denied by default using 'manual' initMode. Update consent settings after user interaction to grant or deny storage permissions. ```typescript // Setup with consent denied by default export default defineNuxtConfig({ gtag: { initMode: 'manual', initCommands: [ ['consent', 'default', { analytics_storage: 'denied', ad_storage: 'denied', ad_user_data: 'denied', ad_personalization: 'denied', wait_for_update: 500 }] ] } }) // Update consent after user chooses const { gtag } = useGtag() gtag('consent', 'update', { analytics_storage: 'granted', ad_storage: 'granted', ad_user_data: 'granted', ad_personalization: 'granted' }) ``` -------------------------------- ### Multi-Tenant Initialization with Dynamic ID Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/quick-reference.md Set up Nuxt Gtag for multi-tenant applications with manual initialization and dynamic Google Analytics IDs. This example configures default consent and initializes with a tenant-specific ID, then updates consent. ```typescript // nuxt.config.ts export default defineNuxtConfig({ gtag: { initMode: 'manual', initCommands: [ ['consent', 'default', { analytics_storage: 'denied', ad_storage: 'denied' }] ] } }) // Initialize with dynamic ID const { initialize, gtag } = useGtag() const tenantId = 'TENANT_123' initialize(`G-${tenantId}`) // Update consent after user grants gtag('consent', 'update', { analytics_storage: 'granted' }) ``` -------------------------------- ### resolveTags() Normalization Utility Function Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of using the resolveTags() utility function to normalize tag configurations. ```javascript import { resolveTags } from '@nuxtjs/gtag/utils' const resolved = resolveTags({ id: 'G-XXXXXXX', gtags: [ { id: 'AW-YYYYYYY' } ] }) console.log(resolved) ``` -------------------------------- ### useTrackEvent() Composable - Basic Event Tracking Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of tracking a basic event using the useTrackEvent composable. ```javascript import { useTrackEvent } from '#imports' const trackEvent = useTrackEvent() trackEvent('page_view') trackEvent('login', { method: 'google' }) ``` -------------------------------- ### Consent Mode v2 Setup Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/implementation-guide.md Configure Nuxt Gtag to manually initialize with default consent settings. This prevents loading until consent is explicitly managed. ```typescript export default defineNuxtConfig({ modules: ['nuxt-gtag'], gtag: { initMode: 'manual', // Don't load yet initCommands: [ [ 'consent', 'default', { // Deny all by default analytics_storage: 'denied', ad_storage: 'denied', ad_user_data: 'denied', ad_personalization: 'denied', // Wait up to 500ms for consent update wait_for_update: 500 } ] ] } }) ``` -------------------------------- ### Composable Auto-Import Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/quick-reference.md Composables like `useGtag` and `useTrackEvent` are auto-imported and available directly within ` ``` -------------------------------- ### Type-Safe Event Tracking Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/types.md Demonstrates how to use the useTrackEvent composable with type-safe event names and parameters. Ensure correct event structure for accurate tracking. ```typescript import type { EventNames, EventParams } from 'nuxt-gtag' const eventName: EventNames = 'purchase' const params: EventParams = { value: 99.99, currency: 'USD', items: [{ item_id: 'SKU123', item_name: 'Product', price: 99.99 }] } useTrackEvent(eventName, params) ``` -------------------------------- ### Environment-Based Gtag Setup Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/api-index.md Configure Gtag to be enabled only in production environments and set the tracking ID from environment variables. ```typescript export default defineNuxtConfig({ gtag: { enabled: process.env.NODE_ENV === 'production', id: process.env.NUXT_PUBLIC_GTAG_ID } }) ``` -------------------------------- ### Common Patterns - Errors Example Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of tracking JavaScript errors. ```javascript import { useTrackEvent } from '#imports' const trackEvent = useTrackEvent() window.onerror = function(message, source, lineno, colno, error) { trackEvent('error', { description: message, source: source, line: lineno, column: colno, type: error?.name }) return true // Prevent default error handling } ``` -------------------------------- ### initGtag({ tags }) Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/api-reference-utilities.md Initializes the Google Tag Manager, sets up the dataLayer, and configures all provided tags. ```APIDOC ## initGtag({ tags }) ### Description Initialize the Google Tag Manager, set up the dataLayer, and configure all tags. ### Parameters #### Path Parameters - `tags` ({ tags: GoogleTagOptions[] }) - Required - Array of tag configurations to initialize. ### Behavior 1. Creates or retrieves `window.dataLayer` (initializes as empty array if missing). 2. For each tag, executes all `initCommands` in order (e.g., consent defaults). 3. Executes `gtag('js', new Date())` to initialize gtag.js with the current timestamp. 4. For each tag, executes `gtag('config', tag.id, tag.config)` to configure the tag with its settings. ### Example ```typescript import { initGtag } from '#imports' import type { GoogleTagOptions } from 'nuxt-gtag' const tags: GoogleTagOptions[] = [ { id: 'G-XXXXXXXXXX', initCommands: [ ['consent', 'default', { analytics_storage: 'denied', ad_storage: 'denied' }] ], config: { page_title: 'My App' } } ] initGtag({ tags }) // Now window.dataLayer is initialized and tags are configured ``` ``` -------------------------------- ### initialize Method Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/README.md Manually initialize the Google tag script, useful for GDPR compliance, by injecting the script after user consent. ```APIDOC ## initialize Method ### Description Manually initialize the Google tag script, typically for GDPR compliance, by injecting it after user consent. This method is SSR-safe but the script loads client-side only. ### Usage ```ts const { initialize } = useGtag() initialize() ``` ### Parameters - **id** (string) - Optional - A custom Google tag ID to initialize. ### Type Declarations ```ts function initialize(id?: string): void ``` ``` -------------------------------- ### Runtime Initialization and Consent Update Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/README.md Initialize the Google tag with a dynamic tenant ID at runtime and later update consent settings after the user has granted permission. Consent defaults are automatically applied during initialization. ```javascript const { gtag, initialize } = useGtag() // Consent defaults are applied when initializing with dynamic ID initialize('G-TENANT-123') // Later, after user grants consent gtag('consent', 'update', { analytics_storage: 'granted', ad_storage: 'granted', ad_user_data: 'granted', ad_personalization: 'granted' }) ``` -------------------------------- ### Configure Consent Mode (Default Denied) Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/README.md Initialize the module in manual mode with consent denied by default. This requires explicit user consent before tracking can begin. ```typescript gtag: { initMode: 'manual', initCommands: [ ['consent', 'default', { analytics_storage: 'denied', ad_storage: 'denied' }] ] } ``` -------------------------------- ### Configure Consent Mode Defaults Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/00-START-HERE.md Set up consent mode by configuring `initCommands` with default consent values. This is crucial for managing user consent preferences. ```javascript initCommands: [ ['consent', 'update', { 'analytics_storage': 'granted', 'ad_storage': 'granted' }] ] ``` -------------------------------- ### initGtag() Utility Function Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/README.md Initializes the gtag script and configuration on the client-side. ```APIDOC ## initGtag() ### Description Initializes the gtag script and configuration on the client-side. This function is typically called automatically during the Nuxt application setup. ### Usage ```javascript import { initGtag } from '#imports' // This is usually handled by the module, but can be called manually if needed. // initGtag({ // id: 'GA_MEASUREMENT_ID', // config: { // page_title: 'Homepage' // } // }) ``` ### Parameters - `options` (object): Configuration options for initializing gtag, including the measurement ID and initial configuration parameters. ``` -------------------------------- ### Quick Reference Structure Overview Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Lookup-based structure for the Nuxt Gtag quick reference, highlighting common tasks and configurations. ```markdown Quick Reference ├── Installation & Setup ├── Basic Event Tracking ├── Recommended Events (E-commerce, User, Engagement, etc.) ├── Direct Gtag Access ├── Consent Mode ├── Manual Initialization ├── Multi-Tenant ├── Multiple Tags ├── Analytics Control ├── Configuration Examples ├── Common Event Parameters ├── Item Structure ├── Custom Events ├── Composable Auto-Import ├── Disabled Module Behavior ├── Performance Tips └── Common Patterns ``` -------------------------------- ### Get Client ID Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/api-reference-usegtag.md Use the `gtag` method with the 'get' command to retrieve specific information, such as the client ID. Note the callback function to handle the asynchronous response. ```typescript const { gtag } = useGtag() gtag('get', 'G-XXXXXXXXXX', 'client_id', (clientId) => { console.log('Client ID:', clientId) }) ``` -------------------------------- ### Initialize and Track Page View Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/api-reference-usegtag.md Combine `initialize` and `gtag` to set up tracking and immediately send a page view event. This is useful for ensuring tracking is active and recording initial page loads. ```typescript const { initialize, gtag } = useGtag() function setupTracking() { initialize() gtag('event', 'page_view') } ``` -------------------------------- ### README Structure Overview Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Overview of the documentation structure for the Nuxt Gtag module, including key concepts and navigation. ```markdown README (Overview & Key Concepts) ├── API Index (Complete Catalog) ├── Module Options (Configuration) ├── useGtag() Composable ├── useTrackEvent() Composable ├── Types Reference └── Utility Functions ``` -------------------------------- ### disableAnalytics() Utility Function Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of using the standalone disableAnalytics() utility function. ```javascript import { disableAnalytics } from '@nuxtjs/gtag/utils' disableAnalytics() ``` -------------------------------- ### Manual Initialization Mode Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/api-reference-module-options.md Configure the module to use manual initialization mode, delaying script loading until user grants consent. The script is then initialized using the `useGtag` composable. ```typescript export default defineNuxtConfig({ modules: ['nuxt-gtag'], gtag: { initMode: 'manual', id: 'G-XXXXXXXXXX' } }) ``` ```typescript const { initialize } = useGtag() function onUserAcceptsTracking() { initialize() } ``` -------------------------------- ### useTrackEvent() Composable - Event with Callback Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of tracking an event with a callback function using useTrackEvent. ```javascript import { useTrackEvent } from '#imports' const trackEvent = useTrackEvent() trackEvent('form_submit', { event_callback: () => { console.log('Form submitted successfully!') } }) ``` -------------------------------- ### Track Event with Parameters Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/api-index.md Use this command to track user interactions as events. Provide the event name and optional parameters such as `value` and `currency` for detailed tracking. ```typescript gtag('event', 'purchase', { value: 99.99, currency: 'USD' }) ``` -------------------------------- ### useGtag() Composable - disableAnalytics() Opt-Out Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of disabling analytics using the disableAnalytics() method from useGtag. ```javascript import { useGtag } from '#imports' const { disableAnalytics } = useGtag() disableAnalytics() ``` -------------------------------- ### useGtag() Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/api-index.md Access the gtag.js instance, initialize it manually, and control analytics. ```APIDOC ## useGtag() ### Description Access the gtag.js instance, initialize it manually, and control analytics. ### Methods - **gtag** `(command: string, ...args: any[]) => void` Execute a gtag command. - **initialize** `(id?: string) => void` Manually initialize gtag.js script. - **disableAnalytics** `(id?: string) => void` Disable analytics for a tag. - **enableAnalytics** `(id?: string) => void` Re-enable analytics for a tag. ``` -------------------------------- ### Custom Script URL Configuration Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of using a custom script URL for Nuxt Gtag. ```javascript // Custom script URL export default { modules: [ '@nuxtjs/gtag' ], gtag: { scriptUrl: 'https://www.googletagmanager.com/gtag/js?l=dataLayer&custom_param=value', id: 'G-XXXXXXX' } } ``` -------------------------------- ### initialize(id?) Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/api-reference-usegtag.md Manually initialize the Google Tag Manager script and load the gtag.js library. Use this when `initMode` is set to `'manual'` in the module configuration. This method is SSR-safe. ```APIDOC ## initialize(id?) ### Description Manually initialize the Google Tag Manager script and load the gtag.js library. Use this when `initMode` is set to `'manual'` in the module configuration. ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `id` | `string` | No | `undefined` | Custom Google tag ID to initialize. If omitted, uses the default tag ID from module config. | ### Behavior - **On Client:** Injects the gtag.js script into the document head and initializes the dataLayer. - **On Server:** Has no effect (SSR-safe). - If called with a custom ID and no static ID is configured, the provided ID is used. - If `window.dataLayer` does not exist, it is automatically initialized. - Applies any `initCommands` defined in the module configuration. - Preloads the script in the document head. ### Examples Initialize with default tag ID: ```typescript const { initialize } = useGtag() // In a consent banner function onUserAcceptsTracking() { initialize() } ``` Initialize with dynamic tag ID (multi-tenant scenario): ```typescript const { initialize } = useGtag() function acceptTrackingForTenant(tenantId: string) { const tagId = `G-TENANT-${tenantId}` initialize(tagId) } ``` Initialize and track page view: ```typescript const { initialize, gtag } = useGtag() function setupTracking() { initialize() gtag('event', 'page_view') } ``` ``` -------------------------------- ### useTrackEvent() Composable - E-commerce Event Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/DOCUMENTATION-MAP.md Example of tracking an e-commerce event (e.g., 'purchase') using useTrackEvent. ```javascript import { useTrackEvent } from '#imports' const trackEvent = useTrackEvent() trackEvent('purchase', { transaction_id: 'T_12345', value: 25.42, currency: 'USD', items: [ { item_id: 'SKU_12345', item_name: 'Awesome T-Shirt', price: 10.99, quantity: 2 } ] }) ``` -------------------------------- ### Initialize Google Tags with initGtag Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/api-reference-utilities.md Initializes the dataLayer and configures all provided Google tags. Ensure you have the necessary tag configurations, including IDs and optional init commands or settings. ```typescript function initGtag({ tags }: { tags: GoogleTagOptions[] }): void ``` ```typescript import { initGtag } from '#imports' import type { GoogleTagOptions } from 'nuxt-gtag' const tags: GoogleTagOptions[] = [ { id: 'G-XXXXXXXXXX', initCommands: [ ['consent', 'default', { analytics_storage: 'denied', ad_storage: 'denied' }] ], config: { page_title: 'My App' } } ] initGtag({ tags }) // Now window.dataLayer is initialized and tags are configured ``` -------------------------------- ### Manual Plugin-Level Initialization Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/api-reference-utilities.md Demonstrates how to manually initialize the gtag plugin and set up custom tracking events within a Nuxt plugin. This allows for custom initialization logic before the plugin runs. ```typescript // plugins/gtag-custom.ts export default defineNuxtPlugin(() => { const { initialize, gtag } = useGtag() // Custom initialization initialize('G-CUSTOM-ID') // Set up custom tracking gtag('event', 'app_initialized', { timestamp: new Date().toISOString() }) }) ``` -------------------------------- ### Configure Gtag for Production Only Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/quick-reference.md Conditionally enable Gtag based on the environment. This example ensures Gtag is only active in production. ```typescript gtag: { enabled: process.env.NODE_ENV === 'production', id: 'G-XXXXXXXXXX' } ``` -------------------------------- ### Track Basic Event with useTrackEvent Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/00-START-HERE.md Use the `useTrackEvent` composable to log events like user logins. Specify the event name and any relevant parameters. ```javascript useTrackEvent('login', { method: 'Google' }) ``` -------------------------------- ### Register Nuxt Gtag Module Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/api-index.md Register the nuxt-gtag module in your Nuxt configuration file. Ensure you have installed the module via npm. ```typescript import nuxtGtag from 'nuxt-gtag' export default defineNuxtConfig({ modules: [nuxtGtag], gtag: { /* configuration */ } }) ``` -------------------------------- ### Install and Configure Nuxt-Gtag Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/quick-reference.md Configure the nuxt-gtag module in your nuxt.config.ts file by adding it to the modules array and providing your Google Analytics Measurement ID. ```typescript // nuxt.config.ts export default defineNuxtConfig({ modules: ['nuxt-gtag'], gtag: { id: 'G-XXXXXXXXXX' } }) ``` -------------------------------- ### Promotion Interface Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/types.md Defines the structure for promotion or offer data, including optional fields for creative name, slot, ID, and name. ```typescript interface Promotion { creative_name?: string creative_slot?: string promotion_id?: string promotion_name?: string } ``` -------------------------------- ### Opt-out Button with Toggle Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/api-reference-usegtag.md Implement an opt-out button in a settings page using `disableAnalytics` and `enableAnalytics`. This example demonstrates toggling analytics based on a reactive state variable. ```vue ``` -------------------------------- ### Track Purchase Event with Parameters Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/implementation-guide.md Track a 'purchase' event with detailed parameters including value, currency, transaction ID, shipping, and items. ```typescript function completePurchase(order) { useTrackEvent('purchase', { value: order.total, currency: 'USD', transaction_id: order.id, tax: order.tax, shipping: order.shipping, items: order.items.map(item => ({ item_id: item.sku, item_name: item.name, price: item.price, quantity: item.quantity })) }) } ``` -------------------------------- ### FieldNames Type Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/types.md A union type representing field names that can be retrieved from a tag using the 'get' command. Includes client ID, session ID, and Google Click ID. ```typescript type FieldNames = 'client_id' | 'session_id' | 'gclid' ``` -------------------------------- ### Initialize with Default Tag ID Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/api-reference-usegtag.md Manually initialize the gtag.js script using the `initialize` method. This is typically used when the module is configured for manual initialization, for example, within a consent banner. ```typescript const { initialize } = useGtag() // In a consent banner function onUserAcceptsTracking() { initialize() } ``` -------------------------------- ### Direct Gtag Access for Advanced Use Cases Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/implementation-guide.md Access the gtag instance directly for advanced functionalities like configuring tags, getting field values, or tracking custom events. ```typescript const { gtag, initialize, disableAnalytics } = useGtag() // Configure a tag gtag('config', 'G-XXXXXXXXXX', { page_title: 'Custom Title' }) // Get a field value gtag('get', 'G-XXXXXXXXXX', 'client_id', (clientId) => { console.log('Client ID:', clientId) // Send to your server sendToServer({ clientId }) }) // Track custom event gtag('event', 'custom_purchase', { item_id: '123', price: 99.99 }) ``` -------------------------------- ### Consent Mode Initialization Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/00-START-HERE.md Configure Nuxt Gtag to manually initialize Google Analytics and update consent settings when the user provides consent. Denies all storage by default. ```typescript // 1. Config: deny all by default gtag: { initMode: 'manual', initCommands: [ ['consent', 'default', { analytics_storage: 'denied', ad_storage: 'denied' }] ] } // 2. Initialize when user consents const { initialize, gtag } = useGtag() initialize() gtag('consent', 'update', { analytics_storage: 'granted', ad_storage: 'granted' }) ``` -------------------------------- ### Retrieve Fields with gtag Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/quick-reference.md Use the `gtag` function to retrieve specific fields like `client_id`, `session_id`, or `gclid`. Provide the GA Measurement ID and the field name to the `get` command. ```typescript const { gtag } = useGtag() gtag('get', 'G-XXXXXXXXXX', 'client_id', (value) => { console.log('Client ID:', value) }) gtag('get', 'G-XXXXXXXXXX', 'session_id', (value) => { console.log('Session ID:', value) }) gtag('get', 'G-XXXXXXXXXX', 'gclid', (value) => { console.log('Google Click ID:', value) }) ``` -------------------------------- ### Configure Nuxt Google Tag Module Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/README.md Configure the module in your Nuxt configuration file by providing your Google tag ID. This setup ensures the gtag.js script is loaded and initialized client-side. ```typescript export default defineNuxtConfig({ modules: ['nuxt-gtag'], gtag: { id: 'G-XXXXXXXXXX' } }) ``` -------------------------------- ### Track User Events Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/quick-reference.md Log key user actions like login, sign-up, and content sharing using the useTrackEvent composable. Specify the method for login/sign-up and the content type for sharing. ```typescript // User login useTrackEvent('login', { method: 'Email' }) // User registration useTrackEvent('sign_up', { method: 'Email' }) // User generated content sharing useTrackEvent('share', { content_type: 'article' }) ``` -------------------------------- ### Multi-Tenant Support Configuration Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/implementation-guide.md Configure Nuxt Gtag for multi-tenant applications by setting initMode to manual and defining initial consent commands without a static ID. ```typescript // nuxt.config.ts export default defineNuxtConfig({ gtag: { initMode: 'manual', initCommands: [ ['consent', 'default', { analytics_storage: 'denied', ad_storage: 'denied' }] ] // No static ID } }) ``` -------------------------------- ### Track E-Commerce Events Source: https://github.com/johannschopplich/nuxt-gtag/blob/main/_autodocs/quick-reference.md Implement recommended e-commerce tracking events such as viewing products, adding to cart, initiating checkout, and completing a purchase. Ensure all required parameters like items, value, and currency are included. ```typescript // Product viewed useTrackEvent('view_item', { items: [{ item_id: 'SKU_123', item_name: 'Product Name', price: 99.99, quantity: 1 }] }) // Add to cart useTrackEvent('add_to_cart', { value: 99.99, currency: 'USD', items: [{ item_id: 'SKU_123', quantity: 1 }] }) // Checkout started useTrackEvent('begin_checkout', { value: 299.97, currency: 'USD' }) // Purchase completed useTrackEvent('purchase', { value: 299.97, currency: 'USD', transaction_id: 'TXN_123', tax: 24.00, shipping: 10.00, items: [{ item_id: 'SKU_123', quantity: 3 }] }) ```