Skip to main content
Solved

klaviyo not registering trackViewedItem

  • January 12, 2023
  • 8 replies
  • 456 views

Forum|alt.badge.img+3
  • Contributor III
  • 5 replies

I’m trying to get Klaviyo into a custom integration. Using the new klaviyo object, it’s successfully registering Active On Site and Started Checkout, but not Viewed Product.

I’m injecting the code in NextJS on product pages using next/script (this is the same thing I’m doing for the Active On Site snippet):

<Script
    id='klaviyo-viewed-product'
    dangerouslySetInnerHTML={{
        __html: `
            !(function () {
                if (window.klaviyo) {
                    klaviyo.trackViewedItem({
                        ProductName: "${data?.seminarDetails?.name}",
                        ProductID: "${data?.seminarDetails?.id}",
                        SKU: "${data?.seminarDetails?.__typename}",
                        URL: "${url}",
                        Price: ${data?.seminarDetails?.price}
                    })
                }
            })();
        `
    }}
/>

Since the above isn’t working, I tried wrapping it in some debug logging:

<Script
    id='klaviyo-viewed-product'
    dangerouslySetInnerHTML={{
        __html: `
            !(async function () {
                if (window.klaviyo) {
                    const resp = await klaviyo.trackViewedItem({
                        ProductName: "${data?.seminarDetails?.name}",
                        ProductID: "${data?.seminarDetails?.id}",
                        SKU: "${data?.seminarDetails?.__typename}",
                        URL: "${url}",
                        Price: ${data?.seminarDetails?.price}
                    })
                    .then(() => console.log('Klaviyo back'))
                    .catch((error => console.log(error));
                } else {
                    console.log('No Klaviyo yet');
                }   
            })();
        `   
    }}  
/>

And it’s successfully logging ‘Klaviyo back’, so the core klaviyo object is successfully loading, and it’s making the call without throwing an error, but … nothing is happening on the back end. Any ideas?

Best answer by Brian Turcotte

Hi @ChrisR and @Omar!

 

I did hear back from Engineering about this, and here’s the main point of clarification:

 

I understand that you are expecting to see an event for klaviyo.trackViewedItem, but Klaviyo does not actually record an event for trackViewedItem. Instead, it is just logged in the lower right corner of the individual profile of the viewer:

 

If you want to see an event, you would need to be using the format of a track call:

klaviyo.push(["track", "Viewed Product", {
                                    ProductName: "${data?.seminarDetails?.name}",
                                    ProductID: "${data?.seminarDetails?.id}",
                                    SKU: "${data?.seminarDetails?.__typename}",
                                    URL: "${url}",
                                    Price: ${data?.seminarDetails?.price}
                                }]);

 

This would yield the event that you were hoping to see in the dashboard.

 

I hope this helps, and thanks for using the Community!

- Brian

View original
Did this topic or the replies in the thread help you find an answer to your question?

8 replies

Brian Turcotte
Forum|alt.badge.img+37

Hi @ChrisR and welcome back to the Community!

 

I’m going to reach out to Engineering to provide some more context on this and then I’ll update the thread ASAP - In the meantime, can you confirm that the tracking is definitely working for Active On Site and Started Checkout? Also, could you provide the code snippets you used for those? (with sensitive info redacted)

 

Thanks,

Brian


Forum|alt.badge.img+3
  • Author
  • Contributor III
  • 5 replies
  • January 13, 2023

Thanks @Brian Turcotte . Yes, confirmed that both are working.

Here’s the generic activity tracking:

{/* Klaviyo per-page scripts */}
<Script
id='klaviyo-active-on-site'
src={`https://static.klaviyo.com/onsite/js/klaviyo.js?company_id=${process.env.NEXT_PUBLIC_KLAVIYO_KEY}`}
/>    
<Script
id='klaviyo-object'
dangerouslySetInnerHTML={{
  __html: `
    !(function () {
      if (!window.klaviyo) {
          window._klOnsite = window._klOnsite || [];
          try {   
              window.klaviyo = new Proxy(
                  {},     
                  {       
                      get: function (n, i) {
                          return "push" === i
                              ? function () {
                                    var n;  
                                    (n = window._klOnsite).push.apply(n, arguments);
                                }       
                              : function () {
                                    for (var n = arguments.length, o = new Array(n), w = 0; w < n; w++) o[w] = arguments[w];
                                    var t = "function" == typeof o[o.length - 1] ? o.pop() : void 0, 
                                        e = new Promise(function (n) {
                                            window._klOnsite.push(
                                                [i].concat(o, [
                                                    function (i) {
                                                        t && t(i), n(i);
                                                    },      
                                                ])      
                                            );      
                                        });     
                                    return e;
                                };      
                      },      
                  }       
              );      
          } catch (n) {
              (window.klaviyo = window.klaviyo || []), 
                  (window.klaviyo.push = function () {
                      var n;  
                      (n = window._klOnsite).push.apply(n, arguments);
                  });
          }
      }
    })();
  `
}}
/>

