Created
December 28, 2021 06:04
-
-
Save hansamlin/1b05df28f97924b5b0f35fbcebd1d6c2 to your computer and use it in GitHub Desktop.
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 Script from 'next/script' | |
import { useRouter } from 'next/router' | |
import * as gtag from './gtag' | |
const App = ({ Component, pageProps }) => { | |
const router = useRouter() | |
useEffect(() => { | |
const handleRouteChange = (url) => { | |
gtag.pageview(url) | |
} | |
router.events.on('routeChangeComplete', handleRouteChange) | |
return () => { | |
router.events.off('routeChangeComplete', handleRouteChange) | |
} | |
}, [router.events]) | |
return ( | |
<> | |
{/* Global Site Tag (gtag.js) - Google Analytics */} | |
<Script | |
strategy="afterInteractive" | |
src={`https://www.googletagmanager.com/gtag/js?id=${gtag.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', '${gtag.GA_TRACKING_ID}', { | |
page_path: window.location.pathname, | |
}); | |
`, | |
}} | |
/> | |
<Component {...pageProps} /> | |
</> | |
) | |
} | |
export default App |
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