Using Hotjar and Google Analytics with Next.js to track behavior

romansorin

Roman Sorin

Posted on September 2, 2021

Using Hotjar and Google Analytics with Next.js to track behavior

As a developer, my go-to analytics tools are Hotjar and Google Analytics for both small, personal projects, and more complex applications that attract users. When I get a choice, Next.js is my favorite React framework – it offers server-side rendering (SSR), a growing and responsive community, and integrates easily with my favorite CSS framework, TailwindCSS.

In this tutorial, you'll learn how to easily integrate Hotjar with Google Analytics into your Next.js app. At the time of writing, the current Next.js version is 11. This tutorial assumes that you have already created Google Analytics and Hotjar accounts, and just need to add the codes into your application.

Installing Dependencies

Only one dependency is required for Hotjar – this makes it super simple to add in Hotjar support:

yarn add react-hotjar

Initializing Hotjar

Before you begin, you'll need your tracking code. When you set up your Hotjar site, you'll be presented with a script tag that contains a bunch of Javascript inside of it – find the line that contains h._hjSettings, and get the values for hjid and hjsfv. You'll need both of these.

Navigate to your _app.js document. We'll be adding in a useEffect hook that is initialized when the component mounts, and initializes the Hotjar client.

  1. Import the react-hotjar module, as well as the useEffect hook.
import { hotjar } from 'react-hotjar'
import { useEffect } from 'react'
Enter fullscreen mode Exit fullscreen mode
  1. Once those are imported, you need to add a useEffect hook within your component with an empty dependency array:
useEffect(() => {
  hotjar.initialize(HJID, HJSV)
}, [])
Enter fullscreen mode Exit fullscreen mode

When you're finished, your component should look something like this:

import { hotjar } from 'react-hotjar'
import { useEffect } from 'react'

function MyApp ({ Component, pageProps }) {
  useEffect(() => {
    hotjar.initialize(0123456, 1)
  }, [])

  return <Component {...pageProps} />
}

export default MyApp
Enter fullscreen mode Exit fullscreen mode

That's it for Hotjar! Next, we'll move onto Google Analytics – keep this component ready as we'll need to add another useEffect hook to track GA actions.

Initializing Google Analytics

Before you begin, you'll need your tracking ID for the property you are installing Google Analytics for. If you can't find this tracking ID, Google provides a useful article with step-by-step instructions.

To install Google Analytics, you'll need to find the Head component of your Next.js app. Depending on how you structured your project, you may find this in the index.js file or a separate layout component. This script needs to be present on every page that you want to collect analytics for, so I suggest creating a separate layout component that wraps around your pages.

  1. Add the gtag scripts into your head tag – notice the dangerouslySetInnerHTML attribute. This is required for you to embed this tag but should be used carefully. For more information on this attribute, see this article by LogRocket.

Replace "TRACKING-ID" with the tracking ID that you got earlier.

<script
  async
  src='https://www.googletagmanager.com/gtag/js?id=TRACKING-ID'
></script>
<script
  dangerouslySetInnerHTML={{
    __html: `
   window.dataLayer = window.dataLayer || [];
   function gtag(){dataLayer.push(arguments);}
   gtag('js', new Date());
   gtag('config', 'TRACKING-ID');`
  }}
></script>
Enter fullscreen mode Exit fullscreen mode
  1. If you don't have one already, create a lib directory in the project root and add a file called gtag.js. Add the following functions into your file, and replace "TRACKING-ID" with the previous tracking ID.
export const pageview = url => {
  window.gtag('config', 'TRACKING-ID', {
    page_path: url
  })
}

export const event = ({ action, category, label, value }) => {
  window.gtag('event', action, {
    event_category: category,
    event_label: label,
    value: value
  })
}
Enter fullscreen mode Exit fullscreen mode
  1. Navigate back to _app.js. We will need to add another useEffect hook that is called each time an event occurs. Import the dependencies and the functions that we created in the previous step:
import * as gtag from 'lib/gtag'

import { useEffect } from 'react'
import { useRouter } from 'next/router'
Enter fullscreen mode Exit fullscreen mode
  1. Once those have been imported, you need to initialize the router and add in the useEffect hook that will follow route changes.
const router = useRouter()

useEffect(() => {
  const handleRouteChange = url => {
    gtag.pageview(url)
  }
  router.events.on('routeChangeComplete', handleRouteChange)
  return () => {
    router.events.off('routeChangeComplete', handleRouteChange)
  }
}, [router.events])
Enter fullscreen mode Exit fullscreen mode

When you're finished with both Hotjar and Google Analytics, your component should look like this:

import * as gtag from 'lib/gtag'

import { hotjar } from 'react-hotjar'
import { useEffect } from 'react'
import { useRouter } from 'next/router'

function MyApp ({ Component, pageProps }) {
  const router = useRouter()

  useEffect(() => {
    const handleRouteChange = url => {
      gtag.pageview(url)
    }
    router.events.on('routeChangeComplete', handleRouteChange)
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange)
    }
  }, [router.events])

  useEffect(() => {
    hotjar.initialize(0123456, 1)
  }, [])

  return <Component {...pageProps} />
}

export default MyApp
Enter fullscreen mode Exit fullscreen mode

Wrapping Up

That's it! You should now have Hotjar and Google Analytics collecting data for your site now.

You can find more of my content here.

💖 💪 🙅 🚩
romansorin
Roman Sorin

Posted on September 2, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related