An attribute-only hydration mismatch discards the server DOM (React 19 keeps it)

Abierto
#196 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
3/5
Tiempo estimado
1-2 días
Aptitud para principiantes
68/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
playwright, react, typescript, vite

Línea de trabajo

Start with packages/redact/src/dom/features/hydration/full.ts, especially hydrateProps, canRecoverHydrationPropMismatch, and failHydration, then check src/dom/react-ids.ts to understand the recovery effect on IDs. Run the issue’s Vite SSR/hydration reproduction with Playwright and compare the Redact and native React controls, including DOM identity and input state. Add a regression test in the existing hydration test suite covering an attribute-only mismatch while preserving the text-content and structural mismatch behavior.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Summary

When a server-rendered element differs from the client render only in an attribute value, React DOM 19 keeps the server DOM, including the server's attribute value. It reports nothing in production; in development it logs "A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up."

Redact 0.3.1 handles the same case as a hydration failure. It:

  • calls onRecoverableError with Hydration mismatch.;
  • discards the server DOM and client-renders the subtree;
  • generates useId values outside hydration, so the ids change (_R_0_ becomes _r_0_ with identifierStrategy: 'react');
  • loses state held in the server DOM, such as text a user typed into an input before hydration.

Real-world trigger. @dnd-kit/core 6.3.1 names aria-describedby="DndDescribedBy-N" on sortable handles from a module-level counter (useUniqueId in @dnd-kit/utilities). A long-running server has usually counted past 0, while a fresh browser starts at 0. In a React Router framework-mode app with native React on the server and Redact in the browser, every page with a sortable table therefore discarded its server DOM after the server's first request. The same page hydrates cleanly with React DOM.

Environment

  • @tanstack/redact 0.3.1 (npm) and main at 61ad375c, built locally
  • react / react-dom 19.3.1, vite 8.4.1, Node 26.13.1
  • Chromium 159.0.8154.6 (Playwright 1.65.2), Windows 11 x64 (10.0.26300)
  • Setup: server rendering with native react-dom/server, hydration with Redact via redact({ environments: ['client'] }) and identifierStrategy: 'react'

Reproduction

This setup has no dnd-kit dependency.

package.json:

{
  "type": "module",
  "dependencies": {
    "@tanstack/redact": "0.3.1",
    "react": "19.3.1",
    "react-dom": "19.3.1",
    "vite": "8.4.1"
  }
}

vite.config.js:

import { redact } from '@tanstack/redact/vite'

// RUNTIME=redact: Redact in the browser. RUNTIME=react: the native React control.
const runtime = process.env.RUNTIME ?? 'redact'

export default ({ isSsrBuild }) => ({
  plugins: !isSsrBuild && runtime === 'redact' ? [redact({ environments: ['client'] })] : [],
  build: isSsrBuild
    ? { outDir: 'dist-ssr' }
    : { outDir: `dist-${runtime}`, rollupOptions: { input: 'client.jsx', output: { entryFileNames: 'client.js' } } },
})

app.jsx:

import { useId, useMemo } from 'react'

// A module-level counter, as some libraries use for generated ids. The server
// process keeps counting across requests; a fresh browser starts at 0.
let next = 0
function useCounterId(prefix) {
  return useMemo(() => `${prefix}-${next++}`, [prefix])
}

export function App() {
  const describedBy = useCounterId('described')
  const id = useId()
  return (
    <main>
      <button type="button" aria-describedby={describedBy}>Sort</button>
      <label htmlFor={id}>Name</label>
      <input id={id} />
    </main>
  )
}

client.jsx:

import { hydrateRoot } from 'react-dom/client'
import { App } from './app.jsx'

hydrateRoot(document.getElementById('root'), <App />, {
  identifierStrategy: 'react',
  onRecoverableError: (error) => console.error('onRecoverableError:', error.message),
})

server.mjs (native react-dom/server; it renders once at startup, as a server that has already handled a request would):

// Usage: node server.mjs <client dir> <port>
import { readFile } from 'node:fs/promises'
import { createServer } from 'node:http'
import { createElement } from 'react'
import { renderToString } from 'react-dom/server'
import { App } from './dist-ssr/app.js'

const [clientDir, port = '4173'] = process.argv.slice(2)
renderToString(createElement(App))
createServer(async (request, response) => {
  if (request.url === '/client.js') {
    response.writeHead(200, { 'content-type': 'text/javascript' })
    return response.end(await readFile(`${clientDir}/client.js`))
  }
  const html = renderToString(createElement(App))
  response.writeHead(200, { 'content-type': 'text/html' })
  response.end(`<!doctype html><html><body><div id="root">${html}</div><script type="module" src="/client.js"></script></body></html>`)
}).listen(Number(port), '127.0.0.1')

probe.mjs (types into the server-rendered input before the client script runs):

