Created
June 15, 2023 12:19
-
-
Save arbaaz/11302c06d3ae58a6e34696ef77cddec2 to your computer and use it in GitHub Desktop.
Google Analytics in Nextjs
This file contains hidden or 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 { useEffect } from "react"; | |
| import * as gtag from "lib/gtag"; | |
| import { useRouter } from "next/router"; | |
| import Script from "next/script"; | |
| export default function GoogleAnalytics({ enabled }) { | |
| const router = useRouter(); | |
| useEffect(() => { | |
| if (enabled) { | |
| const handleRouteChange = url => { | |
| gtag.pageview(url); | |
| }; | |
| router.events.on("routeChangeComplete", handleRouteChange); | |
| return () => { | |
| router.events.off("routeChangeComplete", handleRouteChange); | |
| }; | |
| } | |
| return () => {}; | |
| }, [router.events, enabled]); | |
| if (!enabled) { | |
| return null; | |
| } | |
| return ( | |
| <> | |
| <Script | |
| strategy="afterInteractive" | |
| src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`} | |
| /> | |
| <Script | |
| id="gtag-init" | |
| strategy="afterInteractive" | |
| // eslint-disable-next-line jam3/no-sanitizer-with-danger | |
| dangerouslySetInnerHTML={{ | |
| __html: ` | |
| window.dataLayer = window.dataLayer || []; | |
| function gtag(){dataLayer.push(arguments);} | |
| gtag('js', new Date()); | |
| gtag('config', '${gtag.GA_TRACKING_ID}', { | |
| page_path: window.location.pathname, | |
| }); | |
| `, | |
| }} | |
| /> | |
| </> | |
| ); | |
| } |
This file contains hidden or 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 GA_TRACKING_ID = process.env.NEXT_PUBLIC_GA_ID; | |
| // https://developers.google.com/analytics/devguides/collection/gtagjs/pages | |
| export const pageview = url => { | |
| window.gtag("config", GA_TRACKING_ID, { | |
| page_path: url, | |
| }); | |
| }; | |
| // https://developers.google.com/analytics/devguides/collection/gtagjs/events | |
| export const event = ({ action, category, label, value }) => { | |
| 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