The Started Checkout is a little different, as it’s tied to a React component, instead of a page:

 

async function handleInput(e) {
        e.preventDefault();
        setStartedInput(true);
        const klaviyo = window.klaviyo;

        await klaviyo.identify({})
        .then((profile) => {
            logger.debug({profile}, 'Response from identify');
            if (!profile) return;

            klaviyo.track('Started Checkout', {
                ItemNames: [ `'${activeProductState.name}'` ],
                Items: [
                    {
                        ProductID: activeProductState.id,
                        ProductName: activeProductState.name,
                        Quantity: 1
                    }
                ]
            })
        })        
    }

Looking forward to any help engineering can provide!


Omar
Partner - Platinum
Forum|alt.badge.img+46
  • 2025 Champion
  • 494 replies
  • January 14, 2023

I'm in no way a developer but it seems the code is working but you're not getting the event in Klaviyo. Are you sure the user is identified and the klaviyo script has been loaded?

 

Omar Lovert // Polaris Growth // Klaviyo Master Platinum Partner

Klaviyo - CRO - Customer Value Optimization Specialist


Forum|alt.badge.img+3
  • Author
  • Contributor III
  • 5 replies
  • January 14, 2023

Thanks @Omar . Yes, I’m sure. The other events for the same profile are firing, and I put in the debug logging which makes it clear that on the page in question the script is being loaded.


Forum|alt.badge.img+3
  • Author
  • Contributor III
  • 5 replies
  • January 21, 2023
Brian Turcotte wrote:

I’m going to reach out to Engineering to provide some more context on this and then I’ll update the thread ASAP

Thanks Brian!

Any update from engineering?

I also gave it another shot, attempting to use the promise functionality of the new Klaviyo object, but still no dice. Here’s the updated NextJS code:

            <Script
                id='klaviyo-viewed-product'
                dangerouslySetInnerHTML={{
                    __html: `
                        !(async function () {
                            if (window.klaviyo) {
                                await klaviyo.trackViewedItem({
                                    ProductName: "${data?.seminarDetails?.name}",
                                    ProductID: "${data?.seminarDetails?.id}",
                                    SKU: "${data?.seminarDetails?.__typename}",
                                    URL: "${url}",
                                    Price: ${data?.seminarDetails?.price}
                                })
                                .then(() => {
                                    console.debug('Successfully tracked viewed item');
                                })
                                .catch((error) => {
                                    console.debug({error}, 'Failed to track viewed item');
                                })
                            } else {
                                console.log('No Klaviyo yet');
                            }
                        })();
                    `
                }}
            />

And it’s resolving the promise and successfully logging “Successfully tracked viewed item” in the browser console. But nothing is happening on the Klaviyo dashboard side. :(


Brian Turcotte
Forum|alt.badge.img+37
  • Klaviyo Alum
  • 1393 replies
  • Answer
  • January 25, 2023

Hi @ChrisR and @Omar!

 

I did hear back from Engineering about this, and here’s the main point of clarification:

 

I understand that you are expecting to see an event for klaviyo.trackViewedItem, but Klaviyo does not actually record an event for trackViewedItem. Instead, it is just logged in the lower right corner of the individual profile of the viewer:

 

If you want to see an event, you would need to be using the format of a track call:

klaviyo.push(["track", "Viewed Product", {
                                    ProductName: "${data?.seminarDetails?.name}",
                                    ProductID: "${data?.seminarDetails?.id}",
                                    SKU: "${data?.seminarDetails?.__typename}",
                                    URL: "${url}",
                                    Price: ${data?.seminarDetails?.price}
                                }]);

 

This would yield the event that you were hoping to see in the dashboard.

 

I hope this helps, and thanks for using the Community!

- Brian


Forum|alt.badge.img+3
  • Author
  • Contributor III
  • 5 replies
  • January 26, 2023

Thanks @Brian Turcotte, I was wondering about this, as I had just noticed that little box in the lower right.

This raises a couple of questions.

  1. I assume the track as opposed to trackViewedItem is required to trigger the browse abandonment flow?
  2. If the answer to 1 is “yes”, then what’s the use case for trackViewedItem?

Thanks!
Chris


Forum|alt.badge.img+7
  • Klaviyo Employee
  • 169 replies
  • January 27, 2023
ChrisR wrote:

then what’s the use case for trackViewedItem?

Hi Chris, items passed to trackViewedItem populate “recently viewed products” feeds.

https://help.klaviyo.com/hc/en-us/articles/360019921772-How-to-Insert-Recently-Viewed-Items-into-an-Email