Simple Gtag tracker for Next.js.
Core source code is copied from Next.js official example.
- Next.js (v11.0.0 or later)
- 👋 Easy and simple to use
- 🚀 High Performance by next/script
- 🕳 Zero dependencies
Using npm
npm install next-gtag
or yarn
yarn add next-gtag
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. 🥳
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
})
Please feel free to open an issue or make a pull request.
Distributed under the MIT License. See LICENSE for more information.