Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix React SSR hydration mismatch for objects of other realms #44

Merged
merged 1 commit into from
Jan 12, 2025

Conversation

slorber
Copy link
Contributor

@slorber slorber commented Jan 6, 2025

data instanceof Object is not always reliable, and returns false on edge cases such as objects coming from other realms

On 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 to data.toString() and gets collapsed by default Node.js behavior.

You can see this on initial page load before hydration, or by disabling JS:

CleanShot 2025-01-06 at 15 02 37

After React hydration, it renders fine, but there's an hydration mismatch warning:

CleanShot 2025-01-06 at 15 03 43

Docusaurus React Root onRecoverableError: Error: Minified React error #418; visit https://react.dev/errors/418?args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.


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:

const vm = require('vm');

// Create a new context (another realm)
const context = vm.createContext({}); // Empty sandbox

// Create an object in the new context
const obj = vm.runInContext('({ key: "value" })', context);

console.log(obj); // { key: 'value' }

// Verify it's from another realm
console.log(obj instanceof Object); // false (different realm)

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.

@AnyRoad
Copy link
Owner

AnyRoad commented Jan 12, 2025

Seems like you are right and typeof data === "object" is more reliable. Thank you!

@AnyRoad AnyRoad merged commit ff12199 into AnyRoad:release Jan 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants