Skip to content

Head elements order differs when component is updated #59655

@luixo

Description

@luixo

Link to the code that reproduces this issue

https://codesandbox.io/p/devbox/nextjs-head-order-bug-d6wn3n

To Reproduce

(context: pages dir)

  1. Add a (default) title in _app via next/head component
  2. Add an override title somewhere in your page via next/head component
  3. Make sure the page title doesn't rerender the component (e.g. wrap it in React.memo)
  4. Rerender _app component (say, add a counter with a button to increment)
  5. Witness title being overriden by a page on an initial render - and rerendered to a default one on _app component rerender.

Current vs. Expected behavior

I expect head elements order depend on nesting order, not on rerender order.

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 23.2.0: Wed Nov 15 21:53:18 PST 2023; root:xnu-10002.61.3~2/RELEASE_ARM64_T6000
Binaries:
  Node: 20.10.0
  npm: 10.2.3
  Yarn: 3.6.2
  pnpm: N/A
Relevant Packages:
  next: 14.0.3
  eslint-config-next: 14.0.3
  react: 18.2.0
  react-dom: 18.2.0
  typescript: 5.1.6
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Metadata (metadata, generateMetadata, next/head)

Additional context

My investigation led to side-effect.tsx file lines which add / remove mounted instances of head on their mount / unmount.
Whenever they need to decide what precedence titles do get - their unwrap it in a array (which is not determenistic, I guess) and reduce it to a single (latest) title value.

What happens in my case is that both default head and component head got added - and title is rendered as expected (page one), then useEffect applies after _app rerender, _app mountedInstance is removed and then added again to the set. This makes set extracted in a different order and title being changed.

I'm not sure what the fix should be, but some kind of indexing of those mountedInstances would help.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugIssue was opened via the bug report template.lockedstaleThe issue has not seen recent activity.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions