window is not defined inside Suspense boundary.

I am loading a component with React.lazy() that uses window.location.origin inside <Suspense> boundary like this. const LinkCreateForm = React.lazy(() => import("../components/LinkCreateForm")); <React.Suspense fallback={<div>loading...</div>}><LinkCreateForm /></React.Suspense> Its showing window is not defined on initial load. What could be the reason? Any help is appreciated.
6 Replies
Leonidas
Leonidas3y ago
Could you verify that the LinkCreationForm is not imported somewhere else (outside of the provided example)? That sounds like the most likely issue nevermind, i found the actual issue you need to manually disable ssr in the lazy import like so: const IconPicker = dynamic(() => import("./components/IconPicker"), { ssr: false }) cause on the server the window wont be defined, but you probably already know that - else you would probably not use the lazy import
~Abhinav
~AbhinavOP3y ago
oh okay, but isn't React.lazy() import component on the client side? I thought that was the case
Leonidas
Leonidas3y ago
It is for lazily loading the js - but server rendering will still pregenerate the html for the client (and afterwards the hydration works lazily). But when dependencies (or your own code) require access to the window object no server rendering is possible - you have to fully lazy load it (without server rendering)
~Abhinav
~AbhinavOP3y ago
Yeah that i understand window object is not available on server. So basically React.lazy() doesn't have explicit option for ssr like dynamic() has. Cool, thank you for your help buddy.
Leonidas
Leonidas3y ago
It [React lazy] atleast does not prevent nextJS from trying to server generate the html markup. For this you need to use next own tool, the dynamic import ☝🏼
~Abhinav
~AbhinavOP3y ago
Yes got it, 👍
Want results from more Discord servers?
Add your server