Skip to content

Instantly share code, notes, and snippets.

@segunadebayo
Created August 23, 2019 13:03
Show Gist options
  • Save segunadebayo/4c8b506fc4a69a22735b7fa3a21415e4 to your computer and use it in GitHub Desktop.
Save segunadebayo/4c8b506fc4a69a22735b7fa3a21415e4 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>
)
}
}
@segunadebayo
Copy link
Author

This version doesn't use react-ga library but injects the script directly

import React from 'react'
import Document, { Head, Main, NextScript } from 'next/document'

export default class extends Document {
  render () {
    return (
      <html>
        <Head>
          {/* Global Site Tag (gtag.js) - Google Analytics */}
          <script
            async
            src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
          />
          <script
            dangerouslySetInnerHTML={{
              __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${GA_TRACKING_ID}');
          `
            }}
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    )
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment