From c27052071a1ff92e4c4e82978a927960151111fd Mon Sep 17 00:00:00 2001 From: "alcora-dev[bot]" <346617100+alcora-dev[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:26:40 +0000 Subject: [PATCH 1/4] fix(pages-router): give useRouter() the new route on the first render after a client navigation --- packages/vinext/src/shims/router.ts | 68 ++++++++++++++++++- .../pages-router/first-render-router.spec.ts | 56 +++++++++++++++ .../pages/first-render-router/[id].tsx | 34 ++++++++++ .../pages/first-render-router/index.tsx | 9 +++ 4 files changed, 164 insertions(+), 3 deletions(-) create mode 100644 tests/e2e/pages-router/first-render-router.spec.ts create mode 100644 tests/fixtures/pages-basic/pages/first-render-router/[id].tsx create mode 100644 tests/fixtures/pages-basic/pages/first-render-router/index.tsx diff --git a/packages/vinext/src/shims/router.ts b/packages/vinext/src/shims/router.ts index 0e4527b4be..1eb6e8a481 100644 --- a/packages/vinext/src/shims/router.ts +++ b/packages/vinext/src/shims/router.ts @@ -3935,8 +3935,70 @@ export function useRouter(): NextRouter { ); } +type RouterSnapshot = ReturnType; + +/** + * The live values a client router snapshot is derived from. A navigation + * commits history and `window.__NEXT_DATA__` (always a new object, never + * mutated in place) before `root.render()`, so comparing these by identity + * tells whether the provider's stored snapshot still describes the live route. + */ +type RouterSnapshotSource = { + href: string; + historyState: unknown; + nextData: unknown; + isReady: boolean; + routerDidNavigate: boolean; +}; + +type RouterSnapshotState = { + snapshot: RouterSnapshot; + // `null` on the server, where the snapshot comes from the request context. + source: RouterSnapshotSource | null; +}; + +function getRouterSnapshotSource(): RouterSnapshotSource | null { + if (typeof window === "undefined") return null; + return { + href: window.location.href, + historyState: window.history?.state, + nextData: window.__NEXT_DATA__, + isReady: isPagesRouterReady(), + routerDidNavigate: routerRuntimeState.routerDidNavigate, + }; +} + +function takeRouterSnapshot(): RouterSnapshotState { + return { snapshot: getRouterSnapshot(), source: getRouterSnapshotSource() }; +} + +function refreshRouterSnapshot(prev: RouterSnapshotState): RouterSnapshotState { + if (prev.source === null) return prev; + const next = getRouterSnapshotSource(); + if ( + next !== null && + prev.source.href === next.href && + prev.source.historyState === next.historyState && + prev.source.nextData === next.nextData && + prev.source.isReady === next.isReady && + prev.source.routerDidNavigate === next.routerDidNavigate + ) { + return prev; + } + return { snapshot: getRouterSnapshot(), source: next }; +} + function PagesRouterProvider({ children }: { children: ReactNode }): ReactElement { - const [{ pathname, query, asPath, isReady }, setState] = useState(getRouterSnapshot); + const [routerState, setState] = useState(takeRouterSnapshot); + // A client navigation commits the new URL and __NEXT_DATA__ and then calls + // root.render(), which re-renders this provider with its old state. Next.js + // assigns router state before rendering the new page (Router#set() in + // packages/next/src/shared/lib/router/router.ts), so the page's first render + // already sees the destination route. Re-take the snapshot during render + // when its source changed, before any child reads the context. + const currentRouterState = refreshRouterSnapshot(routerState); + if (currentRouterState !== routerState) setState(currentRouterState); + const { pathname, query, asPath, isReady } = currentRouterState.snapshot; // Popstate is handled by the Pages Router client entry via // installPagesRouterRuntime() so beforePopState() is consistently enforced @@ -3945,7 +4007,7 @@ function PagesRouterProvider({ children }: { children: ReactNode }): ReactElemen // vinext:navigate listener. useEffect(() => { const onNavigate = ((_e: CustomEvent) => { - setState(getRouterSnapshot()); + setState(refreshRouterSnapshot); }) as EventListener; window.addEventListener("vinext:navigate", onNavigate); let cancelled = false; @@ -3954,7 +4016,7 @@ function PagesRouterProvider({ children }: { children: ReactNode }): ReactElemen const becameReady = markPagesRouterReady(); if (becameReady) { - setState(getRouterSnapshot()); + setState(refreshRouterSnapshot); notifyNextNavigationPagesContext(); } }, 0); diff --git a/tests/e2e/pages-router/first-render-router.spec.ts b/tests/e2e/pages-router/first-render-router.spec.ts new file mode 100644 index 0000000000..0c2f3c5925 --- /dev/null +++ b/tests/e2e/pages-router/first-render-router.spec.ts @@ -0,0 +1,56 @@ +import { test, expect, type Page } from "@playwright/test"; + +const BASE = "http://localhost:4173"; + +type RenderRecord = { + query: Record; + pathname: string; + asPath: string; + location: string; +}; + +async function takeRenders(page: Page): Promise { + return page.evaluate(() => { + const w = window as unknown as { __FIRST_RENDER_ROUTER__?: RenderRecord[] }; + const renders = w.__FIRST_RENDER_ROUTER__ ?? []; + w.__FIRST_RENDER_ROUTER__ = []; + return renders; + }); +} + +function expectEveryRenderToSee(renders: RenderRecord[], id: string): void { + expect(renders.length).toBeGreaterThan(0); + for (const render of renders) { + expect(render).toEqual({ + query: { id }, + pathname: "/first-render-router/[id]", + asPath: `/first-render-router/${id}`, + location: `/first-render-router/${id}`, + }); + } +} + +// Next.js assigns router state before rendering the new page (Router#set() +// in packages/next/src/shared/lib/router/router.ts), so the first render after +// a client navigation already sees the destination route. +test("useRouter() returns the new route on the first render after client navigation", async ({ + page, +}) => { + await page.goto(`${BASE}/first-render-router`); + await page.waitForFunction(() => (window as any).next?.router?.isReady === true); + + // from a static page to a dynamic one. + await page.click('[data-testid="first-render-link"]'); + await expect(page.locator('[data-testid="first-render-id"]')).toHaveText("1"); + expectEveryRenderToSee(await takeRenders(page), "1"); + + // router.push between two params of the same dynamic page, which stays mounted. + await page.click('[data-testid="first-render-push"]'); + await expect(page.locator('[data-testid="first-render-id"]')).toHaveText("2"); + expectEveryRenderToSee(await takeRenders(page), "2"); + + // Back (popstate) to the previous param. + await page.goBack(); + await expect(page.locator('[data-testid="first-render-id"]')).toHaveText("1"); + expectEveryRenderToSee(await takeRenders(page), "1"); +}); diff --git a/tests/fixtures/pages-basic/pages/first-render-router/[id].tsx b/tests/fixtures/pages-basic/pages/first-render-router/[id].tsx new file mode 100644 index 0000000000..ca56312b70 --- /dev/null +++ b/tests/fixtures/pages-basic/pages/first-render-router/[id].tsx @@ -0,0 +1,34 @@ +import { useRouter } from "next/router"; + +type RenderRecord = { + query: Record; + pathname: string; + asPath: string; + location: string; +}; + +export const getServerSideProps = async () => ({ props: {} }); + +export default function FirstRenderRouterItem() { + const router = useRouter(); + if (typeof window !== "undefined") { + const w = window as unknown as { __FIRST_RENDER_ROUTER__?: RenderRecord[] }; + (w.__FIRST_RENDER_ROUTER__ ??= []).push({ + query: { ...router.query }, + pathname: router.pathname, + asPath: router.asPath, + location: window.location.pathname, + }); + } + return ( +
+

{String(router.query.id)}

+ +
+ ); +} diff --git a/tests/fixtures/pages-basic/pages/first-render-router/index.tsx b/tests/fixtures/pages-basic/pages/first-render-router/index.tsx new file mode 100644 index 0000000000..283da82473 --- /dev/null +++ b/tests/fixtures/pages-basic/pages/first-render-router/index.tsx @@ -0,0 +1,9 @@ +import Link from "next/link"; + +export default function FirstRenderRouterHome() { + return ( + + go to /first-render-router/1 + + ); +} From a0d55e326e6ea05d4b925b0f0526728fa3af85c8 Mon Sep 17 00:00:00 2001 From: "alcora-dev[bot]" <346617100+alcora-dev[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:41:44 +0000 Subject: [PATCH 2/4] fix(pages-router): render the committed navigation route, not the live location --- packages/vinext/src/shims/router.ts | 95 +++++++++++++++---- .../pages-router/first-render-router.spec.ts | 32 +++++++ 2 files changed, 106 insertions(+), 21 deletions(-) diff --git a/packages/vinext/src/shims/router.ts b/packages/vinext/src/shims/router.ts index 1eb6e8a481..ffa431de95 100644 --- a/packages/vinext/src/shims/router.ts +++ b/packages/vinext/src/shims/router.ts @@ -169,6 +169,7 @@ function renderPagesRouterElement( } cancelPreviousRenderCommit(); + commitRouterSnapshot(); return new Promise((resolve, reject) => { const cancel = () => { @@ -443,6 +444,13 @@ type PagesRouterRuntimeState = { routerDidNavigate: boolean; deprecatedEventBridgeInstalled: boolean; pagesRouterReady: boolean; + /** + * The route snapshot of the last navigation render, taken when it committed + * history and `__NEXT_DATA__`, just before `root.render()`. `token` grows by + * one per commit, so the provider can tell a newer commit from the state it + * already holds. + */ + committedRouterSnapshot: CommittedRouterSnapshot | null; publicRouter?: Record; }; @@ -473,6 +481,7 @@ function createPagesRouterRuntimeState(): PagesRouterRuntimeState { routerDidNavigate: false, deprecatedEventBridgeInstalled: false, pagesRouterReady: typeof window === "undefined" || !shouldDeferInitialPagesRouterReady(), + committedRouterSnapshot: null, }; } @@ -3938,10 +3947,9 @@ export function useRouter(): NextRouter { type RouterSnapshot = ReturnType; /** - * The live values a client router snapshot is derived from. A navigation - * commits history and `window.__NEXT_DATA__` (always a new object, never - * mutated in place) before `root.render()`, so comparing these by identity - * tells whether the provider's stored snapshot still describes the live route. + * The live values a client router snapshot is derived from, compared by + * identity. `__NEXT_DATA__` is always assigned a new object, never mutated in + * place, so a same-URL navigation that refetches props still counts as a change. */ type RouterSnapshotSource = { href: string; @@ -3951,10 +3959,18 @@ type RouterSnapshotSource = { routerDidNavigate: boolean; }; +type CommittedRouterSnapshot = { + token: number; + snapshot: RouterSnapshot; + source: RouterSnapshotSource | null; +}; + type RouterSnapshotState = { snapshot: RouterSnapshot; // `null` on the server, where the snapshot comes from the request context. source: RouterSnapshotSource | null; + // The `committedRouterSnapshot` token this state already accounts for. + commitToken: number; }; function getRouterSnapshotSource(): RouterSnapshotSource | null { @@ -3968,35 +3984,72 @@ function getRouterSnapshotSource(): RouterSnapshotSource | null { }; } +function getCommittedRouterSnapshotToken(): number { + return routerRuntimeState.committedRouterSnapshot?.token ?? 0; +} + +/** + * Record the route a navigation render is about to show. Called once its + * history entry and `__NEXT_DATA__` are committed, right before + * `root.render()`, like Next.js's `Router#set()` assigning `this.state` before + * `this.sub()` renders (packages/next/src/shared/lib/router/router.ts). The + * provider reads this snapshot while rendering, never the live location: on + * popstate the browser moves `location` before the route is resolved, and a + * rejected `beforePopState` never commits at all. + */ +function commitRouterSnapshot(): void { + routerRuntimeState.committedRouterSnapshot = { + token: getCommittedRouterSnapshotToken() + 1, + snapshot: getRouterSnapshot(), + source: getRouterSnapshotSource(), + }; +} + function takeRouterSnapshot(): RouterSnapshotState { - return { snapshot: getRouterSnapshot(), source: getRouterSnapshotSource() }; + return { + snapshot: getRouterSnapshot(), + source: getRouterSnapshotSource(), + commitToken: getCommittedRouterSnapshotToken(), + }; } +/** During render: adopt a navigation commit newer than the provider's state. */ +function adoptCommittedRouterSnapshot(prev: RouterSnapshotState): RouterSnapshotState { + const committed = routerRuntimeState.committedRouterSnapshot; + if (committed === null || committed.token === prev.commitToken) return prev; + return { snapshot: committed.snapshot, source: committed.source, commitToken: committed.token }; +} + +/** + * After `vinext:navigate` or the ready transition: the navigation has finished, + * so the live values are the router state. Keep the previous state when nothing + * it was built from changed, so `router` changes identity once per navigation. + */ function refreshRouterSnapshot(prev: RouterSnapshotState): RouterSnapshotState { - if (prev.source === null) return prev; - const next = getRouterSnapshotSource(); + const source = getRouterSnapshotSource(); + const commitToken = getCommittedRouterSnapshotToken(); if ( - next !== null && - prev.source.href === next.href && - prev.source.historyState === next.historyState && - prev.source.nextData === next.nextData && - prev.source.isReady === next.isReady && - prev.source.routerDidNavigate === next.routerDidNavigate + source !== null && + prev.source !== null && + prev.commitToken === commitToken && + prev.source.href === source.href && + prev.source.historyState === source.historyState && + prev.source.nextData === source.nextData && + prev.source.isReady === source.isReady && + prev.source.routerDidNavigate === source.routerDidNavigate ) { return prev; } - return { snapshot: getRouterSnapshot(), source: next }; + return { snapshot: getRouterSnapshot(), source, commitToken }; } function PagesRouterProvider({ children }: { children: ReactNode }): ReactElement { const [routerState, setState] = useState(takeRouterSnapshot); - // A client navigation commits the new URL and __NEXT_DATA__ and then calls - // root.render(), which re-renders this provider with its old state. Next.js - // assigns router state before rendering the new page (Router#set() in - // packages/next/src/shared/lib/router/router.ts), so the page's first render - // already sees the destination route. Re-take the snapshot during render - // when its source changed, before any child reads the context. - const currentRouterState = refreshRouterSnapshot(routerState); + // A client navigation records its route snapshot and then calls + // root.render(), which re-renders this provider with its old state. Adopt the + // committed snapshot during render, before any child reads the context, so + // the new page's first render already sees its route, as in Next.js. + const currentRouterState = adoptCommittedRouterSnapshot(routerState); if (currentRouterState !== routerState) setState(currentRouterState); const { pathname, query, asPath, isReady } = currentRouterState.snapshot; diff --git a/tests/e2e/pages-router/first-render-router.spec.ts b/tests/e2e/pages-router/first-render-router.spec.ts index 0c2f3c5925..81f176ed1d 100644 --- a/tests/e2e/pages-router/first-render-router.spec.ts +++ b/tests/e2e/pages-router/first-render-router.spec.ts @@ -54,3 +54,35 @@ test("useRouter() returns the new route on the first render after client navigat await expect(page.locator('[data-testid="first-render-id"]')).toHaveText("1"); expectEveryRenderToSee(await takeRenders(page), "1"); }); + +// The provider renders the route the navigation committed, not whatever the +// browser location is when React gets to the render. On popstate the browser +// moves `location` before the route is resolved, so a render that runs in that +// interval must not mix the live URL with the committed page. +test("useRouter() renders the committed route even if location moves before the render runs", async ({ + page, +}) => { + await page.goto(`${BASE}/first-render-router/1`); + await page.waitForFunction(() => (window as any).next?.router?.isReady === true); + await takeRenders(page); + + await page.evaluate(() => { + const root = (window as any).__VINEXT_ROOT__; + const render = root.render.bind(root); + root.render = (element: unknown) => { + root.render = render; + render(element); + // React renders later, in its own task. Move the URL before it does. + window.history.replaceState(window.history.state, "", "/first-render-router/1?moved=1"); + }; + }); + await page.click('[data-testid="first-render-push"]'); + await page.waitForFunction(() => ((window as any).__FIRST_RENDER_ROUTER__ ?? []).length > 0); + + const [first] = await takeRenders(page); + expect({ query: first.query, pathname: first.pathname, asPath: first.asPath }).toEqual({ + query: { id: "2" }, + pathname: "/first-render-router/[id]", + asPath: "/first-render-router/2", + }); +}); From f00fd0374eab33cdd11061359835bb82dbfccc12 Mon Sep 17 00:00:00 2001 From: "alcora-dev[bot]" Date: Tue, 17 Nov 2026 10:58:04 +0000 Subject: [PATCH 3/4] fix(pages-router): keep the committed router snapshot when a navigation completes --- packages/vinext/src/shims/router.ts | 111 ++++++------------ .../pages-router/first-render-router.spec.ts | 40 +++++-- 2 files changed, 65 insertions(+), 86 deletions(-) diff --git a/packages/vinext/src/shims/router.ts b/packages/vinext/src/shims/router.ts index ffa431de95..8b4fc92829 100644 --- a/packages/vinext/src/shims/router.ts +++ b/packages/vinext/src/shims/router.ts @@ -445,10 +445,9 @@ type PagesRouterRuntimeState = { deprecatedEventBridgeInstalled: boolean; pagesRouterReady: boolean; /** - * The route snapshot of the last navigation render, taken when it committed - * history and `__NEXT_DATA__`, just before `root.render()`. `token` grows by - * one per commit, so the provider can tell a newer commit from the state it - * already holds. + * The router snapshot of the last committed router state change (see + * `commitRouterSnapshot`). `token` grows by one per commit, so the provider + * can tell a newer commit from the state it already holds. */ committedRouterSnapshot: CommittedRouterSnapshot | null; publicRouter?: Record; @@ -3227,10 +3226,18 @@ function stripHash(url: string): string { return i === -1 ? url : url.slice(0, i); } +/** + * `detail` of the `vinext:navigate` events the router dispatches. Every such + * navigation has already committed its router snapshot (`commitRouterSnapshot`). + */ +const ROUTER_NAVIGATE_EVENT_DETAIL = { routerStateCommitted: true } as const; + /** Notify in-page listeners (e.g. useRouter hooks) that navigation occurred. */ function dispatchNavigateEvent(): void { notifyNextNavigationPagesContext(); - window.dispatchEvent(new CustomEvent("vinext:navigate")); + window.dispatchEvent( + new CustomEvent("vinext:navigate", { detail: ROUTER_NAVIGATE_EVENT_DETAIL }), + ); } /** @@ -3710,6 +3717,7 @@ async function performNavigation( : (redirectBrowserHref ?? credentialedDisplayHref ?? full), navState, ); + commitRouterSnapshot(); if (doScroll) scrollToHashTarget(extractHash(resolved)); onStateUpdate?.(); routerEvents.emit("hashChangeComplete", eventUrl, { shallow }); @@ -3840,6 +3848,7 @@ async function performNavigation( if (result === "failed") return false; } else { emitBeforeHistoryChange(); + commitRouterSnapshot(); // Shallow navigations skip the render-commit path, so apply the scroll // reset synchronously here — before routeChangeComplete. This matches the // non-shallow path, where the x/y reset runs inside the render-commit @@ -3946,101 +3955,49 @@ export function useRouter(): NextRouter { type RouterSnapshot = ReturnType; -/** - * The live values a client router snapshot is derived from, compared by - * identity. `__NEXT_DATA__` is always assigned a new object, never mutated in - * place, so a same-URL navigation that refetches props still counts as a change. - */ -type RouterSnapshotSource = { - href: string; - historyState: unknown; - nextData: unknown; - isReady: boolean; - routerDidNavigate: boolean; -}; - type CommittedRouterSnapshot = { token: number; snapshot: RouterSnapshot; - source: RouterSnapshotSource | null; }; type RouterSnapshotState = { snapshot: RouterSnapshot; - // `null` on the server, where the snapshot comes from the request context. - source: RouterSnapshotSource | null; // The `committedRouterSnapshot` token this state already accounts for. commitToken: number; }; -function getRouterSnapshotSource(): RouterSnapshotSource | null { - if (typeof window === "undefined") return null; - return { - href: window.location.href, - historyState: window.history?.state, - nextData: window.__NEXT_DATA__, - isReady: isPagesRouterReady(), - routerDidNavigate: routerRuntimeState.routerDidNavigate, - }; -} - function getCommittedRouterSnapshotToken(): number { return routerRuntimeState.committedRouterSnapshot?.token ?? 0; } /** - * Record the route a navigation render is about to show. Called once its - * history entry and `__NEXT_DATA__` are committed, right before - * `root.render()`, like Next.js's `Router#set()` assigning `this.state` before - * `this.sub()` renders (packages/next/src/shared/lib/router/router.ts). The - * provider reads this snapshot while rendering, never the live location: on - * popstate the browser moves `location` before the route is resolved, and a - * rejected `beforePopState` never commits at all. + * Record the router state at the moment a change commits, like Next.js's + * `Router#set()` assigning `this.state` (packages/next/src/shared/lib/router/router.ts). + * A render-backed navigation calls this once its history entry and + * `__NEXT_DATA__` are committed, right before `root.render()`; shallow and + * hash-only changes call it after their history update, and the ready + * transition when it flips the ready bit. The provider only ever shows a + * committed snapshot, never the live location: on popstate the browser moves + * `location` before the route is resolved, a traversal rejected by + * `beforePopState` never commits, and the location may move again before a + * completed navigation dispatches `vinext:navigate`. */ function commitRouterSnapshot(): void { routerRuntimeState.committedRouterSnapshot = { token: getCommittedRouterSnapshotToken() + 1, snapshot: getRouterSnapshot(), - source: getRouterSnapshotSource(), }; } function takeRouterSnapshot(): RouterSnapshotState { - return { - snapshot: getRouterSnapshot(), - source: getRouterSnapshotSource(), - commitToken: getCommittedRouterSnapshotToken(), - }; + return { snapshot: getRouterSnapshot(), commitToken: getCommittedRouterSnapshotToken() }; } -/** During render: adopt a navigation commit newer than the provider's state. */ +/** Adopt a router state commit newer than the provider's state, if there is one. */ function adoptCommittedRouterSnapshot(prev: RouterSnapshotState): RouterSnapshotState { const committed = routerRuntimeState.committedRouterSnapshot; if (committed === null || committed.token === prev.commitToken) return prev; - return { snapshot: committed.snapshot, source: committed.source, commitToken: committed.token }; -} - -/** - * After `vinext:navigate` or the ready transition: the navigation has finished, - * so the live values are the router state. Keep the previous state when nothing - * it was built from changed, so `router` changes identity once per navigation. - */ -function refreshRouterSnapshot(prev: RouterSnapshotState): RouterSnapshotState { - const source = getRouterSnapshotSource(); - const commitToken = getCommittedRouterSnapshotToken(); - if ( - source !== null && - prev.source !== null && - prev.commitToken === commitToken && - prev.source.href === source.href && - prev.source.historyState === source.historyState && - prev.source.nextData === source.nextData && - prev.source.isReady === source.isReady && - prev.source.routerDidNavigate === source.routerDidNavigate - ) { - return prev; - } - return { snapshot: getRouterSnapshot(), source, commitToken }; + return { snapshot: committed.snapshot, commitToken: committed.token }; } function PagesRouterProvider({ children }: { children: ReactNode }): ReactElement { @@ -4059,8 +4016,14 @@ function PagesRouterProvider({ children }: { children: ReactNode }): ReactElemen // provider boundary so many useRouter() calls share one router state and one // vinext:navigate listener. useEffect(() => { - const onNavigate = ((_e: CustomEvent) => { - setState(refreshRouterSnapshot); + // The router's own navigations committed their snapshot already (a + // render-backed one was adopted during render, so this only picks up + // shallow and hash-only changes). Never re-read the live location for + // them: it may have moved since. An event dispatched outside the router + // has no commit, so it records the live state, as before. + const onNavigate = ((e: CustomEvent) => { + if (e.detail !== ROUTER_NAVIGATE_EVENT_DETAIL) commitRouterSnapshot(); + setState(adoptCommittedRouterSnapshot); }) as EventListener; window.addEventListener("vinext:navigate", onNavigate); let cancelled = false; @@ -4069,7 +4032,8 @@ function PagesRouterProvider({ children }: { children: ReactNode }): ReactElemen const becameReady = markPagesRouterReady(); if (becameReady) { - setState(refreshRouterSnapshot); + commitRouterSnapshot(); + setState(adoptCommittedRouterSnapshot); notifyNextNavigationPagesContext(); } }, 0); @@ -4307,6 +4271,7 @@ function handlePagesRouterPopState(e: PopStateEvent): void { // L1381-1403 and L1780). The snapshot stays in sessionStorage, so a later // non-hash popstate to this entry still restores the saved position. const hashUrl = browserUrl + window.location.hash; + commitRouterSnapshot(); routerEvents.emit("hashChangeStart", hashUrl, { shallow: false }); scrollToHashTarget(window.location.hash); routerEvents.emit("hashChangeComplete", hashUrl, { shallow: false }); diff --git a/tests/e2e/pages-router/first-render-router.spec.ts b/tests/e2e/pages-router/first-render-router.spec.ts index 81f176ed1d..5bf587f5fa 100644 --- a/tests/e2e/pages-router/first-render-router.spec.ts +++ b/tests/e2e/pages-router/first-render-router.spec.ts @@ -56,10 +56,10 @@ test("useRouter() returns the new route on the first render after client navigat }); // The provider renders the route the navigation committed, not whatever the -// browser location is when React gets to the render. On popstate the browser -// moves `location` before the route is resolved, so a render that runs in that -// interval must not mix the live URL with the committed page. -test("useRouter() renders the committed route even if location moves before the render runs", async ({ +// browser location is when React renders or when the navigation completes. On +// popstate the browser moves `location` before the route is resolved, so the +// live URL must never be mixed with the committed page. +test("useRouter() keeps the committed route if location moves after the commit", async ({ page, }) => { await page.goto(`${BASE}/first-render-router/1`); @@ -67,22 +67,36 @@ test("useRouter() renders the committed route even if location moves before the await takeRenders(page); await page.evaluate(() => { - const root = (window as any).__VINEXT_ROOT__; + const w = window as any; + w.__FIRST_RENDER_NAVIGATED__ = false; + w.next.router.events.on("routeChangeComplete", () => { + // vinext:navigate is dispatched right after routeChangeComplete; let the + // provider's listener run and React commit before declaring it done. + setTimeout(() => { + w.__FIRST_RENDER_NAVIGATED__ = true; + }, 50); + }); + const root = w.__VINEXT_ROOT__; const render = root.render.bind(root); root.render = (element: unknown) => { root.render = render; render(element); - // React renders later, in its own task. Move the URL before it does. + // React renders later, in its own task. Move the URL before it does and + // keep it moved through the navigation's completion. window.history.replaceState(window.history.state, "", "/first-render-router/1?moved=1"); }; }); await page.click('[data-testid="first-render-push"]'); - await page.waitForFunction(() => ((window as any).__FIRST_RENDER_ROUTER__ ?? []).length > 0); + await page.waitForFunction(() => (window as any).__FIRST_RENDER_NAVIGATED__ === true); - const [first] = await takeRenders(page); - expect({ query: first.query, pathname: first.pathname, asPath: first.asPath }).toEqual({ - query: { id: "2" }, - pathname: "/first-render-router/[id]", - asPath: "/first-render-router/2", - }); + const renders = await takeRenders(page); + expect(renders.length).toBeGreaterThan(0); + for (const render of renders) { + expect({ query: render.query, pathname: render.pathname, asPath: render.asPath }).toEqual({ + query: { id: "2" }, + pathname: "/first-render-router/[id]", + asPath: "/first-render-router/2", + }); + } + await expect(page.locator('[data-testid="first-render-id"]')).toHaveText("2"); }); From 027f2fb5be9a2242e9fe321e7c898467ce43c606 Mon Sep 17 00:00:00 2001 From: "alcora-dev[bot]" <346617100+alcora-dev[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:07:04 +0000 Subject: [PATCH 4/4] fix(pages-router): recognise router navigate events across next/router instances --- packages/vinext/src/shims/router.ts | 5 +++- .../pages-router/first-render-router.spec.ts | 30 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/packages/vinext/src/shims/router.ts b/packages/vinext/src/shims/router.ts index 8b4fc92829..a2300bc187 100644 --- a/packages/vinext/src/shims/router.ts +++ b/packages/vinext/src/shims/router.ts @@ -3229,8 +3229,11 @@ function stripHash(url: string): string { /** * `detail` of the `vinext:navigate` events the router dispatches. Every such * navigation has already committed its router snapshot (`commitRouterSnapshot`). + * A string, not an object: the client entry and page chunks can each evaluate + * their own `next/router` instance, and the provider must recognise an event + * dispatched by any of them. */ -const ROUTER_NAVIGATE_EVENT_DETAIL = { routerStateCommitted: true } as const; +const ROUTER_NAVIGATE_EVENT_DETAIL = "vinext.routerStateCommitted"; /** Notify in-page listeners (e.g. useRouter hooks) that navigation occurred. */ function dispatchNavigateEvent(): void { diff --git a/tests/e2e/pages-router/first-render-router.spec.ts b/tests/e2e/pages-router/first-render-router.spec.ts index 5bf587f5fa..aa413ede71 100644 --- a/tests/e2e/pages-router/first-render-router.spec.ts +++ b/tests/e2e/pages-router/first-render-router.spec.ts @@ -100,3 +100,33 @@ test("useRouter() keeps the committed route if location moves after the commit", } await expect(page.locator('[data-testid="first-render-id"]')).toHaveText("2"); }); + +// The client entry and page chunks can each evaluate their own `next/router` +// instance, so the provider may receive `vinext:navigate` from a router module +// other than its own. Such an event carries the router's marker as a value +// created outside the provider's module, and must still count as a committed +// navigation, never a cue to re-read the live location. +test("useRouter() treats vinext:navigate from another router instance as committed", async ({ + page, +}) => { + await page.goto(`${BASE}/first-render-router/1`); + await page.waitForFunction(() => (window as any).next?.router?.isReady === true); + await takeRenders(page); + + await page.evaluate(async () => { + window.history.replaceState(window.history.state, "", "/first-render-router/1?moved=1"); + window.dispatchEvent( + new CustomEvent("vinext:navigate", { detail: "vinext.routerStateCommitted" }), + ); + await new Promise((resolve) => setTimeout(resolve, 50)); + }); + + // Nothing was committed, so the provider has no reason to re-render; any + // render that does happen must still see the committed route. + for (const render of await takeRenders(page)) { + expect({ query: render.query, asPath: render.asPath }).toEqual({ + query: { id: "1" }, + asPath: "/first-render-router/1", + }); + } +});