Facebook Pixel in NextJS: TypeError: window.fbq is not a function

182 views Asked by At

Attempting to use facebook pixel to track events on client side in my NextJS app-router project.

Pretty much following all steps in NextJS pixel repo: https://github.com/vercel/next.js/tree/canary/examples/with-facebook-pixel/app

I have a pixel.js script in my public/scripts folder. I have the FacebookPixel Component inside my layout.tsx I have the fpixel.js file in my library

However, when I attempt to log any event using the pixel I get an error. Usage:

import * as fbq from "../../../library/third-party/fpixel"
// ...
      fbq.event("Purchase", { currency: "GBP", value: 1 });

and error in the browser is: TypeError: window.fbq is not a function pointing to the fpixel.js file which conveniently exports the event for us to use easily.

Why am I getting this error? Pls help

1

There are 1 answers

0
p--h On

Turns out that at the time of writing, the Next/FB-pixel example on github, in the Facebook Pixel component shows the following:

<Script

    id="fb-pixel"
    src="/scripts/pixel.js"
    strategy="afterInteractive"
    ...

This led to an issue with the pixel loading after components which are contain pixel logic (and are dependent). Therefore switching the strategy to beforeInactive fixed (to load the pixel faster).

For reference: https://nextjs.org/docs/app/api-reference/components/script#optional-props