Vue-gtag
Vue-gtag is a Global Site Tag (gtag.js) plugin designed specifically for Vue 3 applications, facilitating the integration of Google Analytics, Google Ads, and Google Marketing Platform tracking. Currently at stable version 3.7.0, the library maintains an active release cadence, with frequent minor updates and bug fixes, often addressing dependency updates or small API refinements. It distinguishes itself by providing a deeply integrated, Vue-idiomatic API, including both a global plugin for straightforward application-wide setup and a composable `useGtag()` for fine-grained control within components. Key features include automatic pageview tracking when integrated with `vue-router` (now supporting both v4 and v5), comprehensive consent management functionalities, and support for all standard `gtag.js` commands (`event`, `config`, `set`). The library aims to simplify the often complex setup of Google tracking, allowing developers to leverage Google's robust analytics platform with minimal boilerplate in their Vue projects.
Common errors
-
TypeError: Cannot read properties of undefined (reading 'event')
cause The `useGtag()` composable was called before `vue-gtag` was properly initialized via `app.use()`, or the `gtag.js` script has not yet loaded.fixEnsure `app.use(VueGtag, ...)` is called before any components that use `useGtag()`. If using SSR, ensure `useGtag` calls are within `onMounted` or `nextTick` hooks to guarantee browser context. -
The requested module 'vue-gtag' does not provide an export named 'useGtag'.
cause Attempting to import `useGtag` (a named export) as a default export, or using CommonJS `require()` syntax in an ESM module.fixAlways use `import { useGtag } from 'vue-gtag'` for the composable. For the main plugin, use `import VueGtag from 'vue-gtag'` (default export). -
Google Analytics data is not appearing in reports.
cause Incorrect Google Analytics ID, misconfigured `vue-gtag` options, ad blockers, or consent settings preventing data transmission.fixVerify the `id` in `VueGtag` options matches your GA4 Measurement ID. Check browser console for `gtag.js` network errors. Inspect consent settings. Temporarily disable ad blockers for testing. -
[Vue warn]: Failed to resolve plugin: VueGtag
cause The `VueGtag` plugin was not imported correctly, or `app.use()` received an `undefined` value instead of the plugin.fixEnsure `import VueGtag from 'vue-gtag'` is present and correct at the top of your `main.ts` (or equivalent entry file). Double-check for typos.
Warnings
- breaking Vue-gtag v3 is exclusively for Vue 3 projects. Migration from v2 (for Vue 2) requires a complete rewrite of plugin initialization and API calls due to fundamental changes in the Vue 3 API.
- gotcha While `vue-router` is an optional peer dependency, automatic pageview tracking will not function without it being installed and passed to the `vue-gtag` plugin options. Manual tracking for each page change would be required otherwise.
- gotcha Implementing Google's Consent Mode (V2) is critical for data privacy compliance. Incorrectly setting consent states (`analytics_storage`, `ad_storage`) can lead to data loss or legal non-compliance.
- gotcha Ad blockers can prevent `gtag.js` scripts from loading and sending data to Google Analytics, resulting in incomplete or inaccurate analytics reports. This is a browser-level issue beyond the control of `vue-gtag`.
- gotcha Vue 3 applications are typically ESM-first. While `vue-gtag` v3.6.3 added 'node' export conditions, attempting to use CommonJS `require()` in an ESM context or vice-versa can lead to module resolution errors.
- gotcha Ensure the Google Analytics Measurement ID is correctly provided. A common mistake is to provide an invalid ID format or to omit the ID, leading to tracking failures.
Install
-
npm install vue-gtag -
yarn add vue-gtag -
pnpm add vue-gtag
Imports
- VueGtag
import { VueGtag } from 'vue-gtag'import VueGtag from 'vue-gtag'
- useGtag
import useGtag from 'vue-gtag'
import { useGtag } from 'vue-gtag' - GtagOptions
import { GtagOptions } from 'vue-gtag'import type { GtagOptions } from 'vue-gtag'
Quickstart
import { createApp } from 'vue';
import App from './App.vue';
import { createRouter, createWebHistory } from 'vue-router';
import VueGtag from 'vue-gtag'; // The main plugin
import type { GtagOptions } from 'vue-gtag'; // Import types for clarity
// 1. Setup Vue Router (optional, but recommended for pageview tracking)
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: { template: '<div><h1>Home Page</h1><router-link to="/about">Go to About</router-link></div>' } },
{ path: '/about', component: { template: '<div><h1>About Page</h1><router-link to="/">Go to Home</router-link></div>' } }
],
});
// 2. Configure vue-gtag options
const gtagOptions: GtagOptions = {
appName: 'my-vue-app',
pageTrackerScreenviewEnabled: true, // Enables automatic pageview tracking
config: {
id: process.env.VUE_APP_GTAG_ID ?? 'G-XXXXXXXXXX', // Use an environment variable for your GA4 Measurement ID
params: {
send_page_view: true,
},
},
router, // Link router for automatic pageview tracking
// consent: {
// granted: ['analytics_storage', 'ad_storage'],
// denied: [],
// default: { analytics_storage: 'denied', ad_storage: 'denied' }
// }
};
// 3. Create and configure Vue App
const app = createApp(App);
app.use(router);
app.use(VueGtag, gtagOptions);
app.mount('#app');
// App.vue (Example component using useGtag composable)
<template>
<div>
<router-view></router-view>
<button @click="trackButtonClick">Track Interaction</button>
</div>
</template>
<script setup lang="ts">
import { useGtag } from 'vue-gtag';
import { onMounted } from 'vue';
const { event, consent } = useGtag();
onMounted(() => {
console.log('App and gtag are ready.');
// Optionally set or update consent based on user interaction
// consent.update({ analytics_storage: 'granted', ad_storage: 'granted' });
});
function trackButtonClick() {
event('custom_button_click', {
event_category: 'engagement',
event_label: 'user_interaction',
value: Math.floor(Math.random() * 100) + 1,
});
console.log('Custom button click event sent.');
}
</script>