File size: 4,868 Bytes
b2cad4f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | 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
|