Using Google Analytics with Next.js
React is a JavaScript view library, which is based on components. Next.js uses React for generating views seamlessly on the server as well as the client. This means that we can extend and add tracking functionality to our view components to track user behavior using Google Analytics by faking real page loads (in the traditional sense) in our templates.
Next.js offers a bunch of good examples to work with other use cases, in this case walk through on how to use the React-GA example in your own projects. First to help with working with React there is a utility library called react-ga, that abstracts the Google Analytics library. First start by adding this to your project’s package.json file using Yarn (the NPM client works just as fine):
yarn add react-gaOnce this is done, you’ll have added react-ga as a dependency to your project and the library is available in your node_modules directory. We’ll add our own abstraction layer on top of ReactGA to centralize our tracking logic. Create a utility with the following contents:
// utils/analytics.jsimport ReactGA from 'react-ga'export const initGA = () => {
console.log('GA init')
ReactGA.initialize('UA-xxxxxxxxx-1')
}export const logPageView = () => {
console.log(`Logging pageview for ${window.location.pathname}`)
ReactGA.set({ page: window.location.pathname })
ReactGA.pageview(window.location.pathname)
}export const logEvent = (category = '', action = '') => {
if (category && action) {
ReactGA.event({ category, action })
}
}export const logException = (description = '', fatal = false) => {
if (description) {
ReactGA.exception({ description, fatal })
}
}
The code snippet is pretty self-explanatory. It imports the react-ga module, wraps the boilerplate functionality as initialization with your selected account ID, and logging behind a simple API that we'll use in our React components.
Speaking of components, the next thing we’ll do is create our core layout component:
// components/layout.jsimport React from 'react'
import { initGA, logPageView } from '../utils/analytics'export default class Layout extends React.Component {
componentDidMount () {
if (!window.GA_INITIALIZED) {
initGA()
window.GA_INITIALIZED = true
}
logPageView()
}
render () {
return (
<div>
{this.props.children}
</div>
)
}
}
If you’re familiar with React, you’ll see that what we’re doing is hooking our helper utility to the componentDidMount lifecycle hook. This means that this code will be executed each time the component has been mounted. In this case Next.js and React will handle this behind scenes as users navigate your site.
The output returned by the render function is just the child components wrapped in a div. The component does not add anything to the rendered HTML, all tracking is done via the Google Analytics JavaScript API using our wrapper utility and the ReactGA module.
To use the new component you’ll need to include it in an entrypoint. Create a simple page that extends our layout:
// pages/about.jsimport Layout from '../components/layout'export default () => (
<Layout>
<div>About us</div>
</Layout>
)
With this setup every page load now triggers a GA call. When you navigate from view to view, Next only passes you the data without a complete page load. Since we are taking use of the lifecycle hooks in React to do this — you get easy tracking for your whole Next.js powered application or decoupled website.
