Last active
September 19, 2022 13:06
-
-
Save smakosh/42c381d6d6f7d2882f51737df6e7fd79 to your computer and use it in GitHub Desktop.
Adding Google Analytics to your Next js app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Interesting, I have been using this in production for the last 2-3 years now, will double check on that, thanks for sharing!