1

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
  • Have you checked that the path is correct? Commented Feb 17, 2024 at 17:52

2 Answers 2

2

@p--h from what I debug, if you change to strategy="beforeInactive". Script will not function as we expect. One thing you should try if you are using middleware.js in your application is adding scripts into matcher.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.