Skip to content

Bug: Hydration mismatch on <script defer> rendered inside <head> #36169

Closed as not planned

Description

@cprecioso

React version: 19.2.4

Any app that contains a <script defer>, will cause hydration errors. It is "not recommended" in React, but it either shouldn't cause errors or the docs should explicitly say to not use it.

Possibly related to:

Steps To Reproduce

  1. Create a React app that contains a <script src="foo" defer />
  2. Save it to an HTML with react-dom/static#prerenderToNodeStream
  3. Hydrate the app on the browser with react-dom/client#hydrateRoot

Link to code example:
https://gist.github.com/cprecioso/e639bc150f5c22a7078d3878ddebce22
run node ./test.js

The current behavior

Prints a hydration warning

Error: Hydration failed because the server rendered HTML didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used:

- A server/client branch `if (typeof window !== 'undefined')`.
- Variable input such as `Date.now()` or `Math.random()` which changes each time it's called.
- Date formatting in a user's locale which doesn't match the server.
- External changing data without sending a snapshot of it along with the HTML.
- Invalid HTML tag nesting.

It can also happen if the client has a browser extension installed which messes with the HTML before React loaded.

https://react.dev/link/hydration-mismatch

  <App>
    <html>
      <head>
        <script src="app.js" defer={true}>
-         
      ...

The expected behavior

Hydrates with no warnings

Activity

  1. added
    Status: Unconfirmed
    on Mar 30, 2026
  2. finessor06 commented on Mar 31, 2026

    @finessor06
  3. lotfimaria331-ops commented on Mar 31, 2026

    @lotfimaria331-ops
  4. lotfimaria331-ops commented on Apr 1, 2026

    @lotfimaria331-ops
  5. github-actions commented on Jun 30, 2026

    @github-actions

    This issue has been automatically marked as stale. If this issue is still affecting you, please leave any comment (for example, "bump"), and we'll keep it open. We are sorry that we haven't been able to prioritize it yet. If you have any new additional information, please include it with your comment!

  6. added
    Resolution: Stale
    on Jun 30, 2026
  7. cprecioso commented on Jul 1, 2026

    @cprecioso
    Author

    Still affected

  8. eps1lon commented on Jul 1, 2026

    @eps1lon
    Collaborator

    @cprecioso Could you double check if you can reproduce this in a browser or with jsdom? I wasn't able to reproduce this with jsdom so this might be a happy-dom bug.

  9. removed
    Resolution: Stale
    on Jul 1, 2026
  10. cprecioso commented on Jul 2, 2026

    @cprecioso
    Author
  11. eps1lon commented on Jul 2, 2026

    @eps1lon
    Collaborator

    I'm getting this mismatch even without defer though:

      <App>
        <html lang="en">
          <head>
            <meta>
            <meta>
            <title>
            <script
    +         src="https://example-third-party-analytics.invalid/script.js"
    -         src={null}
    -         type="importmap"
            >
    -         {"{\"imports\":{\"react\":\"https://esm.sh/[email protected]?dev\",\"react-dom/client\":\"https://esm.sh/react-..."}
          ...
    
  12. cprecioso commented on Jul 3, 2026

    @cprecioso
    Author

    Then it seems my reproduction was not minimal enough 😅. I think this is the same issue I'm seeing in my project, but it's only present when I use defer scripts (and not only async) because of an interaction between some tags being reordered by React or Vite and some tags not.

    I would still consider this bug, because with defer or without it, the reproduction is using React facilities to do stuff the blessed way (bootstrapModules) and still getting a hydration mismatch.

  13. Aakriti7-giti commented on Aug 15, 2026

    @Aakriti7-giti

    I would like to work on this issue . I can reproduce it and submit a PR

  14. github-actions commented on Nov 13, 2026

    @github-actions

    This issue has been automatically marked as stale. If this issue is still affecting you, please leave any comment (for example, "bump"), and we'll keep it open. We are sorry that we haven't been able to prioritize it yet. If you have any new additional information, please include it with your comment!

  15. added
    Resolution: Stale
    on Nov 13, 2026
  16. github-actions commented on Nov 20, 2026

    @github-actions

    Closing this issue after a prolonged period of inactivity. If this issue is still present in the latest release, please create a new issue with up-to-date information. Thank you!

  17. mattcosta7 commented on Nov 25, 2026

    @mattcosta7
    Contributor

    This still happens on 19.3.1 and on 19.3.0-canary-6ff25743-20261117. As @eps1lon found, defer isn't needed. The trigger is the importMap server option plus any inline <script> that React renders in <head>.

    Minimal repro with React only:

    // app.jsx
    export function App() {
      return (
        <html lang="en">
          <head>
            <script id="data" type="application/json">{'{"ok":true}'}</script>
          </head>
          <body>
            <p>hello</p>
          </body>
        </html>
      )
    }
    
    // client.jsx, bundled with esbuild
    import {hydrateRoot} from 'react-dom/client'
    import {App} from './app.jsx'
    
    hydrateRoot(document, <App />, {onRecoverableError: error => console.error(error)})
    
    // server
    const stream = await renderToReadableStream(<App />, {
      importMap: {imports: {unused: '/unused.js'}},
      bootstrapModules: ['/client.js'],
    })

    In Chromium, the production build reports minified error #418. React then renders the document on the client, and <head> ends up with two #data scripts. The development build reports "Hydration failed because the server rendered text didn't match the client", and the diff compares the #data script with the type="importmap" node.

    Fizz writes the import map into <head> outside the React tree. During hydration, canHydrateInstance walks the <head> children and returns the first <script> node for a script fiber. It only skips async scripts with a src. So the first inline script React renders in <head> claims the import map node.

    We work around it with a patch-package patch that adds a guard to the script case of canHydrateInstance:

                 case "script":
    +              if (
    +                "importmap" === instance.getAttribute("type") &&
    +                "importmap" !== anyProps.type
    +              )
    +                break;
                   name = instance.getAttribute("src");

    The guard has to go in every build that contains the client hydration code: cjs/react-dom-client.development.js, cjs/react-dom-client.production.js, cjs/react-dom-profiling.development.js and cjs/react-dom-profiling.profiling.js. With it, the repro hydrates without errors in both builds, on 19.3.1 and on the canary above. The "importmap" !== anyProps.type check keeps an import map that the app renders itself hydrating against its own node.

    Before the patch, we avoided the error without changing React. We rendered <script type="importmap" suppressHydrationWarning> as the first element in <head> on the client only, returning null during server rendering, so the server's import map node had a matching fiber. Keeping inline scripts out of <head> also avoids it.

    #37067 proposed the same check and was closed as stale.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Resolution: StaleStatus: Unconfirmed

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions