Roman Sorin

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. 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 scripts 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";
  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);
}, []);

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;

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>
  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,
  });
};
  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";
  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]);

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;

Wrapping Up

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

Return home