Getting a document and window is not defined error in NextJS

10 Views Asked by At

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?

0

There are 0 best solutions below