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

Nuxt 3 module to natively integrate Google Analytics

  • 0.6.2
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
30K
decreased by-0.11%
Maintainers
1
Weekly downloads
 
Created
Source

Nuxt Gtag module

Nuxt Gtag

npm version

Nuxt 3 module to integrate Google Analytics 4.

Features

  • 🌻 No dependencies except Google's gtag.js
  • 🤝 Manual consent management for GDPR compliance
  • 📯 Track events manually with composables
  • 🦾 SSR-ready
  • 📂 .env file support

Setup

# pnpm
pnpm add -D nuxt-gtag

# npm
npm i -D nuxt-gtag

Basic Usage

Add nuxt-gtag to the modules section of your Nuxt configuration and provide your Google Analytics measurement ID.

// `nuxt.config.ts`
export default defineNuxtConfig({
  modules: ['nuxt-gtag'],

  gtag: {
    id: 'G-XXXXXXXXXX'
  }
})

Done! Google Analytics will now run in your application's client.

Note

Ensure that the Enhanced measurement feature is enabled to allow Gtag to automatically track page changes based on browser history events in Nuxt.

To enable this feature:

  1. Go to the GA4 reporting view and click on “Admin”
  2. Select “Data Streams” under the “Property” column.
  3. Click on your web data stream.
  4. Next, toggle the switch button near “Enhanced measurement”.

Configuration

All supported module options can be configured using the gtag key in your Nuxt configuration:

export default defineNuxtConfig({
  modules: ['nuxt-gtag'],

  gtag: {
    id: 'G-XXXXXXXXXX',
    config: {
      page_title: 'My Custom Page Title'
    }
  }
})

If you want to disable tracking by default, you can set the initialConsent option to false. This will prevent the gtag.js script from loading until the user has consented to tracking.

export default defineNuxtConfig({
  modules: ['nuxt-gtag'],

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

To manually manage consent, you can use the useGtagConsent composable to set the consent state, e.g. after the user has accepted your cookie policy.

<script setup lang="ts">
function acceptTracking() {
  useGtagConsent({ hasConsent: true })
}
</script>

<template>
  <button @click="acceptTracking">
    Accept Tracking
  </button>
</template>

Runtime Config

Alternatively, leveraging automatically replaced public runtime config values by matching environment variables at runtime, set your desired option in your project's .env file:

# Sets 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 want to set the measurement ID.

Module Options

OptionTypeDefaultDescription
idstringundefinedThe Google Analytics measurement ID.
configRecord<string, any>{}The configuration parameters to be passed to gtag.js on initialization.
initialConsentbooleantrueWhether to initially consent to tracking.
loadingStrategy'async' | 'defer''defer'The loading strategy to be used for the gtag.js script.

Composables

As with other composables in the Nuxt 3 ecosystem, they are auto-imported and can be used in your application's components.

useGtag

The useGtag composable is SSR-safe and can be used to call any of the gtag.js methods.

// SSR-ready
const gtag = useGtag()
gtag(
  // <command>,
  // <command-parameters>
)

ℹ️ Since the Gtag instance is available in the client only, any gtag() (assuming the variable from above) calls executed on the server will have no effect.

Type Declarations

function useGtag(): {
  (command: 'config', targetId: string, config?: Record<string, any>): void
  (command: 'event', eventName: string, eventParams?: Record<string, any>): void
  (command: 'set', targetId: string, config: string | boolean | Record<string, any>): void
  (command: 'set', config: Record<string, any>): void
  (command: 'get', targetId: string, fieldName: string, callback?: (field?: string | Record<string, any>) => void): void
  (command: 'consent', consentArg: string, consentParams: Record<string, any>): void
  (command: 'js', config: Date): void
}

Example

The following event command fires the event screen_view with two parameters: app_name and screen_name.

// SSR-ready
const gtag = useGtag()
gtag('event', 'screen_view', {
  app_name: 'My App',
  screen_name: 'Home'
})

useGtagConsent

If you want to manually manage consent, i.e. for GDPR compliance, you can use the useGtagConsent composable to set the consent state. This composable accepts a single argument, an object with the following properties:

  • hasConsent (optional): Whether to accept or decline the consent. Defaults to true.
  • id (optional): In case you want to initialize a custom Gtag ID. Make sure to set initialConsent to false in the module options beforehand.

If the user has consented, the gtag.js script will be loaded and tracking will begin.

This is only necessary if you have disabled the initialConsent option.

useGtagConsent({
  hasConsent: true
})

ℹ️ Since the Gtag instance is available in the client only, executing the composable on the server will have no effect.

Type Declarations

interface UseGtagConsentOptions {
  /**
   * Whether to accept or decline the consent.
   *
   * @default true
   */
  hasConsent?: boolean
  /**
   * In case you want to initialize a custom Gtag ID. Make sure to set
   * `initialConsent` to `false` in the module options beforehand.
   */
  id?: string
}

function useGtagConsent(options: UseGtagConsentOptions): void

useTrackEvent

Track your defined goals by passing the following parameters:

  • The name of the recommended or custom event
  • A collection of parameters that provide additional information about the event (optional)

ℹ️ Since the Gtag instance is available in the client only, executing the composable on the server will have no effect.

Type Declarations

function useTrackEvent(
  eventName: string,
  eventParams?: Record<string, any>
): void

Example

For example, the following is an event called login with a parameter method:

// Tracks the `login` event
useTrackEvent('login', {
  method: 'Google'
})

💻 Development

  1. Clone this repository
  2. Enable Corepack using corepack enable
  3. Install dependencies using pnpm install
  4. Run pnpm run dev:prepare
  5. Start development server using pnpm run dev

Credits

License

MIT License © 2023-present Johann Schopplich

Keywords

FAQs

Package last updated on 29 Aug 2023

Did you know?

Socket

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.

Install

Related posts

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