Head hydration matches <meta> by name only: an inserted theme-color meta breaks Next.js viewport.themeColor hydration on every page

Aberta
#85 6 comentários 0 reações 0 responsáveis Ver no GitHub

Mantenedores costumam responder em até 1 dia

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
3/5
Tempo estimado
1-2 dias
Facilidade para iniciantes
57/100
Tipo de issue
Bug
Clareza
Claramente especificada
Status de atividade
Ativa
Stack de tecnologia
javascript, next.js, react, typescript
Domínio
frontend, testing-qa

Direção de pesquisa

Start with dist/dom/features/hydration/full.js, especially HEAD_KEY_ATTRS.meta and HydrationCursor.head(); the report also points to related issue #17. Reproduce with the supplied Next.js app and compare REDACT=1 against REDACT=0 in production, checking recoverable errors and the three theme color tags after hydration. Done means inserted head nodes are skipped, the reported errors disappear, and server rendered attributes remain unchanged.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

Version: @tanstack/redact 0.2.1 through withRedact, Next.js 16.4.3 (latest stable; App Router, Turbopack), react/react-dom 19.3.1, Chromium, production build (next build && next start).

What happens

Next.js renders a viewport.themeColor with light and dark entries as two <meta name="theme-color"> tags that differ only in media. A common no-flash theme pattern adds an inline <head> script that runs before hydration and inserts one more <meta name="theme-color"> (the active colour, no media) in front of them.

HEAD_KEY_ATTRS.meta in dist/dom/features/hydration/full.js is ["name", "property", "charSet", "httpEquiv"]. Because media isn't part of the key, HydrationCursor.head() claims the inserted tag for the first server-rendered meta, and the next theme-color meta is matched one tag too early. This happens on every page load:

  • 6 recoverable errors. In production each one reads Hydration mismatch.. In development they read Hydration mismatch on <meta> for "media". (×4) and Hydration mismatch on <meta> for "content". (×2): the same three mismatches, reported twice. Next.js passes them to reportError, so every page view fires 6 window error events.
  • The tags are rewritten. The inserted meta gets media="(prefers-color-scheme: light)", and the light meta becomes a second dark one.

Native React hydrates the same HTML with no errors and leaves the tags unchanged.

meta[name="theme-color"] after hydration React 19.3.1 Redact 0.2.1
1st (inserted by the script) no media, #ffffff (prefers-color-scheme: light), #ffffff
2nd (prefers-color-scheme: light), #ffffff (prefers-color-scheme: dark), #000000
3rd (prefers-color-scheme: dark), #000000 (prefers-color-scheme: dark), #000000
Errors per page load 0 6

The app stays interactive: a client counter on the page still works.

Reproduction

package.json dependencies: [email protected], [email protected], [email protected], @tanstack/[email protected].

next.config.mjs:

import { withRedact } from '@tanstack/redact/next'

const config = {}

export default process.env.REDACT === '1' ? withRedact(config) : config

app/layout.js:

const themeScript = `(function(){var m=document.createElement('meta');m.setAttribute('name','theme-color');m.setAttribute('data-active','');m.setAttribute('content','#ffffff');var first=document.querySelector('meta[name="theme-color"]');document.head.insertBefore(m,first||document.head.firstChild)})()`

export const viewport = {
  themeColor: [
    { media: '(prefers-color-scheme: light)', color: '#ffffff' },
    { media: '(prefers-color-scheme: dark)', color: '#000000' },
  ],
}

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <head>
        <script dangerouslySetInnerHTML={{ __html: themeScript }} />
      </head>
      <body>{children}</body>
    </html>
  )
}

app/page.js:

import Counter from './counter'

export default function Page() {
  return (
    <main>
      <h1>Redact repro</h1>
      <Counter />
    </main>
  )
}

app/counter.js:

'use client'
import { useState } from 'react'

export default function Counter() {
  const [count, setCount] = useState(0)
  return <button id="counter" onClick={() => setCount(count + 1)}>count {count}</button>
}

Run REDACT=1 next build && next start, open /, and watch the console or Playwright pageerror. Then run the same steps with REDACT=0 to compare. REDACT=1 next dev shows the detailed messages.

Expected

The same result as React: head nodes the server didn't render are skipped, nothing is reported, and no attributes are rewritten.

Suggested fix

Add media to HEAD_KEY_ATTRS.meta. When a head candidate fails attribute validation, keep scanning instead of claiming it, because scripts and browser extensions often insert nodes into <head>. #17 (head claiming, foreign nodes) looks related.

Why it matters for us

We evaluated 0.2.1 on a production Next.js 16.4.3 app. The bundle saving matched your numbers: every page loads 34.6 KB less JS (zstd). 0.2.1 also fixed everything we hit on 0.2.0 (react-modal dialogs, focus after sending a form), so thank you for that! But our e2e suite (87 tests) still fails on every page, and these errors are the only cause, so we can't ship Redact to production yet. Our other blocker is #81: QR codes from qrcode.react and SVG chart labels render wrong after client rendering. I've added the details in a comment there.

Linguagem predominante
TypeScript
Estrelas
640
Forks
32
Merge médio
1h 15min
PRs com merge (30d)
7

Preparar o ambiente

Este projeto não oferece contêiner de desenvolvimento, Dockerfile nem guia de contribuição, então a configuração fica por sua conta: comece pelo README e veja nosso guia da primeira contribuição para os passos gerais.

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de TanStack/redact

Todas as issues de TanStack/redact

Issues semelhantes

Mais issues de TypeScript

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.