Google Tag Manager is a tag management system that allows you to quickly and easily update tags and code snippets on your website or mobile app, such as those intended for traffic analysis and marketing optimization.
useScriptGoogleAnalytics
composable instead.If you'd like to avoid loading the analytics in development, you can use the Environment overrides in your Nuxt config.
export default defineNuxtConfig({
scripts: {
registry: {
googleTagManager: {
id: '<YOUR_ID>'
}
}
}
})
The useScriptGoogleTagManager
composable lets you have fine-grain control over when and how Google Tag Manager is loaded on your site.
const { proxy } = useScriptGoogleTagManager({
id: 'YOUR_ID' // id is only needed if you haven't configured globally
})
// example
proxy.dataLayer.push({ event: 'conversion', value: 1 })
Please follow the Registry Scripts guide to learn more about proxy
.
If you'd like to manually send page events to Google Tag Manager, you can use the proxy
with the useScriptEventPage composable.
This composable will trigger the provided function on route change after the page title has been updated.
const { proxy } = useScriptGoogleTagManager({
id: 'YOUR_ID' // id is only needed if you haven't configured globally
})
useScriptEventPage((title, path) => {
// triggered on route change after title is updated
proxy.dataLayer.push({
event: 'pageview',
title,
path
})
})
interface GoogleTagManagerApi {
dataLayer: Record<string, any>[]
google_tag_manager: GoogleTagManager
}
You must provide the options when setting up the script for the first time.
export const GoogleTagManagerOptions = object({
/**
* The Google Tag Manager ID.
*/
id: string(),
/**
* The name of the dataLayer you want to use
* @default 'dataLayer'
*/
dataLayerName: optional(string())
})
type GoogleTagManagerInput = typeof GoogleTagManagerOptions & { onBeforeGtmStart?: ((gtag: Gtag) => void) => void }
Using Google Tag Manager only in production while using dataLayer
to send a conversion event.
<script setup lang="ts">
const { dataLayer } = useScriptGoogleTagManager()
// noop in development, ssr
// just works in production, client
dataLayer.push({ event: 'conversion-step', value: 1 })
function sendConversion() {
dataLayer.push({ event: 'conversion', value: 1 })
}
</script>
<template>
<div>
<button @click="sendConversion">
Send Conversion
</button>
</div>
</template>
useScriptGoogleTagManager
initialize Google Tag Manager by itself. This means it pushes the js
, config
and the gtm.start
events for you.
If you need to configure GTM before it starts. For example, setting the consent mode. You can use the onBeforeGtmStart
hook which is run right before we push the gtm.start
event into the dataLayer.