Skip to content

Instantly share code, notes, and snippets.

@chriswitko
Forked from segunadebayo/NextGA.js
Created February 26, 2021 04:59
Show Gist options
  • Save chriswitko/1a72a8ba3a75fe7ca3a58f9ef7f07183 to your computer and use it in GitHub Desktop.
Save chriswitko/1a72a8ba3a75fe7ca3a58f9ef7f07183 to your computer and use it in GitHub Desktop.
Add Google Analytics to NextJS
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