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

未关闭
#196 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
3/5
预计耗时
1-2 天
新手友好度
68/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
playwright, react, typescript, vite

调研方向

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.

由索引模型根据 Issue 内容生成。

描述

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.
主要语言
TypeScript
星标
640
派生
32
平均合并
1 小时 15 分钟
30 天内合并 PR
7

环境准备

这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

TanStack/redact 的其他 Issue

查看 TanStack/redact 的全部 Issue

相似的 Issue

更多 TypeScript Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。