You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Bug: Hydration mismatch error due to plugins generating script tag on top #24430
If a script tag is inserted before the head tag due to the user's browser environment such as a plugin, it is judged as a hydration mismatch and the screen is broken.
2022-04-24.11.02.00.mov
The expected behavior
This problem may be a part that each third party needs to solve, but I'm wondering if it's possible to handle an exception in the hydration matching logic of React.
Reacted by Josh Manning, Adrien Antoine, Luke Askew, Benjamin Dobell, huw, Shripad Krishna, James Gentes, Pedro Simon, MrSiby, Bruno Bonamin and 94 more
Is the hydrateRoot function expecting the whole html document to be exactly what gets rendered by renderToPipeableStream? The best would be to just try to hydrate the React root element where the app is rendered?
It does seem that to use renderToPipeableStream I need to render the whole HTML document with a React component, but this is not ideal when e.g. using Vite with SSR in development, since it needs to transform the html to inject custom scripts.
Reacted by ksavblik, Shripad Krishna, René Verheij, Juri Adams, JulianAndresCasasCartagena, Daniel Ferenc Balogh and Maxim Blinenkov
From my understanding, if anything else other than document was passed in into hydrateRoot, it doesn't seem to crash when I have chrome extensions that modify the DOM installed (e.g. Dark Reader / Apollo DevTools).
Something I've noticed is that when React does encounter a hydration mismatch, it attempts to fallback to client side rendering.
Which does show up in the example codesandbox (the one where we are hydrating the document):
Warning: An error occurred during hydration. The server HTML was replaced with client content in <#document>.
Uncaught Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.
However, it results in an application crash because of the next error:
Failed to execute 'appendChild' on 'Node': Only one element on document allowed.
which is from the call stack:
appendChildToContainer <- insertOrAppendPlacementNodeIntoContainer (3) <- commitPlacement <- commitMutationEffectsOnFiber <- commitMutationEffects_complete <- commitMutationEffects_begin <- commitMutationEffects <- commitRootImpl
Then later another error is thrown:
Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
which is from the call stack:
removeChildFromContainer <- unmountHostComponents <- commitDeletion <- commitMutationEffects_begin <- commitMutationEffects <- commitRootImpl <- commitRoot <- performSyncWorkOnRoot <- flushSyncCallbacks <- commitRootImpl
What I am wondering about is: In the case of falling back to client side rendering, why does React do appendChild instead of replaceChild? If it was replaceChild, there wouldn't be an app crash in this case, but at the cost of needing to fall back to client side rendering.
Reacted by ksavblik, Magnus Markling, Nathan Phillip Brink and Ted Marozzi
Yes, that issue is #22833. I believe the fix we wanted to do is changing which top-level element we modify. (Maybe body instead of html?) It would be nice to not have to introduce a separate “host config” method (which we’d have to do if we added a call to “replace”). So ideally the fix should use the methods we already use.
Not an ideal solution but in my use case, I'm only concerned with generating/modifying the head during SSR, and the following hack allows me to work around errors that occur as the result of modifications to the head outside of React by Cypress, various chrome plugins, etc.
constHead: React.FC=()=>{if(globalThis.document?.head){return(<headdangerouslySetInnerHTML={{__html: document.head.innerHTML}}/>);}return(<head>{/* ... Do important things on the server */}</head>);};
This is especially useful for me because even with current fixes added to react-dom@next that allow the client to "recover", doing so wipes out all styles generated by @emotion that have been collected into the head.
Reacted by Tomer Almog, Shripad Krishna, jbrocher and René Verheij
Reacted by Peter Hozák, Tomer Almog, Shripad Krishna, Bora and Philip Waritschlager
I tried React 18.2.0, but it still breaks the page when Apollo Client DevTools extension is used. So my ugly solution for this problem is fix the DOM before hydrateRoot:
@dbashford Which in particular issue are you hitting? We’ve released a short-term fix for the most urgent part of the problem in 18.2 (document fallback didn’t work at all). Now it should work by doing a full client render but this will lose the third party things. There is a possible fix to do something smarter but it’s a bigger project and a bit further on the timeline. So it would help to know what exactly broke for you. Is there a repro? Particular scenario? Thanks.
Mine is the Cypress case. Everything works fine in dev and in prod, but Cypress when it kicks up fails (418), and only after making the hydrateRoot switch. I haven't dug into it too far to really understand the problem, but I've read in this thread and in the Remix discord that the problem may be that Cypress monkey's with the head causing the hydration issue. I admit that SSR/hydration are still voodoo/witchcraft to me, so I'm struggling a bit to work my way through it. Baby steps.
Hey @Mordred thanks a lot for this quick hack, I modified it slightly to also get rid of inputs within html as the Yoroi extensions injects a hidden input directly into the <html/> (not <body/>)
document.querySelectorAll("html > script, html > input").forEach((s)=>{s.parentNode?.removeChild(s);});
@grundmanise I have seen this, yes, and at first it appears to be related.
But as you can see in my post above, it remained a problem in Next.js long after the React 19 release (latest Next.js v15 release still shows an error with the Video Speed Controller browser extension).
So it wasn't fixed in React 19 - it was fixed much later (although I haven't yet found the exact PRs where the changes were made).
Look at this part:
data-new-gr-c-s-check-loaded="14.1275.0"
data-gr-ext-installed=""
These attributes are *NOT from your code*.
They are added by the *Grammarly browser extension*.
So the flow becomes:
1.
Server sends HTML
2.
Grammarly extension *modifies the HTML*
3.
React tries to hydrate
4.
HTML changed → *hydration mismatch error*
Solution 1 (Recommended)
Disable *Grammarly extension* for localhost.
Steps:
1.
Open Chrome Extensions
2.
Find *Grammarly*
3.
Disable it for your dev site
OR open site in *Incognito mode*.
------------------------------
Solution 2
Run your app in *Incognito* where extensions are disabled.
------------------------------
Solution 3 (If issue from code)
Hydration errors also happen if you use things like:
Math.random()
Date.now()
typeof window !== "undefined"
inside server-rendered components.
But *your case is clearly a browser extension*.
Activity
gaearon commentedon Apr 24, 2022
Might be related to (or same as) #22833, but let's keep both open for now
marcusthelin commentedon Apr 24, 2022
Is the
hydrateRootfunction expecting the whole html document to be exactly what gets rendered byrenderToPipeableStream? The best would be to just try to hydrate the React root element where the app is rendered?It does seem that to use
renderToPipeableStreamI need to render the whole HTML document with a React component, but this is not ideal when e.g. using Vite with SSR in development, since it needs to transform the html to inject custom scripts.hrgui commentedon Apr 25, 2022
From my understanding, if anything else other than document was passed in into hydrateRoot, it doesn't seem to crash when I have chrome extensions that modify the DOM installed (e.g. Dark Reader / Apollo DevTools).
Here is the code sandbox: https://codesandbox.io/s/react-18-root-div-hydrateroot-1f5d5q?file=/src/Html.js:193-941
In the above example, I changed the following:
Html.js
export default function Html({ assets, children, title }) { return ( <html lang="en"> <head> <meta charSet="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="shortcut icon" href="favicon.ico" /> <link rel="stylesheet" href={assets["main.css"]} /> <title>{title}</title> </head> <body> <noscript dangerouslySetInnerHTML={{ __html: `<b>Enable JavaScript to run this app.</b>` }} /> + <div id="root">{children}</div> - {children} <script dangerouslySetInnerHTML={{ __html: `assetManifest = ${JSON.stringify(assets)};` }} /> </body> </html> ); }App.js
export default function App({ assets }) { return ( <Html assets={assets} title="Hello"> + <AppContent /> - <Suspense fallback={<Spinner />}> - <ErrorBoundary FallbackComponent={Error}> - <Content /> - </ErrorBoundary> = </Suspense> </Html> ); } + export function AppContent() { + return ( + <Suspense fallback={<Spinner />}> + <ErrorBoundary FallbackComponent={Error}> + <Content /> + </ErrorBoundary> + </Suspense> + ); + }index.js:
I don't know if this crashes with Cypress though.The app doesn't seem to crash under cypress.Cypress was adding
to the document. I'd assume it would crash if I hydrated the document.
gaearon commentedon Apr 25, 2022
I don’t think the “stricter” behavior here is intentional. I’ll be checking with the team but my current understanding is that this is a bug.
hrgui commentedon Apr 30, 2022
Something I've noticed is that when React does encounter a hydration mismatch, it attempts to fallback to client side rendering.
Which does show up in the example codesandbox (the one where we are hydrating the document):
However, it results in an application crash because of the next error:
which is from the call stack:
appendChildToContainer <- insertOrAppendPlacementNodeIntoContainer (3) <- commitPlacement <- commitMutationEffectsOnFiber <- commitMutationEffects_complete <- commitMutationEffects_begin <- commitMutationEffects <- commitRootImpl
Then later another error is thrown:
which is from the call stack:
removeChildFromContainer <- unmountHostComponents <- commitDeletion <- commitMutationEffects_begin <- commitMutationEffects <- commitRootImpl <- commitRoot <- performSyncWorkOnRoot <- flushSyncCallbacks <- commitRootImpl
What I am wondering about is: In the case of falling back to client side rendering, why does React do
appendChildinstead ofreplaceChild? If it wasreplaceChild, there wouldn't be an app crash in this case, but at the cost of needing to fall back to client side rendering.gaearon commentedon Apr 30, 2022
Yes, that issue is #22833. I believe the fix we wanted to do is changing which top-level element we modify. (Maybe body instead of html?) It would be nice to not have to introduce a separate “host config” method (which we’d have to do if we added a call to “replace”). So ideally the fix should use the methods we already use.
rdadoune commentedon May 19, 2022
Not an ideal solution but in my use case, I'm only concerned with generating/modifying the
headduring SSR, and the following hack allows me to work around errors that occur as the result of modifications to theheadoutside of React by Cypress, various chrome plugins, etc.This is especially useful for me because even with current fixes added to
react-dom@nextthat allow the client to "recover", doing so wipes out all styles generated by@emotionthat have been collected into thehead.adbutterfield commentedon Jun 3, 2022
I think I have the same error. But mine is from using styled-components. Initially, they put a style tag in the body, but then the style tag gets moved up to the head. You can check this repo here: https://github.com/adbutterfield/fast-refresh-express/tree/react-18
I tried just now using react@next/react-dom@next, but I still get the error.
Of course, it's always possible that I'm doing something stupid in my code...
Mordred commentedon Jun 15, 2022
I tried React 18.2.0, but it still breaks the page when Apollo Client DevTools extension is used. So my ugly solution for this problem is fix the DOM before
hydrateRoot:Note: You can replace the selector more strict query .. e.g.
'html > script[src^=chrome-extension]'(remix-run/remix#2947)
dbashford commentedon Jun 21, 2022
Getting the issue with Cypress tests, as suggested in Remix Discord, my workaround for those coming here:
🙏 for a fix soon, thx all!
gaearon commentedon Jun 22, 2022
@dbashford Which in particular issue are you hitting? We’ve released a short-term fix for the most urgent part of the problem in 18.2 (document fallback didn’t work at all). Now it should work by doing a full client render but this will lose the third party things. There is a possible fix to do something smarter but it’s a bigger project and a bit further on the timeline. So it would help to know what exactly broke for you. Is there a repro? Particular scenario? Thanks.
dbashford commentedon Jun 22, 2022
Mine is the Cypress case. Everything works fine in dev and in prod, but Cypress when it kicks up fails (418), and only after making the
hydrateRootswitch. I haven't dug into it too far to really understand the problem, but I've read in this thread and in the Remix discord that the problem may be that Cypress monkey's with the head causing the hydration issue. I admit that SSR/hydration are still voodoo/witchcraft to me, so I'm struggling a bit to work my way through it. Baby steps.CanRau commentedon Jun 22, 2022
Hey @Mordred thanks a lot for this quick hack, I modified it slightly to also get rid of
inputs withinhtmlas the Yoroi extensions injects a hidden input directly into the<html/>(not<body/>)72 remaining items
mehedi-codes commentedon Feb 5, 2025
In my case Grammerly was the culprit.
javadazizmohamad commentedon Feb 6, 2025
یادگیری وآموزش
madfcat commentedon Feb 18, 2025
Also, happens to next 14.2.15., next-international 1.3.1, Google Chrome "Always translate" option in dev and prod.
alvyynm commentedon Mar 10, 2025
Happened to me today. Dark Reader was the culprit.
javadazizmohamad commentedon Mar 10, 2025
من،بروزرسانی،مخزنم،به،پایان،رسیده،بود،بخاطر،همین،ازشما،طلب،کمک،کردم
karlhorky commentedon Feb 13, 2026
It looks like Next.js 16.0.0+ no longer reports hydration errors on
htmlelement 😳Next.js 15.5.12 to contrast:
Seems like this was a change in Next.js v16 or React...?
karlhorky commentedon Feb 13, 2026
@eps1lon mentioned offline that this was a change in React:
So maybe this issue should be closed now?
@yongdamsh or anyone else in the thread: are you still experiencing problems with some browser extensions?
grundmanise commentedon Feb 16, 2026
@karlhorky I think that was mentioned here: https://react.dev/blog/2024/12/05/react-19#compatibility-with-third-party-scripts-and-extensions
karlhorky commentedon Feb 16, 2026
@grundmanise I have seen this, yes, and at first it appears to be related.
But as you can see in my post above, it remained a problem in Next.js long after the React 19 release (latest Next.js v15 release still shows an error with the Video Speed Controller browser extension).
So it wasn't fixed in React 19 - it was fixed much later (although I haven't yet found the exact PRs where the changes were made).
fix: resolve React hooks linting violations in gamification components
SukkaW commentedon Mar 8, 2026
Here is the situation of the "Grammarly" browser extension (which I am using), they fxxking added their attributes to
<body>.karlhorky commentedon Mar 8, 2026
@SukkaW Ah, thanks for the note. Too bad!
I guess this issue should still be kept open then, to track the browser extensions which cause React hydration mismatch problems.
BSPREDDY commentedon Mar 8, 2026
fix: resolve React hooks linting violations in gamification components
fix(phase-10): React #418 hydration fix + better invoice error visibi…