Skip to content

Commit

Permalink
🔍 Analytics tracking
Browse files Browse the repository at this point in the history
Closes #56
  • Loading branch information
Luuk de Vlieger committed Aug 21, 2020
1 parent 355fb85 commit 59c4153
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 2 deletions.
1 change: 1 addition & 0 deletions .env.development
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ LANGUAGE=nl
NODE_TLS_REJECT_UNAUTHORIZED=0
SITE_URL=https://localhost:3000
WP_URL=https://headless-wordpress.lndo.site
TRACKING_ID=UA-XXXXXXX-Y
4 changes: 3 additions & 1 deletion next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ const redirects = async () => [
},
]

const { SITE_URL, TRACKING_ID, WP_URL } = process.env

module.exports = transpiled({
env: { SITE_URL: process.env.SITE_URL, WP_URL: process.env.WP_URL },
env: { SITE_URL, TRACKING_ID, WP_URL },
redirects,
})
18 changes: 18 additions & 0 deletions pages/_app.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,24 @@
import 'styles/main.css'
import Router from 'next/router'
import { useEffect } from 'react'

const App = function ({ Component, pageProps }) {
useEffect(() => {
if (process.env.NODE_ENV !== 'production') {
return
}

const sendView = (path) => {
window.gtag('config', process.env.TRACKING_ID, { page_path: path })
}

Router.events.on('routeChangeComplete', sendView)

return () => {
Router.events.off('routeChangeComplete', sendView)
}
}, [])

return <Component {...pageProps} />
}

Expand Down
27 changes: 26 additions & 1 deletion pages/_document.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export default class extends Document {
render() {
return (
<Html lang={process.env.LANGUAGE} className="antialiased">
<Head />
<Head>{process.env.NODE_ENV === 'production' && <Analytics />}</Head>
<body>
<Main />
<NextScript />
Expand All @@ -18,3 +18,28 @@ export default class extends Document {
)
}
}

const Analytics = () => (
<>
<script
async
src={`https://www.googletagmanager.com/gtag/js?id=${process.env.TRACKING_ID}`}
/>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', '${process.env.TRACKING_ID}', {
page_path: window.location.pathname
});
`,
}}
/>
</>
)

0 comments on commit 59c4153

Please sign in to comment.