4

Attempting to import ReactPixel from 'react-facebook-pixel'; but when I do its throwing a reference error that says window is not defined.

 module.exports = require("react-facebook-pixel");

is the particular line of code it is having issues with when I import ReactPixel.

J. M. Arnold
  • 6,261
  • 3
  • 20
  • 38
Ayub Faarah
  • 41
  • 1
  • 2
  • 1
    Does this answer your question? [How to add facebook Pixel on Next.js react app?](https://stackoverflow.com/questions/64792217/how-to-add-facebook-pixel-on-next-js-react-app) – Zsolt Meszaros Mar 18 '21 at 18:14

1 Answers1

5

I am going to guess you are importing facebook-pixel as if it was running on the client-side and not ssr (Which is NextJS). You will need to dynamically important once your component has loaded on the client side:

https://github.com/zsajjad/react-facebook-pixel/issues/53

Use either useEffect:

  React.useEffect(() => {
    import("react-facebook-pixel")
      .then((x) => x.default)
      .then((ReactPixel) => {
        ReactPixel.init(constants.siteMeta.FacebookPixelID);
        ReactPixel.pageView();

        Router.events.on("routeChangeComplete", () => {
          ReactPixel.pageView();
        });
      });
  });

Or componentDidMount()

export default class App extends NextApp {
  componentDidMount() {
    import('react-facebook-pixel')
      .then((x) => x.default)
      .then((ReactPixel) => {
        ReactPixel.init('your-pixel-id');
        ReactPixel.pageView();

        Router.events.on('routeChangeComplete', () => {
          ReactPixel.pageView();
        });
      });
  }
}
Sir Codes Alot
  • 1,149
  • 8
  • 11