Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

nuxt-gtag

Package Overview
Dependencies
Maintainers
1
Versions
36
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nuxt-gtag - npm Package Compare versions

Comparing version 1.2.1 to 2.0.1

dist/runtime/analytics.d.ts

186

dist/module.d.ts
import * as _nuxt_schema from '@nuxt/schema';
interface GoogleTagOptions {
/**
* The Google tag ID to initialize.
*/
id: string;
config?: Record<string, any>;
/**
* Additional commands to be executed before the Google tag ID is initialized.
*
* @remarks
* Useful to set the default consent state.
*
* @example
* ```ts
* commands: [
* ['consent', 'default', {
* ad_storage: 'denied',
* ad_user_data: 'denied',
* ad_personalization: 'denied',
* analytics_storage: 'denied'
* }]
* ]
* ```
*
* @default undefined
*/
initCommands?: {
[K in keyof GtagCommands]: [K, ...GtagCommands[K]];
}[keyof GtagCommands][];
/**
* Additional configuration for the Google tag ID, to be set during initialization of the tag ID with the `config' command.
*
* @default undefined
*/
config?: GtagCommands['config'][1];
}
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];
}
type CustomParams = Record<string, any>;
interface ConfigParams {
page_title?: string;
page_location?: string;
page_path?: string;
send_page_view?: boolean;
}
interface ControlParams {
groups?: string | string[];
send_to?: string | string[];
event_callback?: () => void;
event_timeout?: number;
}
type EventNames = 'add_payment_info' | 'add_shipping_info' | 'add_to_cart' | 'add_to_wishlist' | 'begin_checkout' | 'checkout_progress' | 'earn_virtual_currency' | 'exception' | 'generate_lead' | 'join_group' | 'level_end' | 'level_start' | 'level_up' | 'login' | 'page_view' | 'post_score' | 'purchase' | 'refund' | 'remove_from_cart' | 'screen_view' | 'search' | 'select_content' | 'select_item' | 'select_promotion' | 'set_checkout_option' | 'share' | 'sign_up' | 'spend_virtual_currency' | 'tutorial_begin' | 'tutorial_complete' | 'unlock_achievement' | 'timing_complete' | 'view_cart' | 'view_item' | 'view_item_list' | 'view_promotion' | 'view_search_results';
interface EventParams {
checkout_option?: string;
checkout_step?: number;
content_id?: string;
content_type?: string;
coupon?: string;
currency?: string;
description?: string;
fatal?: boolean;
items?: Item[];
method?: string;
number?: string;
promotions?: Promotion[];
screen_name?: string;
search_term?: string;
shipping?: Currency;
tax?: Currency;
transaction_id?: string;
value?: number;
event_label?: string;
event_category?: string;
}
type Currency = string | number;
/**
* Interface of an item object used in lists for this event.
*
* Reference:
* @see {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/events#view_item_item view_item_item}
* @see {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/events#view_item_list_item view_item_list_item}
* @see {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/events#select_item_item select_item_item}
* @see {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/events#add_to_cart_item add_to_cart_item}
* @see {@link https://developers.google.com/analytics/devguides/collection/ga4/reference/events#view_cart_item view_cart_item}
*/
interface Item {
item_id?: string;
item_name?: string;
affiliation?: string;
coupon?: string;
currency?: string;
creative_name?: string;
creative_slot?: string;
discount?: Currency;
index?: number;
item_brand?: string;
item_category?: string;
item_category2?: string;
item_category3?: string;
item_category4?: string;
item_category5?: string;
item_list_id?: string;
item_list_name?: string;
item_variant?: string;
location_id?: string;
price?: Currency;
promotion_id?: string;
promotion_name?: string;
quantity?: number;
}
interface Promotion {
creative_name?: string;
creative_slot?: string;
promotion_id?: string;
promotion_name?: string;
}
type FieldNames = 'client_id' | 'session_id' | 'gclid';
type ConsentArg = 'default' | 'update';
/**
* Reference:
* @see {@link https://support.google.com/tagmanager/answer/10718549#consent-types consent-types}
* @see {@link https://developers.google.com/tag-platform/security/guides/consent consent}
*/
interface ConsentParams {
ad_personalization?: 'granted' | 'denied' | undefined;
ad_user_data?: 'granted' | 'denied' | undefined;
ad_storage?: 'granted' | 'denied';
analytics_storage?: 'granted' | 'denied';
functionality_storage?: 'granted' | 'denied';
personalization_storage?: 'granted' | 'denied';
security_storage?: 'granted' | 'denied';
wait_for_update?: number;
region?: string[];
}
interface ModuleOptions {
/**
* Whether to initialize the Google tag script immediately after the page has loaded.
*
* @remarks
* Set this to `false` to delay the initialization until you call the `enable` function manually.
*
* @default true
*/
enabled?: boolean;
/**
* The Google tag ID to initialize.

@@ -16,28 +164,40 @@ *

/**
* The Google tags to initialize.
* Additional commands to be executed before the Google tag ID is initialized.
*
* @remarks
* Each item can be a string or an object with `id` and `config` properties. The latter is useful especially when you want to set additional configuration for the Google tag ID.
* Useful to set the default consent state. Only applies when `id` is set. For multiple tags, use the `tags` option instead.
*
* @default undefined
* @example
* ```ts
* commands: [
* ['consent', 'default', {
* ad_storage: 'denied',
* ad_user_data: 'denied',
* ad_personalization: 'denied',
* analytics_storage: 'denied'
* }]
* ]
* ```
*
* @default []
*/
tags?: string[] | GoogleTagOptions[];
initCommands: GoogleTagOptions['initCommands'];
/**
* Additional configuration for the Google tag ID to be set when initializing the tag ID with the `config` command.
* Additional configuration for the Google tag ID, to be set during initialization of the tag ID with the `config' command.
*
* @remarks
* Does only apply when `id` is set or the `ids` array contains strings.
* Only applies when `id` is set. For multiple tags, use the `tags` option instead.
*
* @default undefined
* @default {}
*/
config?: Record<string, any>;
config?: GoogleTagOptions['config'];
/**
* Whether to initialize the Google tag script immediately after the page has loaded.
* The Google tags to initialize.
*
* @remarks
* Set this to `false` to delay the initialization until you call the `grantConsent` function manually.
* Each item can be a string or an object with `id` and `config` properties. The latter is useful especially when you want to set additional configuration for the Google tag ID.
*
* @default true
* @default []
*/
initialConsent?: boolean;
tags?: string[] | GoogleTagOptions[];
/**

@@ -44,0 +204,0 @@ * Whether to load the Google tag ID script asynchronously or defer its loading.

2

dist/module.json
{
"name": "nuxt-gtag",
"version": "1.2.1",
"version": "2.0.1",
"configKey": "gtag",

@@ -5,0 +5,0 @@ "compatibility": {

@@ -1,7 +0,7 @@

import type { Gtag, UseGtagConsentOptions } from '../types';
import type { Gtag } from '../types';
export declare function useGtag(): {
gtag: Gtag;
setConsent: ({ id, hasConsent, }: UseGtagConsentOptions) => void;
grantConsent: (id?: string) => void;
revokeConsent: (id?: string) => void;
initialize: (id?: string) => void;
disableAnalytics: (id?: string) => void;
enableAnalytics: (id?: string) => void;
};

@@ -1,2 +0,2 @@

import type { ControlParams, EventNames, EventParams } from '../types';
export declare function useTrackEvent(eventName: EventNames | (string & Record<never, never>), eventParams?: ControlParams | EventParams | Record<string, any>): void;
import type { GtagCommands } from '../types';
export declare function useTrackEvent(...args: GtagCommands['event']): void;
import type { GoogleTagOptions } from './types';
export declare function gtag(command: string, ...args: any[]): void;
export declare function gtag(...args: any[]): void;
/**

@@ -9,15 +9,1 @@ * Initialize the Google tag.

}): void;
/**
* Disable the Google tag if it is a Google Analytics property.
*
* @remarks
* The Google tag library includes a `window['ga-disable-GA_MEASUREMENT_ID']`
* property that, when set to `true`, turns off the Google tag from sending data.
*
* @see https://developers.google.com/analytics/devguides/collection/gtagjs/user-opt-out
*/
export declare function disableGtag(id: string): void;
/**
* Enable Google Analytics if it was disabled before.
*/
export declare function enableGtag(id: string): void;
export interface GoogleTagOptions {
/**
* The Google tag ID to initialize.
*/
id: string;
config?: Record<string, any>;
}
export interface UseGtagConsentOptions {
/**
* Whether to accept or decline the consent.
* Additional commands to be executed before the Google tag ID is initialized.
*
* @default true
* @remarks
* Useful to set the default consent state.
*
* @example
* ```ts
* commands: [
* ['consent', 'default', {
* ad_storage: 'denied',
* ad_user_data: 'denied',
* ad_personalization: 'denied',
* analytics_storage: 'denied'
* }]
* ]
* ```
*
* @default undefined
*/
hasConsent?: boolean;
initCommands?: {
[K in keyof GtagCommands]: [K, ...GtagCommands[K]];
}[keyof GtagCommands][];
/**
* In case you want to initialize a custom Google tag ID. Make sure to set
* `initialConsent` to `false` in the module options beforehand.
* Additional configuration for the Google tag ID, to be set during initialization of the tag ID with the `config' command.
*
* @default undefined
*/
id?: string;
config?: GtagCommands['config'][1];
}
export 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];
}
export interface Gtag {
(command: 'config', targetId: string, config?: ControlParams | EventParams | ConfigParams | Record<string, any>): void;
(command: 'set', targetId: string, config: string | boolean | Record<string, any>): void;
(command: 'set', config: Record<string, any>): void;
(command: 'js', config: Date): void;
(command: 'event', eventName: EventNames | (string & Record<never, never>), eventParams?: ControlParams | EventParams | Record<string, any>): void;
(command: 'get', targetId: string, fieldName: FieldNames | string, callback?: (field?: string | Record<string, any>) => any): void;
(command: 'consent', consentArg: ConsentArg | string, consentParams: ConsentParams): void;
<Command extends keyof GtagCommands>(command: Command, ...args: GtagCommands[Command]): void;
}
export type CustomParams = Record<string, any>;
export interface ConfigParams {

@@ -109,5 +134,7 @@ page_title?: string;

* @see {@link https://support.google.com/tagmanager/answer/10718549#consent-types consent-types}
* @see {@link https://developers.google.com/tag-platform/devguides/consent consent}
* @see {@link https://developers.google.com/tag-platform/security/guides/consent consent}
*/
interface ConsentParams {
ad_personalization?: 'granted' | 'denied' | undefined;
ad_user_data?: 'granted' | 'denied' | undefined;
ad_storage?: 'granted' | 'denied';

@@ -114,0 +141,0 @@ analytics_storage?: 'granted' | 'denied';

{
"name": "nuxt-gtag",
"type": "module",
"version": "1.2.1",
"packageManager": "pnpm@8.15.3",
"version": "2.0.1",
"packageManager": "pnpm@8.15.4",
"description": "Natively integrates Google Tag into Nuxt",

@@ -45,3 +45,3 @@ "author": "Johann Schopplich <pkg@johannschopplich.com>",

"dependencies": {
"@nuxt/kit": "^3.10.2",
"@nuxt/kit": "^3.10.3",
"defu": "^6.1.4",

@@ -54,8 +54,7 @@ "pathe": "^1.1.2",

"@nuxt/module-builder": "^0.5.5",
"@nuxt/schema": "^3.10.2",
"@types/node": "^20.11.19",
"@nuxt/schema": "^3.10.3",
"@types/node": "^20.11.20",
"bumpp": "^9.3.0",
"eslint": "^8.56.0",
"nuxt": "^3.10.2",
"nuxt-gtag": "workspace:*",
"eslint": "^8.57.0",
"nuxt": "^3.10.3",
"typescript": "^5.3.3",

@@ -62,0 +61,0 @@ "vue-tsc": "^1.8.27"

@@ -11,10 +11,10 @@ ![Nuxt Google Tag module](./.github/social-card.jpg)

- 🌻 No dependencies except Google's `gtag.js`
- 🛍️ For Google Analytics 4, Google Ads and other products
- 🤝 Manual [consent management](#consent-management) for GDPR compliance
- 🌻 Zero dependencies except Google's `gtag.js`
- 🛍️ Use Google Analytics 4, Google Ads and other products
- 🛎️ Supports [Google Consent Mode v2](#google-consent-mode)
- 🤝 Manually [initialize](#manually-load-gtagjs-script) a Google tag
- 🔢 Supports [multiple tag IDs](#multiple-google-tags)
- 📯 Track events manually with [composables](#composables)
- 📯 Track events with [composables](#composables)
- 🏷️ Fully typed `gtag.js` API
- 🦾 SSR-ready
- 📂 [`.env` file support](#configuration)

@@ -61,10 +61,7 @@ ## Setup

### Multiple Google Tags
## Configuration
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.
All [supported module options](#module-options) can be configured using the `gtag` key in your Nuxt configuration. An example of some of the options you can set:
The following example shows how to load a second Google tag that is connected to a Floodlight destination. To send data to Floodlight (tag ID `DC-ZZZZZZZZZZ`), add another config command after initializing the first Google tag (tag ID `GT-XXXXXXXXXX`):
```ts
// `nuxt.config.ts`
export default defineNuxtConfig({

@@ -74,6 +71,8 @@ modules: ['nuxt-gtag'],

gtag: {
tags: [
'GT-XXXXXXXXXX', // Google Ads and GA4
'DC-ZZZZZZZZZZ' // Floodlight
]
// Your primary Google tag ID
id: 'G-XXXXXXXXXX',
// Additional configuration for this tag ID
config: {
page_title: 'My Custom Page Title'
},
}

@@ -83,4 +82,8 @@ })

Or use the object syntax to initialize multiple tags with different configurations:
### Multiple Google Tags
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:
```ts

@@ -93,14 +96,11 @@ // `nuxt.config.ts`

tags: [
// Google Ads and GA4, with additional configuration
{
id: 'GT-XXXXXXXXXX',
id: 'G-XXXXXXXXXX',
config: {
page_title: 'GA4'
page_title: 'My Custom Page Title'
}
},
{
id: 'DC-ZZZZZZZZZZ',
config: {
page_title: 'Floodlight'
}
}
// Second Google tag ID for Floodlight
'DC-ZZZZZZZZZZ'
]

@@ -111,7 +111,24 @@ }

## Configuration
### Runtime Config
All [supported module options](#module-options) can be configured using the `gtag` key in your Nuxt configuration. An example of some of the options you can set:
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](https://nuxt.com/docs/api/nuxt-config#runtimeconfig) by matching environment variables at runtime.
```ini
# 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.
### Google Consent Mode
> [!TIP]
> Follows the [Google Consent Mode v2](https://developers.google.com/tag-platform/security/guides/consent) 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:
```ts
// `nuxt.config.ts`
export default defineNuxtConfig({

@@ -121,13 +138,12 @@ 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'
},
// To send data to multiple destinations, use this option instead:
tags: [
'GT-XXXXXXXXXX', // Google Ads and GA4
'DC-ZZZZZZZZZZ' // Floodlight
initCommands: [
// Setup up consent mode
['consent', 'default', {
ad_user_data: 'denied',
ad_personalization: 'denied',
ad_storage: 'denied',
analytics_storage: 'denied',
wait_for_update: 500,
}]
]

@@ -138,17 +154,30 @@ }

### Runtime Config
After a user indicates their consent choices, update relevant parameters to `granted`:
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](https://nuxt.com/docs/api/nuxt-config#runtimeconfig) by matching environment variables at runtime.
```ts
function allConsentGranted() {
const { gtag } = useGtag()
gtag('consent', 'update', {
ad_user_data: 'granted',
ad_personalization: 'granted',
ad_storage: 'granted',
analytics_storage: 'granted'
})
}
```ini
# Overwrites the `gtag.id` module option
NUXT_PUBLIC_GTAG_ID=G-XXXXXXXXXX
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()`
```
With this setup, you can omit the `gtag` key in your Nuxt configuration if you only intend to set the Google tag ID.
### Manually Load `gtag.js` Script
### Consent Management
For even more control than the [consent mode](#set-up-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:
For GDPR compliance, you may want to delay the loading of the `gtag.js` script until the user has granted consent. Set the `initialConsent` option to `false` to prevent the `gtag.js` script from loading until you manually enable it.
```ts

@@ -159,4 +188,4 @@ export default defineNuxtConfig({

gtag: {
id: 'G-XXXXXXXXXX',
initialConsent: false
enabled: false,
id: 'G-XXXXXXXXXX'
}

@@ -166,12 +195,12 @@ })

To manually manage consent, you can use the [`grantConsent` method destructurable from `useGtag`](#usegtag) to set the consent state, e.g. after the user has accepted your cookie policy.
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`](#usegtag):
```vue
<script setup lang="ts">
const { gtag, grantConsent, revokeConsent } = useGtag()
const { gtag, initialize } = useGtag()
</script>
<template>
<button @click="grantConsent()">
Accept Tracking
<button @click="initialize()">
Grant Consent
</button>

@@ -183,9 +212,9 @@ </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 `grantConsent`. This is especially useful if you want to use a custom ID for each user or if your app manages multiple tenants.
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.
```ts
const { gtag, grantConsent, revokeConsent } = useGtag()
const { gtag, initialize } = useGtag()
function acceptTracking() {
grantConsent('G-XXXXXXXXXX')
initialize('G-XXXXXXXXXX')
}

@@ -198,6 +227,7 @@ ```

| --- | --- | --- | --- |
| `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. |
| `config` | `Record<string, any>` | `undefined` | The [configuration parameters](https://developers.google.com/analytics/devguides/collection/ga4/reference/config) to be passed to `gtag.js` on initialization. |
| `initCommands` | See `initCommands` of `GoogleTagOptions` | `[]` | Commands to be executed when the Google tag ID is initialized. |
| `config` | See `config` of `GoogleTagOptions` | `{}` | The [configuration parameters](https://developers.google.com/analytics/devguides/collection/ga4/reference/config) to be passed to `gtag.js` on initialization. |
| `tags` | `string[] \| GoogleTagOptions[]` | `[]` | Multiple Google tag IDs to initialize for sending data to different destinations. |
| `initialConsent` | `boolean` | `true` | Whether to initialize the Google tag script immediately after the page has loaded. |
| `loadingStrategy` | `'async' \| 'defer'` | `'defer'` | The loading strategy to be used for the `gtag.js` script. |

@@ -215,4 +245,5 @@ | `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. |

- The `gtag.js` instance
- The `grantConsent` method
- The `revokeConsent` method
- The `initialize` method
- The `disableAnalytics` method
- The `enableAnalytics` method

@@ -224,3 +255,3 @@ It can be used as follows:

// used on the server and client-side
const { gtag, grantConsent, revokeConsent } = useGtag()
const { gtag, initialize, disableAnalytics, enableAnalytics } = useGtag()
```

@@ -233,4 +264,5 @@

gtag: Gtag
grantConsent: (id?: string) => void
revokeConsent: (id?: string) => void
initialize: (id?: string) => void
disableAnalytics: (id?: string) => void
enableAnalytics: (id?: string) => void
}

@@ -241,4 +273,11 @@ ```

The `gtag` function is the main interface to the `gtag.js` instance and can be used to call any of the [gtag.js methods](https://developers.google.com/tag-platform/gtagjs/reference).
The `gtag` function is the main interface to the `gtag.js` instance and can be used to run every [gtag.js command](https://developers.google.com/tag-platform/gtagjs/reference).
> [!NOTE]
> Since the `gtag.js` instance is available in the client only, any `gtag()` 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`.
```ts

@@ -254,69 +293,77 @@ const { gtag } = useGtag()

> [!NOTE]
> Since the `gtag.js` instance is available in the client only, any `gtag()` calls executed on the server will have no effect.
**Type Declarations**
```ts
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: 'config', targetId: string, config?: ControlParams | EventParams | ConfigParams | Record<string, any>): void
(command: 'set', targetId: string, config: string | boolean | Record<string, any>): void
(command: 'set', config: Record<string, any>): void
(command: 'js', config: Date): void
(command: 'event', eventName: EventNames | (string & Record<never, never>), eventParams?: ControlParams | EventParams | Record<string, any>): void
(command: 'get', targetId: string, fieldName: FieldNames | string, callback?: (field?: string | Record<string, any>) => any): void
(command: 'consent', consentArg: ConsentArg | string, consentParams: ConsentParams): void
<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**
The following event command fires the event `screen_view` with two parameters: `app_name` and `screen_name`.
```ts
const { gtag } = useGtag()
const { initialize } = useGtag()
// SSR-ready
gtag('event', 'screen_view', {
app_name: 'My App',
screen_name: 'Home'
})
// Load the `gtag.js` script and initialize all tag IDs from the module options
initialize()
```
#### `grantConsent`
> [!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.
If you want to manually manage consent, i.e. for GDPR compliance, you can use the `grantConsent` method to initialize the `gtag.js` script after the user has accepted your cookie policy. Make sure to set `initialConsent` to `false` in the module options beforehand.
**Type Declarations**
This function accepts an optional ID in case you want to initialize a custom Google tag ID and haven't set it in the module options.
```ts
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**
```ts
const { grantConsent } = useGtag()
const { disableAnalytics } = useGtag()
// When called, the `gtag.js` script will be loaded all tag IDs initialized
grantConsent()
disableAnalytics()
```
> [!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**
```ts
function grantConsent(id?: string): void
function disableAnalytics(id?: string): void
```
#### `revokeConsent`
#### `enableAnalytics`
If a user has previously granted consent, you can use the `revokeConsent` method to revoke the consent. It will prevent the Google tag from sending data until the consent is granted again.
The `enableAnalytics` method is the counterpart to `disableAnalytics` and can be used to re-enable Google Analytics after it has been disabled.
> [!Note]
> This works only with Google Analytics 4 tags
**Example**
This function accepts an optional ID in case you haven't set it in the module options. Make sure to pass the same ID that was used to grant the consent.
```ts
const { revokeConsent } = useGtag()
const { enableAnalytics } = useGtag()
// When called, the `gtag.js` script will be stopped from tracking events
revokeConsent()
enableAnalytics()
```

@@ -327,3 +374,3 @@

```ts
function revokeConsent(id?: string): void
function enableAnalytics(id?: string): void
```

@@ -341,11 +388,2 @@

**Type Declarations**
```ts
function useTrackEvent(
eventName: EventNames | (string & Record<never, never>),
eventParams?: ControlParams | EventParams | Record<string, any>,
): void
```
**Example**

@@ -362,2 +400,11 @@

**Type Declarations**
```ts
function useTrackEvent(
eventName: EventNames | (string & {}),
eventParams?: ControlParams | EventParams | CustomParams
): void
```
## 💻 Development

@@ -364,0 +411,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc