NextJS: Window is undefined error

2019.06.17 | 325 words |

problem

I’m using NextJS as a framework for my webapp and trying to access a property that an external script has saved to the window. The problem is that my code is throwing a window is undefined error when I try to access that property on render. How do I access my property on the window?

solution

The issue here is likely that you’re hitting this component on first app touch which means that NextJS will, by default, be executing this code server side before the SPA loads into the browser after which subsequent executions happen client side. What this means is that code executed server side will not necessarily (and likely will not in general) have access to the window cause the code isn’t being executed in a traditional browser.

It’s likely that you’re calling the code path that tries to access the window property in a lifecycle method that gets executed on server-side. Thus a solution to this problem is to move the code paths that rely on window out to lifecycle methods that will only be called client side.

An example of just such a lifecycle method is React’s componentDidMount.

So if your current app code looked something like:

class MyComponent extends React.Component {
    accessMyWindowProperty() { ... }

    render() {
        accessMyWindowProperty();
        ...
    }
}

You should be able to fix the window is undefined error by moving that access up to the componentDidMount lifecycle method:

class MyComponent extends React.Component {
    accessMyWindowProperty() { ... }

    componentDidMount() {
        accessMyWindowProperty();
    }

    render() { ... }
}

Another way to do this is to just set ssr: false which will turn server-side rendering off but this seems like a blunt fix of a symptom rather than a solution to the root cause.

sources

did this help?

I regularly post about tech topics I run into. You can get a periodic email containing updates on new posts and things I’ve built by subscribing here .

 

About the Ham

Hi I'm Hamilton - I built this! If you want more content like this subscribe to my email list, connect with me around the web, or take a look at some of my other projects.

More Projects

comments powered by Disqus