Step by step guide on how to integrate hotjar with nextjs

Hotjar is a great way to find out how users are interacting with your website.

It's easy to setup and you can get a free account that allows you to do more than simply evaluate the software, you'll get real user insights, and learn about user behaviour rather than make assumptions.

To demonstrate, here's a video of a visitor to this website who was interacting with my theme generator.

Setting up hotjar

Sign up for a free account with Hotjar, follow the setup instructions.

You'll get to apoint where they ask you to embed a script on every page of your website in the <head/> of each page.

Add the tracking script

With Nextjs it's simply a matter of grabbing the script, and adding it into a <Script/> component in the root layout.tsx file if you using app router, if you're using pages router then add it to _app.tsx.

Personally, I like to kep things neat and tidy so create a component for the script and then import it, here's the file:

// Hotjar.tsx
 
"use client";
import Script from "next/script";
import { HOTJAR_ID } from "@/utils/constants";
 
const HotJar = () => {
  if (process.env.NODE_ENV === "production" && HOTJAR_ID) {
    return (
      <Script id="hotjar">
        {`
          (function (h, o, t, j, a, r) {
            h.hj =
              h.hj ||
              function () {
                // eslint-disable-next-line prefer-rest-params
                (h.hj.q = h.hj.q || []).push(arguments);
              };
            h._hjSettings = { hjid: ${HOTJAR_ID}, hjsv: 6 };
            a = o.getElementsByTagName("head")[0];
            r = o.createElement("script");
            r.async = 1;
            r.src = t + h._hjSettings.hjid + j + h._hjSettings.hjsv;
            a.appendChild(r);
          })(window, document, "https://static.hotjar.com/c/hotjar-", ".js?sv=");
        `}
      </Script>
    );
  }
  return null;
};
 
export { HotJar };

Make sure to pass your hotjar id to this variable HOTJAR_ID.

That's all there is to it, enjoy.