diff --git a/packages/next/src/client/components/app-router.tsx b/packages/next/src/client/components/app-router.tsx index d043d825cb..446c8b277b 100644 --- a/packages/next/src/client/components/app-router.tsx +++ b/packages/next/src/client/components/app-router.tsx @@ -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