ReferenceError: window is not defined on NextJs

Viewed 5996

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.

1 Answers

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();
        });
      });
  }
}
Related