diff --git a/src/lib/gtag.tsx b/src/lib/gtag.tsx
new file mode 100644
index 00000000..b6656851
--- /dev/null
+++ b/src/lib/gtag.tsx
@@ -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 (
+ <>
+
+
+ >
+ )
+}
diff --git a/src/pages/_app.tsx b/src/pages/_app.tsx
index 328d4f32..434c63d3 100644
--- a/src/pages/_app.tsx
+++ b/src/pages/_app.tsx
@@ -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 (
+
)