Add GA
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
import { NextRouter } from 'next/router'
|
||||
import Script from 'next/script'
|
||||
import { useEffect } from 'react'
|
||||
|
||||
export const GA_TRACKING_ID = process.env.NEXT_PUBLIC_GA_ID
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
gtag: any
|
||||
}
|
||||
}
|
||||
|
||||
// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
|
||||
export const pageview = (url: string) => {
|
||||
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,
|
||||
}: {
|
||||
action: string
|
||||
category: string
|
||||
label: string
|
||||
value: string
|
||||
}) => {
|
||||
window.gtag('event', action, {
|
||||
event_category: category,
|
||||
event_label: label,
|
||||
value: value,
|
||||
})
|
||||
}
|
||||
|
||||
export function useGtagPageViewReport(router: NextRouter) {
|
||||
useEffect(() => {
|
||||
const handleRouteChange = (url: string) => {
|
||||
pageview(url)
|
||||
}
|
||||
router.events.on('routeChangeComplete', handleRouteChange)
|
||||
router.events.on('hashChangeComplete', handleRouteChange)
|
||||
return () => {
|
||||
router.events.off('routeChangeComplete', handleRouteChange)
|
||||
router.events.off('hashChangeComplete', handleRouteChange)
|
||||
}
|
||||
}, [router])
|
||||
}
|
||||
|
||||
export const GtagScript = () => {
|
||||
return (
|
||||
<>
|
||||
<Script
|
||||
strategy='afterInteractive'
|
||||
src={`https://www.googletagmanager.com/gtag/js?id=${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', '${GA_TRACKING_ID}', {
|
||||
page_path: window.location.pathname,
|
||||
});
|
||||
`,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { useRouter } from 'next/router'
|
||||
import '../styles/nprogress.css'
|
||||
import '../styles/nextjs.css'
|
||||
import Head from 'next/head'
|
||||
import { GtagScript, useGtagPageViewReport } from '../lib/gtag'
|
||||
|
||||
function MyApp({ Component, pageProps }: AppProps) {
|
||||
const router = useRouter()
|
||||
@@ -30,11 +31,14 @@ function MyApp({ Component, pageProps }: AppProps) {
|
||||
}
|
||||
}, [router])
|
||||
|
||||
useGtagPageViewReport(router)
|
||||
|
||||
return (
|
||||
<ThemeProvider theme={theme}>
|
||||
<Head>
|
||||
<meta name='viewport' content='initial-scale=1.0, width=device-width' />
|
||||
</Head>
|
||||
<GtagScript />
|
||||
<Component {...pageProps} />
|
||||
</ThemeProvider>
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user