Skip to content

Commit 5ec0a10

Browse files
authored
Merge pull request #802 from ethereum-optimism/sc/fix-ga
feat: add GA natively instead of via netlify injection
2 parents d6d3570 + 6c1c601 commit 5ec0a10

File tree

4 files changed

+73
-5
lines changed

4 files changed

+73
-5
lines changed

pages/_app.mdx

Lines changed: 0 additions & 5 deletions
This file was deleted.

pages/_app.tsx

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import '../styles/global.css'
2+
3+
import { useEffect } from 'react'
4+
import { useRouter } from 'next/router'
5+
import * as gtag from '../utils/gtag'
6+
7+
export default function App({ Component, pageProps }) {
8+
const router = useRouter()
9+
useEffect(() => {
10+
const handleRouteChange = (url) => {
11+
gtag.pageview(url)
12+
}
13+
router.events.on('routeChangeComplete', handleRouteChange)
14+
return () => {
15+
router.events.off('routeChangeComplete', handleRouteChange)
16+
}
17+
}, [router.events])
18+
19+
return <Component {...pageProps} />
20+
}

pages/_document.tsx

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import Document, { Html, Head, Main, NextScript } from 'next/document'
2+
3+
import { GA_TRACKING_ID } from '../utils/gtag'
4+
5+
export default class MyDocument extends Document {
6+
render() {
7+
return (
8+
<Html>
9+
<Head>
10+
{/* Global Site Tag (gtag.js) - Google Analytics */}
11+
<script
12+
async
13+
src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
14+
/>
15+
<script
16+
dangerouslySetInnerHTML={{
17+
__html: `
18+
window.dataLayer = window.dataLayer || [];
19+
function gtag(){dataLayer.push(arguments);}
20+
gtag('js', new Date());
21+
22+
gtag('config', '${GA_TRACKING_ID}', {
23+
page_path: window.location.pathname,
24+
});
25+
`,
26+
}}
27+
/>
28+
</Head>
29+
<body>
30+
<Main />
31+
<NextScript />
32+
</body>
33+
</Html>
34+
)
35+
}
36+
}

utils/gtag.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
export const GA_TRACKING_ID = process.env.NEXT_PUBLIC_GA_ID
2+
3+
// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
4+
export const pageview = (url) => {
5+
(window as any).gtag('config', GA_TRACKING_ID, {
6+
page_path: url,
7+
})
8+
}
9+
10+
// https://developers.google.com/analytics/devguides/collection/gtagjs/events
11+
export const event = ({ action, category, label, value }) => {
12+
(window as any).gtag('event', action, {
13+
event_category: category,
14+
event_label: label,
15+
value: value,
16+
})
17+
}

0 commit comments

Comments
 (0)