import { chromium } from 'playwright'

const browser = await chromium.launch()
const page = await browser.newPage()
const messages = []
page.on('console', (message) => messages.push(`${message.type()}: ${message.text()}`))
let release
const held = new Promise((resolve) => (release = resolve))
await page.route('**/client.js', async (route) => {
  await held
  await route.continue()
})
await page.goto('http://127.0.0.1:4173/', { waitUntil: 'commit' })
await page.waitForSelector('input')
const serverHtml = await page.innerHTML('#root')
await page.evaluate(() => {
  window.serverButton = document.querySelector('button')
  window.serverInput = document.querySelector('input')
})
await page.fill('input', 'typed before hydration')
release()
await page.waitForTimeout(1500)
const after = await page.evaluate(() => ({
  html: document.getElementById('root').innerHTML,
  buttonKept: document.querySelector('button') === window.serverButton,
  inputKept: document.querySelector('input') === window.serverInput,
  inputValue: document.querySelector('input').value,
}))
console.log({ serverHtml, after, console: messages })
await browser.close()

Steps

npm install
RUNTIME=redact npx vite build && RUNTIME=react npx vite build && npx vite build --ssr app.jsx
node server.mjs dist-redact 4173   # then, in another shell: node probe.mjs
node server.mjs dist-react 4173    # control, then: node probe.mjs

Both runs receive the same server HTML:

<main><button type="button" aria-describedby="described-1">Sort</button><label for="_R_0_">Name</label><input id="_R_0_"></main>

Expected (React DOM 19.3.1, production build)

The server DOM, its ids and the typed text are kept. onRecoverableError is not called.

after: {
  html: '<main><button type="button" aria-describedby="described-1">Sort</button><label for="_R_0_">Name</label><input id="_R_0_"></main>',
  buttonKept: true, inputKept: true, inputValue: 'typed before hydration'
},
console: []

A development build (NODE_ENV=development npx vite build --mode development) also keeps everything. It only logs A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up. ....

In React DOM 19.3.1 source:

Actual (Redact 0.3.1, and main at 61ad375c)

after: {
  html: '<main><button type="button" aria-describedby="described-1">Sort</button><label for="_r_0_">Name</label><input id="_r_0_"></main>',
  buttonKept: false, inputKept: false, inputValue: ''
},
console: [ 'error: onRecoverableError: Hydration mismatch.' ]

With a development build the message is onRecoverableError: Hydration mismatch on <button> for "aria-describedby"., and the outcome is the same.

The re-rendered button ends up with described-1 here only because the discarded render had already advanced the counter.

Where (packages/redact/src/dom/features/hydration/full.ts; line numbers match the 0.3.1 tarball's src/ and main at 61ad375c):

  • In hydrateProps, any differing prop calls failHydration (line 242).
  • canRecoverHydrationPropMismatch (line 340) allows in-place recovery only for document-shell tags and nodes inside <head>.
  • For everything else, failHydration (line 145) reports through onRecoverableError and then calls abortHydration, which throws and client-renders the subtree.
  • useId calls during that client render take the clientReactId path (src/dom/react-ids.ts), because the root is no longer hydrating.

Suggested fix

Match React DOM in production: for an attribute-only difference on a matched element, keep the server node and its attribute, and do not call onRecoverableError or abort hydration. Keep the text-content and structural mismatch paths as they are. In development, log a diagnostic like React's instead of failing. The existing recoverInPlace branch already handles the <head> and shell cases; it could cover every element, without the queueProp patch, since React does not patch attributes either.

Related

  • #42 (open): camelCase SVG attributes are lowercased, so a case-sensitive getAttribute misses them and hydration aborts. There the mismatch is a Redact naming bug: server and client values are actually equal. Here the values genuinely differ, and the question is what hydration should do with a real attribute-only difference.
  • #17 (closed, fixed by 0.2.3): four hydration strictness bugs, including uncaught mismatches during suspended hydration and rejecting edge-injected leftover nodes. None covers a differing attribute value on an element that both sides render.
  • #190 (open): a missing development warning for an extra attribute on <html>. A shell element recovers in place, so there is no failure there.
  • #183 (open): useId mismatches when identifierStrategy: 'react' cannot be passed. Here it is passed, and the ids match until hydration is abandoned.
  • Searched open and closed issues and PRs on 5/12/2026 for attribute mismatch, hydration attribute, aria-describedby, patched up, attributes match, discard server, dnd-kit, module counter, prop mismatch and attribute recover. Nothing covers attribute-only differences outside <head> and the document shell.
Lenguaje dominante
TypeScript
Estrellas
640
Forks
32
Merge medio
1 h 15 min
PR fusionados (30 d)
7

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de TanStack/redact

Todos los issues de TanStack/redact

Issues similares

Más issues de TypeScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.