Created
August 23, 2019 13:03
-
-
Save segunadebayo/4c8b506fc4a69a22735b7fa3a21415e4 to your computer and use it in GitHub Desktop.
Add Google Analytics to NextJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import NextHead from 'next/head' | |
import React from 'react' | |
import ReactGA from 'react-ga' | |
import Router from 'next/router' | |
// GA Tracking Id | |
const gaTrackingId = '[GOOGLE ANALYTICS TRACKING ID GOES HERE]' | |
Router.onRouteChangeComplete = () => { | |
ReactGA.initialize(gaTrackingId) | |
ReactGA.pageview(window.location.pathname) | |
} | |
export default class extends React.Component { | |
render () { | |
return ( | |
<NextHead> | |
<script async src={`https://www.googletagmanager.com/gtag/js?id=${gaTrackingId}`} /> | |
<script dangerouslySetInnerHTML={{ __html: ` | |
window.dataLayer = window.dataLayer || [] | |
function gtag(){ | |
dataLayer.push(arguments) | |
} | |
gtag('js', new Date()) | |
gtag('config', '${gaTrackingId}') | |
`}} /> | |
</NextHead> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This version doesn't use
react-ga
library but injects the script directly