Skip to content

Instantly share code, notes, and snippets.

@smakosh
Last active September 19, 2022 13:06
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smakosh/42c381d6d6f7d2882f51737df6e7fd79 to your computer and use it in GitHub Desktop.
Save smakosh/42c381d6d6f7d2882f51737df6e7fd79 to your computer and use it in GitHub Desktop.
Adding Google Analytics to your Next js app
import Error from "next/error";
import Script from "next/script";
import * as gtag from "utils/ga";
import { useEffect } from "react";
import { AppProps } from "next/app";
import { useRouter } from "next/router";
const App = ({ Component, pageProps, err }: AppProps & { err: Error }) => {
const router = useRouter();
useEffect(() => {
const handleRouteChange = (url: string) => {
gtag.pageview(url);
};
router.events.on("routeChangeComplete", handleRouteChange);
return () => {
router.events.off("routeChangeComplete", handleRouteChange);
};
}, [router.events]);
return (
<>
<Script
strategy="afterInteractive"
src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_TRACKING_ID}`}
/>
<Script
id="gtag-init"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${process.env.NEXT_PUBLIC_GA_TRACKING_ID}', {
page_path: window.location.pathname,
send_page_view: false,
});
`,
}}
/>
<Component {...pageProps} err={err} />
</>
);
};
export default App;
export const pageview = (url: string) => {
window.gtag('event', 'page_view', {
page_path: url,
});
};
type GaEventArgs = {
action: string;
category: string;
label: string;
value: string;
};
export const event = ({ action, category, label, value }: GaEventArgs) => {
window.gtag('event', action, {
event_category: category,
event_label: label,
value: value,
});
};
@bacarybruno
Copy link

bacarybruno commented Sep 16, 2022

I think that the pageview event should be this instead:

// see: https://developers.google.com/analytics/devguides/collection/gtagjs/pages#page_view_event
export const pageview = (url: string) => {
  gtag('event', 'page_view', {
    page_path: url,
  });
};

And page_view measurement should also be disabled in App components Scripts: "If you send manual pageviews without disabling pageview measurement, you may end up with pageviews counted twice.". See https://developers.google.com/analytics/devguides/collection/gtagjs/pages#manual_pageviews

// _app.tsx
gtag('config', '${process.env.NEXT_PUBLIC_GA_TRACKING_ID}', {
   send_page_view: false,
});

What do you think @smakosh ?

@smakosh
Copy link
Author

smakosh commented Sep 16, 2022

Interesting, I have been using this in production for the last 2-3 years now, will double check on that, thanks for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment