NextJS ‘window is not defined’
Lets say you are using NextJS and want to check the window location path:
If you are currently in development mode, you will probably run into this error:
The problem is that during getInitialProps
NextJS will render your component once. The node process doesn’t have a window object.
You heard that NextJS 10 populates the process.browser
object that will work easily:
The problem is that according to these sources process.browser
is deprecated. We should use typeof window === 'undefined'
instead.
Here is a simple util function that you can copy:export const isServer = () => typeof window === 'undefined'
If you don’t render your component on the server side, your build works again:
Voila! Component is rendering again.