Window is undefined during SSR

If when server side rendering a React application (other JS frameworks are available) that makes use of the global window object during the initial render, or perhaps the global document object, then you may get an error stating “window is undefined”. This is because when the app is being rendered on the server side on the web server it is not within the browser environment and therefore it cannot access the global objects that the browser provides.

To resolve this issue you will need to check for the presence and validity of the window object before calling it. This could be done manually in your code but a simple widely used npm package can do the job for you – ‘global‘. A very small lightweight library tor require global variables. It is a common dependency on popular npm packages and so it may already be indirectly referenced in your app anyway, but install via ..

npm i global

Then in your code just add an import for window before using it like below. Now the lack of window object will be handled.

// import the global window variable
import window from 'global';

// you can now use window global object
const url = window && window.location.href ? window.location.href : ''

For more info checkout the npm page for global or the github repo LINK

Links:

https://npmjs.com/package/global
https://github.com/Raynos/global

Advertisement

Useful React.JS Learning Resources

Below are some links that you might find useful for learning React.js and Flux, Facebook’s successful JavaScript UI framework.  There are a lot of resources out there but here are some of the best that I have collected for members of my team.

Introductions and overviews of React.js:

Flux:

Tutorials for Flux & React:

Books: 

Prefer the old school approach of reading a book then instead check out this: React.js Essentials by Artemij Fedosejev