Skip to content

fix(pages-router): give useRouter() the new route on the first render after a client navigation - #4749

Merged
james-elicx merged 4 commits into
mainfrom
alcora/run_2x551z2x440c0c2i2272/fix/fix
Nov 17, 2026
Merged

james-elicx merged 4 commits into
mainfrom
alcora/run_2x551z2x440c0c2i2272/fix/fix

Conversation

@alcora-dev

@alcora-dev alcora-dev Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #4748

After a client-side navigation in the Pages Router, the destination page's first render got the previous route from useRouter(): query, pathname and asPath were still the ones from the page you left, though window.location had already changed. The right values only arrived on a second render, after vinext:navigate fired. Next.js gives the new page the new route on its first render: Router#set() assigns this.state before calling this.sub(...) to render (packages/next/src/shared/lib/router/router.ts, set(state, data, resetScroll); checked in the installed next@16.2.7, dist/shared/lib/router/router.js).

Root cause

PagesRouterProvider (packages/vinext/src/shims/router.ts) kept the route snapshot in useState(getRouterSnapshot) and refreshed it only from the vinext:navigate listener and the ready timer. Both navigation render paths (renderPagesNavigationTarget for the data endpoint, and the HTML path in navigateClientHtml) commit history and window.__NEXT_DATA__ and then call root.render() through renderPagesRouterElement. The provider element keeps its type, so React keeps its state, and the page renders with the old snapshot. dispatchNavigateEvent() only runs after that render has committed.

Fix

This mirrors Router#set(), which assigns this.state for every router state change (full, shallow and hash-only) before anything renders from it. The provider only ever shows a committed snapshot, never the live location.

  • A new commitRouterSnapshot() stores routerRuntimeState.committedRouterSnapshot: the snapshot and a token that grows by one per commit. It is called where the router state changes:
    • in renderPagesRouterElement, right before root.render(), once the history entry and __NEXT_DATA__ are committed (push, replace and popstate, data and HTML paths);
    • after the history update of a shallow navigation, a hash-only push and a hash-only popstate;
    • in the provider's ready timer, when it flips the ready bit.
  • While rendering, PagesRouterProvider adopts that snapshot when its token is newer than the one in its state, calling setState during render before any child reads the context. The vinext:navigate listener adopts it the same way, so a render-backed navigation's snapshot, already adopted during render, is kept when the navigation completes, and router changes identity once per navigation.
  • So the live URL never leaks into the router state: not while a popstate's route is still resolving, not for a traversal beforePopState rejects (it never commits), and not if location moves between the commit and the completion event.
  • The router's own vinext:navigate events carry a string detail ("vinext.routerStateCommitted"). It is a string, not an object, so the provider recognises events from any next/router module instance (the client entry and page chunks can each evaluate their own). A vinext:navigate event dispatched outside the router, without that detail, still records the live state, as before. tests/e2e/pages-router/shallow-routing.spec.ts relies on that.
  • SSR and hydration are unchanged: no commit has happened, so the provider's initial state is taken as before.

getRouterSnapshot() and the next/navigation compat hooks are not changed.

Behaviour

What the destination page's render sees from useRouter():

Scenario Next.js 16.2.7 Before After
<Link> from /first-render-router to /first-render-router/1, first render new route query {}, asPath and pathname of the previous page new route
router.push from /first-render-router/1 to /2 (page stays mounted), first render new route id: "1" id: "2"
Back (popstate) to /first-render-router/1, first render new route id: "2" id: "1"
location moves after the navigation commits, before React renders and through completion committed route previous route, then the moved URL committed route on every render
Second render after vinext:navigate — (no extra render) new route, new router identity no snapshot change, router keeps its identity
Shallow push / hash change updated after the change updated by the listener updated by the listener, from the snapshot committed at the history update
Direct load / hydration new route new route new route (unchanged)

