Skip to content

Bug: Hydration mismatch error due to plugins generating script tag on top #24430

Open

Description

@yongdamsh

React version: 18.0.0, 18.1.0-next-fc47cb1b6-20220404 (latest version in codesandbox)

Steps To Reproduce

  1. Install a plugin that creates a script tag at the top(ex: Apollo Client Devtools)
  2. Go to the demo in the new SSR suspense guide
  3. Open preview in a new window
  4. UI mismatch error occurs at hydration time

스크린샷 2022-04-24 오전 11 02 34

Link to code example: https://codesandbox.io/s/kind-sammet-j56ro?file=/src/App.js

The current behavior

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.

Activity

  1. added
    Status: Unconfirmed
    on Apr 24, 2022
  2. gaearon commented on Apr 24, 2022

    @gaearon
    Collaborator

    Might be related to (or same as) #22833, but let's keep both open for now

  3. marcusthelin commented on Apr 24, 2022

    @marcusthelin

    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.

  4. hrgui commented on Apr 25, 2022

    @hrgui

    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:

    - hydrateRoot(document <AppContent />);
    + hydrateRoot(document.getElementById("root"), <AppContent />);

    I don't know if this crashes with Cypress though. The app doesn't seem to crash under cypress.

    Cypress was adding

    function $RC(a,b) {...} 

    to the document. I'd assume it would crash if I hydrated the document.

  5. gaearon commented on Apr 25, 2022

    @gaearon
    Collaborator

    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.

  6. hrgui commented on Apr 30, 2022

    @hrgui

    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.

  7. gaearon commented on Apr 30, 2022

    @gaearon
    Collaborator

    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.

  8. rdadoune commented on May 19, 2022

    @rdadoune

    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.

    const Head: React.FC = () => {
    
      if (globalThis.document?.head) {
        return (
          <head dangerouslySetInnerHTML={{ __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.

  9. adbutterfield commented on Jun 3, 2022

    @adbutterfield

    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...

  10. self-assigned this
    on Jun 6, 2022
  11. Mordred commented on Jun 15, 2022

    @Mordred

    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:

    document.querySelectorAll('html > script').forEach((s) => {
      s.parentNode.removeChild(s);
    });
    
    const root = hydrateRoot(
      document,
      <React.StrictMode>
        <AppWithFullDocument />
      </React.StrictMode>,
    );

    Note: You can replace the selector more strict query .. e.g. 'html > script[src^=chrome-extension]'

    (remix-run/remix#2947)

  12. dbashford commented on Jun 21, 2022

    @dbashford

    Getting the issue with Cypress tests, as suggested in Remix Discord, my workaround for those coming here:

    if (process.env.NODE_ENV === 'test') {
      require('react-dom').hydrate(<RemixBrowser />, document);
    } else {
      hydrateRoot(document, <RemixBrowser />);
    }

    🙏 for a fix soon, thx all!

  13. gaearon commented on Jun 22, 2022

    @gaearon
    Collaborator

    @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.

  14. dbashford commented on Jun 22, 2022

    @dbashford

    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.

  15. CanRau commented on Jun 22, 2022

    @CanRau

    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);
    });

    Using this now in my Remix Deno Stack with Streaming 🥳

  16. 72 remaining items

  17. mehedi-codes commented on Feb 5, 2025

    @mehedi-codes

    In my case Grammerly was the culprit.

  18. javadazizmohamad commented on Feb 6, 2025

    @javadazizmohamad

    یادگیری وآموزش

  19. madfcat commented on Feb 18, 2025

    @madfcat

    Also, happens to next 14.2.15., next-international 1.3.1, Google Chrome "Always translate" option in dev and prod.

  20. alvyynm commented on Mar 10, 2025

    @alvyynm

    Happened to me today. Dark Reader was the culprit.

  21. javadazizmohamad commented on Mar 10, 2025

    @javadazizmohamad

    من،بروزرسانی،مخزنم،به،پایان،رسیده،بود،بخاطر،همین،ازشما،طلب،کمک،کردم

  22. karlhorky commented on Feb 13, 2026

    @karlhorky
    Contributor

    It looks like Next.js 16.0.0+ no longer reports hydration errors on html element 😳

    Image

    Next.js 15.5.12 to contrast:

    Image

    Seems like this was a change in Next.js v16 or React...?

  23. karlhorky commented on Feb 13, 2026

    @karlhorky
    Contributor

    @eps1lon mentioned offline that this was a change in React:

    We changed in React 19 how hydration works for html, head and body.

    We made those a lot more resistant to handle 3rd party code

    So maybe this issue should be closed now?

    @yongdamsh or anyone else in the thread: are you still experiencing problems with some browser extensions?

  24. karlhorky commented on Feb 16, 2026

    @karlhorky
    Contributor

    @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).

  25. SukkaW commented on Mar 8, 2026

    @SukkaW
    Image

    Here is the situation of the "Grammarly" browser extension (which I am using), they fxxking added their attributes to <body>.

  26. karlhorky commented on Mar 8, 2026

    @karlhorky
    Contributor

    @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.

  27. BSPREDDY commented on Mar 8, 2026

    @BSPREDDY
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions