formerly I was using react-ga npm module to insert google analytics in my next js app. and It was simply like this:
import ReactGA from 'react-ga'
export const initGA = () => {
ReactGA.initialize('UA-*******-*', {
titleCase: false
})
}
export const logPageView = () => {
if (window.location.href.split('?')[1]) {
ReactGA.set({page: window.location.pathname + '?' + window.location.href.split('?')[1]})
ReactGA.pageview(window.location.pathname + '?' + window.location.href.split('?')[1])
} else {
ReactGA.set({page: window.location.pathname})
ReactGA.pageview(window.location.pathname)
}
}
and then I was calling logPageView function in my header(that was inserted to every page of my app) like this:
componentDidMount () {
if (!window.GA_INITIALIZED) {
initGA()
window.GA_INITIALIZED = true
}
logPageView()
}
componentWillReceiveProps () {
if (!window.GA_INITIALIZED) {
initGA()
window.GA_INITIALIZED = true
}
logPageView()
}
now I want to use Google Tag Manager to handle Analytics page view . How could I do this?
In order to use Google Tag Manager you should inject your tag manager script on every page. since _document.js
is the wrapper for every page, you should add the GTM script to _document.js
in the head section like this:
<Head>
<script dangerouslySetInnerHTML={{
__html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-*****');`,
}}>
</script>
...
</Head>
Now you are all set to use Google Tag Manager in your next-js app. You should only proceed to handle pageview and other analytics related stuff from your GTM dashboard.
To set up google analytics pageview for single page applications(like nextjs) you can follow these steps.