I am sorry for this noob question, I just start to use a next.js template form https://github.com/zeit/next.js/tree/canary/examples/hello-world/pages Normally I would just add gtag.js to index.html but for this next.js there is only index.js. The question is how I can include this? I had tried to make gtag as a component and try to import it and also include the script as it is inside render function of index.js but so far it is not working! please help me!
Gtag:
<script async src="https://www.googletagmanager.com/gtag/js?
id=GA_TRACKING_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA_TRACKING_ID');
</script>
index.js:
import Link from 'next/link'
export default () => (
<div>Hello World. <Link href='/about'><a>About</a></Link></div>
)
To install the Google tag, copy the following code and paste it immediately after the <head> tag on every page of your site. Replace GA_TRACKING_ID with the ID of the Google Analytics property to which you want to send data. You need only one snippet per page.
You can add the gtag func as lib like this:
export const GA_TRACKING_ID = '<YOUR_GA_TRACKING_ID>'
// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
export const pageview = url => {
window.gtag('config', GA_TRACKING_ID, {
page_location: url
})
}
// https://developers.google.com/analytics/devguides/collection/gtagjs/events
export const event = ({ action, category, label, value }) => {
window.gtag('event', action, {
event_category: category,
event_label: label,
value: value
})
}
For complete example of how to add google analytics in NextJS, you can take a look here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With