Skip to content

Commit 55bec40

Browse files
committed
Add Google Analytics
1 parent 1f1b928 commit 55bec40

3 files changed

Lines changed: 31 additions & 2 deletions

File tree

src/lib/ga/index.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
export const pageview = (url) => {
2+
window.gtag('config', process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS, {
3+
page_path: url,
4+
})
5+
}
6+
7+
// log specific events happening.
8+
export const event = ({ action, params }) => {
9+
window.gtag('event', action, params)
10+
}

src/pages/_app.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import Router from 'next/router'
1010
import { Fragment, useEffect, useState } from 'react'
1111
import '../css/fonts.css'
1212
import '../css/main.css'
13+
import * as ga from '../lib/ga'
1314

1415
if (typeof window !== 'undefined' && !('ResizeObserver' in window)) {
1516
window.ResizeObserver = ResizeObserver
@@ -41,14 +42,15 @@ export default function App({ Component, pageProps, router }) {
4142

4243
useEffect(() => {
4344
if (!navIsOpen) return
44-
function handleRouteChange() {
45+
function handleRouteChange(url) {
4546
setNavIsOpen(false)
47+
ga.pageview(url)
4648
}
4749
Router.events.on('routeChangeComplete', handleRouteChange)
4850
return () => {
4951
Router.events.off('routeChangeComplete', handleRouteChange)
5052
}
51-
}, [navIsOpen])
53+
}, [navIsOpen],[router.events])
5254

5355
const Layout = Component.layoutProps?.Layout || Fragment
5456
const layoutProps = Component.layoutProps?.Layout

src/pages/_document.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,23 @@ export default class Document extends NextDocument {
2222
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#3884ff" />
2323
<meta name="theme-color" content="#ffffff" />
2424
<meta name="google-site-verification" content="OMYBoUbVEYAJu6SsOajfrvkTJunKMieK9ZhAgOFHobM"/>
25+
{/* Global Site Tag (gtag.js) - Google Analytics */}
26+
<script
27+
async
28+
src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`}
29+
/>
30+
<script
31+
dangerouslySetInnerHTML={{
32+
__html: `
33+
window.dataLayer = window.dataLayer || [];
34+
function gtag(){dataLayer.push(arguments);}
35+
gtag('js', new Date());
36+
gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}', {
37+
page_path: window.location.pathname,
38+
});
39+
`,
40+
}}
41+
/>
2542
</Head>
2643
<body>
2744
<Main />

0 commit comments

Comments
 (0)