Heap Analytics in NextJs with NextAuthJs | Samelogic Blog

How to setup heap analytics in NextJs and identify users when they log in with NextAuth.Js (Auth.js)
Blog - NextJs Heap NextAuth

How to set up Heap Analytics Web SDK in NextJs and identify the user with NextAuth.Js.

This way, we can know who is doing what and understand our user behaviors better.

Prerequisites

  1. Heap Analytics Account - Follow the instructions to get the script.

  2. Setup basic authentication with NextAuth.Js - Follow their github instructions.

Methods

Since most web apps use multiple analytics sources, we will structure our code to wrap all analytics under one component.

Our file structure will look like this:

We will reference `AnalyticsWrapper` inside our `_app.tsx` component.

🧾 Let's write code

Lets jump right into the main code.

Here we have an `HeapAnalytics` component that does a few things:

  1. It inject's the heap sdk using the NextJs `Script` component.

  2. When the script is ready, it will signal to `useEffect` to setup the identifier. We use useEffect here to watch the state of `session` and `status` since those will change depending on when the component fetches the data.

  3. We then check the `window.heap` object to ensure heap attached itself to the object and then we make the calls to their API.

  4. We are identifying users by email address, so we take that from the session and assign it to heap.

import React, { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import Script from "next/script";
import { config } from "../../utils/config";
export default function HeapAnalytics() {
const { data: session, status } = useSession();
const [scriptLoaded, setScriptLoaded] = useState(false);
useEffect(() => {
if (status === "authenticated" && window.heap) {
console.info("Identifying Heap User...");
window.heap.identify(session.user.email);
window.heap.addUserProperties({
name: session.user.name,
userId: session.user.id,
});
}
}, [scriptLoaded, session, status]);
const scriptReady = () => {
if (window.heap) {
setScriptLoaded(true);
}
};
return (
<Script
id="heap-analytics"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
window.heap=window.heap||[],heap.load=function(e,t){window.heap.appid=e,window.heap.config=t=t||{};var r=document.createElement("script");r.type="text/javascript",r.async=!0,r.src="https://cdn.heapanalytics.com/js/heap-"+e+".js";var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(r,a);for(var n=function(e){return function(){heap.push([e].concat(Array.prototype.slice.call(arguments,0)))}},p=["addEventProperties","addUserProperties","clearEventProperties","identify","resetIdentity","removeEventProperty","setEventProperties","track","unsetEventProperty"],o=0;o<p.length;o++)heap[p[o]]=n(p[o])};
heap.load("${config.tags.HEAP_ANALYTICS}");
`,
}}
onReady={scriptReady}
/>
);
}

❗️Note: Set up your environment variables to differentiate between dev and production, or you will contaminate your data.

The `AnalyticsWrapper` is just a wrapper component around the other analytics scripts (even google tag manager).

In your `_app.tsx`, make sure to setup your `<SessionProvider>` first and then place the `AnalyticsWrapper` inside:

import { useEffect, useState } from "react";
import NextApp, { AppContext, AppProps } from "next/app";
import Head from "next/head";
import Script from "next/script";
import { SessionProvider } from "next-auth/react";
import AnalyticsWrapper from "../components/Analytics/AnalyticsWrapper";
export default function App(props: AppProps) {
const {
Component,
pageProps: { session, ...pageProps },
} = props;
return (
<>
<SessionProvider session={session}>
<Head>
...
</Head>
<AnalyticsWrapper />
<Component {...pageProps} />
</SessionProvider>
</>
);
}

Conclusion

We integrated heap to attach identification to the user who logged in on this website using the code above.

A user in heap will look like this:

This seems to be all that is needed for now.

GLHF!

Struggling to understand user behavior in your product?

Engage your users where they are - right inside your product. Our Smart Intercept Surveys deliver up to 60% response rates, so you can gather candid, contextual feedback effortlessly. Trusted by top SaaS companies.