/next-gtag

Simple Gtag tracker for Next.js

Primary LanguageTypeScriptMIT LicenseMIT

next-gtag

npm version MIT License code style: prettier

Simple Gtag tracker for Next.js.
Core source code is copied from Next.js official example.

Requirements

  • Next.js (v11.0.0 or later)

Features

  • 👋 Easy and simple to use
  • 🚀 High Performance by next/script
  • 🕳 Zero dependencies

Installation

Using npm

npm install next-gtag

or yarn

yarn add next-gtag

Usage

pages/_app.js:

import { NextGtag } from "next-gtag";

function MyApp({ Component, pageProps }) {
  return (
    <>
      <NextGtag trackingId="YOUR_TRACKING_ID" />
      <Component {...pageProps} />
    </>
  );
}

export default MyApp;

pages/_document.js:

import { Html, Head, Main, NextScript } from 'next/document'
import { gtagScript } from "next-gtag";

export default function Document() {
  return (
    <Html>
      <Head />
      <body>
      <Main />
      <NextScript />
      {gtagScript}
      </body>
    </Html>
  )
}

Then, gtag tracking will be added to your page. 🥳

Util Functions

gtagEvent

gtagEvent is a helper function to track events.
See google document for more details.

import { gtagEvent } from "next-gtag";

gtagEvent('ACTION_NAME', {
  value: 123,
  category: 'CATEGORY_NAME', // optional
  label: 'LABEL_NAME',       // optional
  nonInteraction: false      // optional
})

Contribution

Please feel free to open an issue or make a pull request.

License

Distributed under the MIT License. See LICENSE for more information.