The Next.js column comes from its source (Router#set() assigning state before sub(), and AppContainer building the context from that state), not from running a Next.js app.

Tests

tests/e2e/pages-router/first-render-router.spec.ts, with new pages tests/fixtures/pages-basic/pages/first-render-router/{index,[id]}.tsx. The [id] page records useRouter() and location.pathname on every client render.

  • "returns the new route on the first render after client navigation": every render after a <Link> click, a router.push to another param and a back navigation sees the destination's query, pathname and asPath. On main it fails on the first step: the first render records {"query":{},"pathname":"/first-render-router","asPath":"/first-render-router","location":"/first-render-router/1"}.

  • "keeps the committed route if location moves after the commit": wraps __VINEXT_ROOT__.render so the URL changes with history.replaceState right after the push to /2 schedules its render, waits until routeChangeComplete and the vinext:navigate listener have run, and checks that every render saw /first-render-router/2. With a provider that re-reads the live location during render or on completion, a render mixed the moved URL with the committed page (asPath "/first-render-router/1?moved=1", query {id: "1", moved: "1"}). It also fails on main.

  • "treats vinext:navigate from another router instance as committed": moves the URL, then dispatches vinext:navigate with the router's marker built outside the provider's module, as a second next/router instance would, and checks that no render picks up the moved URL. With an object marker compared by identity, the provider took the event as external and rendered asPath "/first-render-router/1?moved=1".

Validation

  • PLAYWRIGHT_PROJECT=pages-router npx playwright test tests/e2e/pages-router/first-render-router.spec.ts --project=pages-router --retries=0: all three tests pass with the fix. With router.ts restored to main, the first two fail as described above.
  • PLAYWRIGHT_PROJECT=pages-router npx playwright test tests/e2e/pages-router/first-render-router.spec.ts tests/e2e/pages-router/shallow-routing.spec.ts tests/e2e/pages-router/before-pop-state.spec.ts --project=pages-router --retries=0: 20 passed. An earlier run that also included navigation.spec.ts: 39 passed (including hmr.spec.ts, which the config pulls in through pages-router-isolated; its MDX test failed intermittently in earlier runs, on main too).
  • npx vp test run tests/shims.test.ts: 1483 passed.
  • npx vp check: format, lint and type check pass.
  • Not run: a Next.js probe app; the comparison above is from its source.

@alcora-dev

alcora-dev Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

clanky review

@alcora-dev

alcora-dev Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

/bigbonk review for issues
Please review exact head c27052071a1ff92e4c4e82978a927960151111fd without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

@pkg-pr-new

pkg-pr-new Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@vinext/cloudflare

npm i https://pkg.pr.new/@vinext/cloudflare@4749

create-vinext-app

npm i https://pkg.pr.new/create-vinext-app@4749

@vinext/types

npm i https://pkg.pr.new/@vinext/types@4749

vinext

npm i https://pkg.pr.new/vinext@4749

@cloudflare/workers-response-store

npm i https://pkg.pr.new/@cloudflare/workers-response-store@4749

commit: 027f2fb

@github-actions

Copy link
Copy Markdown
Contributor
Example Preview Production Original
app-router-cloudflare preview production
pages-router-cloudflare preview production
app-router-playground preview production original
realworld-api-rest preview production
nextra-docs-template preview production
benchmarks preview production
hackernews preview production original
response-store-demo preview production
workers-cache preview production
kv preview production
static-assets-cache preview production
static-assets-pages preview production
static-assets-pages-i18n preview production
static-export preview production
web preview production

Comment thread packages/vinext/src/shims/router.ts Resolved
@ask-bonk

ask-bonk Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Review: 1 finding.

Posted 1 actionable inline finding about uncommitted popstate state leaking into router snapshots.

github run

@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Performance benchmarks

Compared 027f2fb against base f4f6d48 using alternating same-runner rounds. Next.js was unchanged and skipped.

1 improved · 0 regressed · 6 within ±1.5%

Scenario Framework Baseline Current Change
Client bundle size (gzip) vinext 152.5 KB 152.5 KB ⚫ 0.0%
Client entry size (gzip) vinext 140.8 KB 140.8 KB ⚫ 0.0%
Dev server cold start vinext 1.79 s 1.76 s 🟢 -1.8%
Dev server cold start (large Pages Router app) vinext 13.47 s 13.46 s ⚫ -0.1%
Production build time vinext 1.97 s 1.96 s ⚫ -0.4%
RSC entry closure size (gzip) vinext 143.0 KB 143.0 KB ⚫ +0.0%
Server bundle size (gzip) vinext 250.9 KB 250.9 KB ⚫ +0.0%

View detailed results and traces

🟢 improvement · 🔴 regression · ⚫ change below 1.5% · paired base/head

@alcora-dev

alcora-dev Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

/bigbonk review for issues
Please review exact head a0d55e326e6ea05d4b925b0f0526728fa3af85c8 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

Comment thread packages/vinext/src/shims/router.ts Resolved
@ask-bonk

ask-bonk Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Review: 1 finding.

Posted 1 actionable inline finding about the completion listener overwriting the committed router snapshot.

github run

@alcora-dev

alcora-dev Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

/bigbonk review for issues
Please review exact head f00fd0374eab33cdd11061359835bb82dbfccc12 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

Comment thread packages/vinext/src/shims/router.ts Resolved
@ask-bonk

ask-bonk Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Since last review: 1 resolved, 0 still open, 1 new.

Posted 1 actionable inline finding about the event marker failing across duplicate next/router module instances.

github run

@alcora-dev

alcora-dev Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

/bigbonk review for issues
Please review exact head 027f2fb5be9a2242e9fe321e7c898467ce43c606 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

@ask-bonk

ask-bonk Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

LGTM!

github run

@clanky-the-clanker

Copy link
Copy Markdown

This pull request was not reviewed automatically because it was opened by a bot. A maintainer with write access can start a review by commenting clanky review (or clanker review or @clanky-the-clanker review), optionally followed by instructions (e.g. clanky review focus on the retry logic).

@alcora-dev

alcora-dev Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

clanky review

@james-elicx
james-elicx merged commit 027d6d2 into main Nov 17, 2026
107 checks passed
@james-elicx
james-elicx deleted the alcora/run_2x551z2x440c0c2i2272/fix/fix branch November 17, 2026 14:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Pages Router: useRouter() returns the previous page's query/pathname/asPath on the first render after a client navigation

1 participant