Skip to content

Instantly share code, notes, and snippets.

@smakosh
Last active September 19, 2022 13:06
Show Gist options
  • 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,
});
};
@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