1do the following in _document.js or wherever you defined Head:
2
3<Head>
4 <script
5 async
6 src="https://www.googletagmanager.com/gtag/js?id=[Tracking ID]"
7 />91011131415171819
1export const GA_TRACKING_ID = "<INSERT_TAG_ID>";
2
3// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
4export const pageview = (url: URL): void => {
5 window.gtag("config", GA_TRACKING_ID, {
6 page_path: url,
7 });
8};
9
10type GTagEvent = {
11 action: string;
12 category: string;
13 label: string;
14 value: number;
15};
16
17// https://developers.google.com/analytics/devguides/collection/gtagjs/events
18export const event = ({ action, category, label, value }: GTagEvent): void => {
19 window.gtag("event", action, {
20 event_category: category,
21 event_label: label,
22 value,
23 });
24};
25
1import { AppProps } from "next/app";
2import { useRouter } from "next/router";
3import { useEffect } from "react";
4import * as gtag from "../lib/gtag";
5const isProduction = process.env.NODE_ENV === "production";
6
7const App = ({ Component, pageProps }: AppProps): JSX.Element => {
8 const router = useRouter();
9
10 useEffect(() => {
11 const handleRouteChange = (url: URL) => {
12 /* invoke analytics function only for production */
13 if (isProduction) gtag.pageview(url);
14 };
15 router.events.on("routeChangeComplete", handleRouteChange);
16 return () => {
17 router.events.off("routeChangeComplete", handleRouteChange);
18 };
19 }, [router.events]);
20 // eslint-disable-next-line react/jsx-props-no-spreading
21 return <Component {...pageProps} />;
22};
23
24export default App;
25
26