Security News
Input Validation Vulnerabilities Dominate MITRE's 2024 CWE Top 25 List
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Google Tag integration for Nuxt with support for Google Analytics 4, Google Ads and more.
gtag.js
gtag.js
API# pnpm
pnpm add -D nuxt-gtag
# npm
npm i -D nuxt-gtag
# yarn
yarn add -D nuxt-gtag
Add nuxt-gtag
to the modules
section of your Nuxt configuration and provide your Google tag ID (for multiple tag IDs, see below).
// `nuxt.config.ts`
export default defineNuxtConfig({
modules: ['nuxt-gtag'],
gtag: {
id: 'G-XXXXXXXXXX'
}
})
Done! The gtag.js
script will be loaded and initialized client-side with your Google tag ID when the Nuxt application starts.
[!NOTE] Ensure that the Enhanced measurement feature is enabled to allow
gtag.js
to automatically track page changes based on browser history events in Nuxt.To enable this feature:
- Go to the GA4 reporting view and click on “Admin”
- Select “Data Streams” under the “Property” column.
- Click on your web data stream.
- Next, toggle the switch button near “Enhanced measurement”.
All supported module options can be configured using the gtag
key in your Nuxt configuration. An example of some of the options you can set:
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'
},
}
})
If you want to send data to multiple destinations, you can add more than one Google tag ID to your Nuxt configuration in the tags
module option. Pass a string (single tag ID) or an object (tag ID with additional configuration) to the tags
array.
The following example shows how to load a second Google tag that is connected to a Floodlight destination:
// `nuxt.config.ts`
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'
]
}
})
Instead of hard-coding your Google tag ID in your Nuxt configuration, you can set your desired option in your project's .env
file, leveraging automatically replaced public runtime config values by matching environment variables at runtime.
# Overwrites the `gtag.id` module option
NUXT_PUBLIC_GTAG_ID=G-XXXXXXXXXX
With this setup, you can omit the gtag
key in your Nuxt configuration if you only intend to set the Google tag ID.
[!TIP] Follows the Google Consent Mode v2 specification.
Set a default value for each consent type you are using. By default, no consent mode values are set.
The following example sets multiple consent mode parameters to denied by default:
// `nuxt.config.ts`
export default defineNuxtConfig({
modules: ['nuxt-gtag'],
gtag: {
id: 'G-XXXXXXXXXX',
initCommands: [
// Setup up consent mode
['consent', 'default', {
ad_user_data: 'denied',
ad_personalization: 'denied',
ad_storage: 'denied',
analytics_storage: 'denied',
wait_for_update: 500,
}]
]
}
})
After a user indicates their consent choices, update relevant parameters to granted
:
function allConsentGranted() {
const { gtag } = useGtag()
gtag('consent', 'update', {
ad_user_data: 'granted',
ad_personalization: 'granted',
ad_storage: 'granted',
analytics_storage: 'granted'
})
}
function consentGrantedAdStorage() {
const { gtag } = useGtag()
gtag('consent', 'update', {
ad_storage: 'granted'
})
}
// Invoke the consent function when a user interacts with your banner
consentGrantedAdStorage() // Or `allConsentGranted()`
gtag.js
ScriptFor even more control than the consent mode, you can delay the loading of the gtag.js
script until the user has granted consent to your privacy policy. Set the enabled
option to false
to prevent loading the gtag.js
script until you manually enable it:
export default defineNuxtConfig({
modules: ['nuxt-gtag'],
gtag: {
enabled: false,
id: 'G-XXXXXXXXXX'
}
})
To manually load the Google tag script, i.e. after the user has accepted your privacy policy, you can use the initialize
method destructurable from useGtag
:
<script setup lang="ts">
const { gtag, initialize } = useGtag()
</script>
<template>
<button @click="initialize()">
Grant Consent
</button>
</template>
You can even leave the Google tag ID in your Nuxt config blank and set it dynamically later in your application by passing your ID as the first argument to initialize
. This is especially useful if you want to use a custom ID for each user or if your app manages multiple tenants.
const { gtag, initialize } = useGtag()
function acceptTracking() {
initialize('G-XXXXXXXXXX')
}
Option | Type | Default | Description |
---|---|---|---|
enabled | boolean | true | Whether to initialize the Google tag script immediately after the page has loaded. |
id | string | undefined | The Google tag ID to initialize. |
initCommands | See initCommands of GoogleTagOptions | [] | Commands to be executed when the Google tag ID is initialized. |
config | See config of GoogleTagOptions | {} | The configuration parameters to be passed to gtag.js on initialization. |
tags | string[] | GoogleTagOptions[] | [] | Multiple Google tag IDs to initialize for sending data to different destinations. |
loadingStrategy | 'async' | 'defer' | 'defer' | The loading strategy to be used for the gtag.js script. |
url | string | 'https://www.googletagmanager.com/gtag/js' | The URL to the gtag.js script. Use this option to load the script from a custom URL. |
As with other composables in the Nuxt 3 ecosystem, they are auto-imported and can be used in your application's components.
useGtag
The SSR-safe useGtag
composable provides access to:
gtag.js
instanceinitialize
methoddisableAnalytics
methodenableAnalytics
methodIt can be used as follows:
// Each method is destructurable from the composable and can be
// used on the server and client-side
const { gtag, initialize, disableAnalytics, enableAnalytics } = useGtag()
Type Declarations
function useGtag(): {
gtag: Gtag
initialize: (id?: string) => void
disableAnalytics: (id?: string) => void
enableAnalytics: (id?: string) => void
}
gtag
The gtag
function is the main interface to the gtag.js
instance and can be used to run every gtag.js command.
[!NOTE] Since the
gtag.js
instance is available in the client only, anygtag()
calls executed on the server will have no effect.
Example
The following event command fires the event screen_view
with two parameters: app_name
and screen_name
.
const { gtag } = useGtag()
// SSR-ready
gtag('event', 'screen_view', {
app_name: 'My App',
screen_name: 'Home'
})
Type Declarations
interface GtagCommands {
config: [targetId: string, config?: ControlParams | EventParams | ConfigParams | CustomParams]
set: [targetId: string, config: CustomParams | boolean | string] | [config: CustomParams]
js: [config: Date]
event: [eventName: EventNames | (string & {}), eventParams?: ControlParams | EventParams | CustomParams]
get: [
targetId: string,
fieldName: FieldNames | string,
callback?: (field?: string | CustomParams) => any,
]
consent: [consentArg: ConsentArg | (string & {}), consentParams: ConsentParams]
}
const gtag: {
<Command extends keyof GtagCommands>(command: Command, ...args: GtagCommands[Command]): void
}
initialize
If you want to manually manage the initialization of the Google tag script, i.e. for GDPR compliance, you can use the initialize
method to inject the gtag.js
script to the document's head after the user has accepted your privacy policy. Make sure to set enabled
to false
in the Nuxt module for this to work.
The function accepts an optional ID in case you want to initialize a custom Google tag ID, which isn't set in the module options.
Example
const { initialize } = useGtag()
// Load the `gtag.js` script and initialize all tag IDs from the module options
initialize()
[!TIP] Although this method is SSR-safe, the
gtag.js
script will be loaded in the client only. Make sure to run this method in the client.
Type Declarations
function initialize(id?: string): void
disableAnalytics
In some cases, it may be necessary to disable Google Analytics without removing the Google tag. For example, you might want to provide users with the option to opt out of tracking.
The gtag.js
library includes a window
property that, toggles gtag.js
from sending data to Google Analytics. When Google Analytics attempts to set a cookie or send data back to the Google Analytics servers, this property is checked to determine whether to allow the action.
Example
const { disableAnalytics } = useGtag()
disableAnalytics()
Type Declarations
function disableAnalytics(id?: string): void
enableAnalytics
The enableAnalytics
method is the counterpart to disableAnalytics
and can be used to re-enable Google Analytics after it has been disabled.
Example
const { enableAnalytics } = useGtag()
enableAnalytics()
Type Declarations
function enableAnalytics(id?: string): void
useTrackEvent
Track your defined goals by passing the following parameters:
[!NOTE] This composable is SSR-ready. But since the
gtag.js
instance is available in the client only, executing the composable on the server will have no effect.
Example
For example, the following is an event called login
with a parameter method
:
// Tracks the `login` event
useTrackEvent('login', {
method: 'Google'
})
Type Declarations
function useTrackEvent(
eventName: EventNames | (string & {}),
eventParams?: ControlParams | EventParams | CustomParams
): void
corepack enable
pnpm install
pnpm run dev:prepare
pnpm run dev
gtag.js
API type definitionsMIT License © 2023-PRESENT Johann Schopplich
FAQs
Natively integrates Google Tag into Nuxt
The npm package nuxt-gtag receives a total of 28,823 weekly downloads. As such, nuxt-gtag popularity was classified as popular.
We found that nuxt-gtag demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.