Unverified Commit 0fd2e51e authored by dan's avatar dan Committed by GitHub

Fix race when navigating Back before hydration (#96252)

Relands #95682 (reverted in #95853 due to #95848).

This contains:

- A bunch of tests (some failing and some passing before this PR; all
passing after this PR).
- The fix from #95682.

In short, we use Navigation API to detect during hydration that we're on
a different history entry than we started, and in that case, replay the
missed traversal with similar logic to what we do for `onPopState`.

The issue with the original PR was that under Activity, React would
sometimes hang applying the state update. This was fixed in
https://github.com/react/react/pull/37135 and synced, so we can do this
fix again now.

## Test Plan

Old and new tests.
parent 55d30fb9
......@@ -56,6 +56,59 @@ const globalMutable: {
pendingMpaPath?: string
} = {}
// A Back/Forward press before the router's popstate listener exists moves the
// browser to a different history entry than the one the document was activated
// on, and the resulting popstate fires with nobody listening. The activation
// entry is fixed for the document's lifetime and entry keys are stable across
// replaceState, so until the listener is installed a key mismatch means a
// traversal went unobserved.
function hasMissedTraversal(): boolean {
if (typeof window.navigation === 'undefined') {
return false
}
const activationEntry = window.navigation.activation?.entry
const currentEntry = window.navigation.currentEntry
return (
activationEntry != null &&
currentEntry != null &&
activationEntry.key !== currentEntry.key &&
// Only entries written by the app router can be restored; on any other
// entry the traversal is left unhandled, as before.
window.history.state?.__NA === true
)
}
let checkedMissedTraversalBeforeHistoryWrite = false
let checkedMissedTraversalBeforeReplay = false
/**
* Handles a popstate event (or one that was missed before hydration).
* By default dispatches ACTION_RESTORE, however if the history entry was not
* pushed/replaced by app-router it will reload the page.
* That case can happen when the old router injected the history entry.
*/
function handlePopState(state: PopStateEvent['state']): void {
if (!state) {
// TODO-APP: this case only happens when pushState/replaceState was called outside of Next.js. It should probably reload the page in this case.
return
}
// This case happens when the history entry was pushed by the `pages` router.
if (!state.__NA) {
window.location.reload()
return
}
// TODO-APP: Ideally the back button should not use startTransition as it should apply the updates synchronously
// Without startTransition works if the cache is there for this path
startTransition(() => {
dispatchTraverseAction(
window.location.href,
state.__PRIVATE_NEXTJS_INTERNALS_TREE
)
})
}
function HistoryUpdater({
appRouterState,
}: {
......@@ -70,6 +123,16 @@ function HistoryUpdater({
const { tree, pushRef, canonicalUrl, renderedSearch } = appRouterState
if (!checkedMissedTraversalBeforeHistoryWrite) {
checkedMissedTraversalBeforeHistoryWrite = true
if (hasMissedTraversal()) {
// Skip the write: it would overwrite the traversed-to entry's state.
// The tree was rendered even though the history write is skipped.
setLastCommittedTree(tree)
return
}
}
const appHistoryState: AppHistoryState = {
tree,
renderedSearch,
......@@ -371,35 +434,17 @@ function Router({
return originalReplaceState(data, _unused, url)
}
/**
* Handle popstate event, this is used to handle back/forward in the browser.
* By default dispatches ACTION_RESTORE, however if the history entry was not pushed/replaced by app-router it will reload the page.
* That case can happen when the old router injected the history entry.
*/
const onPopState = (event: PopStateEvent) => {
if (!event.state) {
// TODO-APP: this case only happens when pushState/replaceState was called outside of Next.js. It should probably reload the page in this case.
return
}
const onPopState = (event: PopStateEvent) => handlePopState(event.state)
// This case happens when the history entry was pushed by the `pages` router.
if (!event.state.__NA) {
window.location.reload()
return
}
window.addEventListener('popstate', onPopState)
// TODO-APP: Ideally the back button should not use startTransition as it should apply the updates synchronously
// Without startTransition works if the cache is there for this path
startTransition(() => {
dispatchTraverseAction(
window.location.href,
event.state.__PRIVATE_NEXTJS_INTERNALS_TREE
)
})
if (!checkedMissedTraversalBeforeReplay) {
checkedMissedTraversalBeforeReplay = true
if (hasMissedTraversal()) {
handlePopState(window.history.state)
}
}
// Register popstate event to call onPopstate.
window.addEventListener('popstate', onPopState)
return () => {
window.history.pushState = originalPushState
window.history.replaceState = originalReplaceState
......
import { ThirdPartyPush } from './third-party-push'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>
<ThirdPartyPush />
{children}
</body>
</html>
)
}
import Link from 'next/link'
export default function Home() {
return (
<>
<h1 id="home">Home</h1>
<Link id="to-post" href="/post">
To post
</Link>
</>
)
}
import Link from 'next/link'
export default function Post() {
return (
<>
<h1 id="post">Post</h1>
<Link id="to-home" href="/">
To home
</Link>
<a id="hash-link" href="#section">
Jump to section
</a>
<div id="section">Section</div>
</>
)
}
import Link from 'next/link'
import { Suspense } from 'react'
async function CurrentPage({
searchParams,
}: {
searchParams: Promise<{ page?: string }>
}) {
const { page = '1' } = await searchParams
return <h1 id="search">Page {page}</h1>
}
export default function Search({
searchParams,
}: {
searchParams: Promise<{ page?: string }>
}) {
return (
<>
<Suspense fallback={null}>
<CurrentPage searchParams={searchParams} />
</Suspense>
<Link id="to-page-2" href="/search?page=2">
To page 2
</Link>
</>
)
}
import { Suspense } from 'react'
export default function SuspenseLayout({
children,
}: {
children: React.ReactNode
}) {
return <Suspense>{children}</Suspense>
}
import Link from 'next/link'
export default function Home() {
return (
<>
<h1 id="home">Home</h1>
<Link id="to-post" href="/suspense/post">
To post
</Link>
</>
)
}
import Link from 'next/link'
export default function Post() {
return (
<>
<h1 id="post">Post</h1>
<Link id="to-home" href="/suspense">
To home
</Link>
<a id="hash-link" href="#section">
Jump to section
</a>
<div id="section">Section</div>
</>
)
}
import Link from 'next/link'
import { Suspense } from 'react'
async function CurrentPage({
searchParams,
}: {
searchParams: Promise<{ page?: string }>
}) {
const { page = '1' } = await searchParams
return <h1 id="search">Page {page}</h1>
}
export default function Search({
searchParams,
}: {
searchParams: Promise<{ page?: string }>
}) {
return (
<>
<Suspense fallback={null}>
<CurrentPage searchParams={searchParams} />
</Suspense>
<Link id="to-page-2" href="/suspense/search?page=2">
To page 2
</Link>
</>
)
}
'use client'
import { useEffect } from 'react'
// Simulates a third-party script writing to history between the router's
// traversal detection and its popstate replay: this component's effect runs
// after all insertion effects but before the parent router's effects.
export function ThirdPartyPush() {
useEffect(() => {
if ((window as any).__injectThirdPartyPush) {
window.history.pushState(
{ thirdParty: true },
'',
window.location.pathname + '?tp=1'
)
}
}, [])
return null
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment