-
-
Save chriswitko/1a72a8ba3a75fe7ca3a58f9ef7f07183 to your computer and use it in GitHub Desktop.
Add Google Analytics to NextJS
This file contains hidden or 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