react-indexed-db icon indicating copy to clipboard operation
react-indexed-db copied to clipboard

react-Indexed-db not SSR safe (window/document not defined)

Open jcarroll-ceo opened this issue 1 year ago • 0 comments

I use Gatsby to build a lot of my projects which does "server side rendering" (SSR) which does an initial pass at building pages in node.js.

When including react-indexed-db into the project it works fine in development and when loading in a browser, but it fails when actually doing a build with an error that "window is not defined". I am confident the problem is in this package because I've been able to isolate the import statements and the indexedDB hook calls and then the build resumes.

Recommendation would be to make changes to this package/repo by adding additional checks around window/document calls to confirm it's not being called server side/nodejs.

Gatsby docs also have several techniques for dealing with this situation including adjusting webpack, adding a packaged called browser-monads, and wrapping code in checking if window exists -- none of the above solutions work with this package (thus the bug ticket).

(before anyone comments about "why would you need indexedDB in node/server side - it's only client", yes, I know that, and no, there is no need for indexedDB on the serfer. But, that's not what SSR in Gatsby is doing. This is a VERY common framework for React dev teams and its aim in doing SSR is for SPA/PWA, transpiling, and final speed. The bug isn't in Gatsby's framework, the fix is an enhancement to this lib for checking/guarding against window/document not being defined at the time the code is called.)

See https://github.com/search?q=repo%3Aassuncaocharles%2Freact-indexed-db%20window.&type=code for an example of where window is expected but would be undefined in a Gatsby build doing a nodejs SSR server side compile; I didn't check the entire code base for additional examples of window and/or document usages. But a simple check of typeof window === 'undefined' can help, and/or consider using something like browser-monads here for when window/document is undefined.

jcarroll-ceo avatar Nov 04 '23 14:11 jcarroll-ceo