Fix React SSR hydration mismatch for objects of other realms #44
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
data instanceof Object
is not always reliable, and returns false on edge cases such as objects coming from other realmsOn the Docusaurus site, we have such objects. For example our
docusaurus.config.js
file is rendered by this lib on both the server at build time (SSG in Node.js) and in the client:https://docusaurus.io/__docusaurus/debug
On Node.js it is rendered as
[object Object]
because it is neither an object/array, neither a primitive so it defaults todata.toString()
and gets collapsed by default Node.js behavior.You can see this on initial page load before hydration, or by disabling JS:
After React hydration, it renders fine, but there's an hydration mismatch warning:
In our case, we are using Jiti to load/transpile our config file: https://github.com/unjs/jiti
Here's a simpler repro case to obtain such object in Node.js:
Note there's a ShadowRealm proposal in the process of being standardized for browser usage.
I believe this lib should support this use-case better and not lead to hydration mismatches by default.
typeof data === "object"
is more reliable.However, maybe it introduces other edge cases? I don't really know but in my case, I didn't see any: this change fixes our hydration error and the lib keeps working properly.