Question

Using Heap client API in next.js project

  • 2 May 2024
  • 1 reply
  • 31 views

Badge +1

Hi community,

I’ve been trying to implement Heap on my next.js website. Adding the <script> tags was straightforward and clicks and views are tracking without any issues.

However, I’d like to track some custom events using the heap.track() and use the heap.addUserProperties() APIs. I’ve been trying many different approaches, but can’t figure out an elegant way to do it. Is there a way to access the window.heap API I initialise in the <script> tags from the methods in my client components?

I tried to look into the url below too, but wasn’t able to apply it to a next.js configuration.

https://help.heap.io/data-management/code-and-framework-management/using-heap-with-popular-web-frameworks-libraries/

I prefer not to use the server side REST API since I want to include the session data.

Thanks in advance for any help!

Best regards,

Tobi


1 reply

Badge +1

Managed to find a way to make it work now. Here is how I did it:

Just configured a very simple heap service file as shown below. Make sure that it is a client function so you have access to the window object. I can call the functions in my HeapService file from all my client components that have the <script> tags in their <head> now.

I also had to add reactStrictMode: false to my next.config.mjs file because this made my components render twice, causing my events to fire twice as well.

 

'use client';

 

export const trackHeapEvent = (event: string, properties: Record<string, any>) => {

window.heap.track(event, properties);

console.log(`Heap track: [${event}] with properties:`, properties);

};

 

Hope this is helpful for others!

Reply