0

I initially had a create-react-app working and I decided to migrate the app to NextJS. So far everything is good but I have a utility file (src/lib/utils.ts) where I'm getting an error that I can't quite figure out as I am new to NextJS.

const setReferrer = () => {
    const referrer = document.referrer;
    ...
};

This worked in create-react-app but in NextJS I'm getting this error:

Server Error
ReferenceError: document is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.

When I comment this code out, I also get errors when getting the resolution of the device:

const setResolution = () => {
    const resolution =
        window.screen.width * window.devicePixelRatio + 'x' + window.screen.height * window.devicePixelRatio;
    ...
};

In which case it's the window not being defined.

Is it a different process for getting these data with NextJS compared to create-react-app?

dokgu
  • 4,957
  • 3
  • 39
  • 77
  • Where are you calling these functions? You may need to wrap them in an effect hook to ensure they run on the client-side – Phil Feb 14 '23 at 03:35
  • @Phil on CRA, I have a utility file to initialize sentry.io from the entry point `index.js` before rendering the app which seems to work because it's CSR so those objects are defined. I tried to copy the same utility file on the NextJS app and initialized sentry.io from the `_app.js` file which I believe is also the entry point. – dokgu Feb 14 '23 at 03:43

0 Answers0