Unverified Commit ae6d43b8 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Fix: Update the URL when a client navigation redirects to a rewritten route (#95207)

On a client-side navigation, when a proxy/middleware redirected the
requested URL to a destination that was itself rewritten to a
dynamically rendered route, the page content updated correctly but the
address bar stayed on the original URL. Hard navigations (reload, typing
the URL) were unaffected.

This happened because the navigation optimistically committed the
predicted URL up front, and when the redirect resolved to a route with
the same shape as the prediction, the router treated the navigation as
already correct and never reconciled the address bar.

A redirect discovered during a navigation now invalidates the prediction
and re-resolves the route, so the address bar reflects the redirect
destination.

Adds an end-to-end test covering the regression.

Fixes #95195
parent 1682685a
...@@ -109,7 +109,7 @@ const enum NavigationTaskExitStatus { ...@@ -109,7 +109,7 @@ const enum NavigationTaskExitStatus {
Done = 0, Done = 0,
/** /**
* Some data failed to load, presumably due to a route tree mismatch. Perform * Some data failed to load, presumably due to a route tree mismatch. Perform
* a soft retry to reload the entire tree. * a soft retry to reload the entire tree (re-fetching the dynamic data).
*/ */
SoftRetry = 1, SoftRetry = 1,
/** /**
...@@ -117,6 +117,14 @@ const enum NavigationTaskExitStatus { ...@@ -117,6 +117,14 @@ const enum NavigationTaskExitStatus {
* parallel route. Fall back to a hard (MPA-style) retry. * parallel route. Fall back to a hard (MPA-style) retry.
*/ */
HardRetry = 2, HardRetry = 2,
/**
* The route tree matched, but the request was redirected, so the navigation
* committed the wrong canonical URL. The route cache is no longer reliable
* (the redirect implies a server change the prediction couldn't account for),
* so we re-resolve the route — but the data we already received is correct, so
* the retry reuses it instead of re-fetching.
*/
RedirectRetry = 3,
} }
export type NavigationRequestAccumulation = { export type NavigationRequestAccumulation = {
...@@ -1536,7 +1544,8 @@ async function finishNavigationTask( ...@@ -1536,7 +1544,8 @@ async function finishNavigationTask(
return return
} }
case NavigationTaskExitStatus.SoftRetry: { case NavigationTaskExitStatus.SoftRetry: {
// Some data failed to finish loading. Trigger a soft retry. // Some data failed to finish loading. Trigger a soft retry that re-fetches
// the tree's dynamic data.
// TODO: As an extra precaution against soft retry loops, consider // TODO: As an extra precaution against soft retry loops, consider
// tracking whether a navigation was itself triggered by a retry. If two // tracking whether a navigation was itself triggered by a retry. If two
// happen in a row, fall back to a hard retry. // happen in a row, fall back to a hard retry.
...@@ -1549,7 +1558,27 @@ async function finishNavigationTask( ...@@ -1549,7 +1558,27 @@ async function finishNavigationTask(
primaryRequestResult.seed, primaryRequestResult.seed,
task.route, task.route,
routeCacheEntry, routeCacheEntry,
navigateType navigateType,
FreshnessPolicy.RefreshAll
)
return
}
case NavigationTaskExitStatus.RedirectRetry: {
// The route matched, but the request was redirected, so we committed the
// wrong canonical URL. Re-resolve the route to invalidate the now-stale
// route cache and correct the URL — but reuse the data we already received
// (HistoryTraversal) instead of re-fetching it. See issue #95195.
const isHardRetry = false
const primaryRequestResult = await primaryRequestPromise
dispatchRetryDueToTreeMismatch(
isHardRetry,
primaryRequestResult.url,
nextUrl,
primaryRequestResult.seed,
task.route,
routeCacheEntry,
navigateType,
FreshnessPolicy.HistoryTraversal
) )
return return
} }
...@@ -1571,7 +1600,8 @@ async function finishNavigationTask( ...@@ -1571,7 +1600,8 @@ async function finishNavigationTask(
primaryRequestResult.seed, primaryRequestResult.seed,
task.route, task.route,
routeCacheEntry, routeCacheEntry,
navigateType navigateType,
FreshnessPolicy.RefreshAll
) )
return return
} }
...@@ -1641,7 +1671,14 @@ function dispatchRetryDueToTreeMismatch( ...@@ -1641,7 +1671,14 @@ function dispatchRetryDueToTreeMismatch(
// a dynamic rewrite so future predictions bail out. // a dynamic rewrite so future predictions bail out.
routeCacheEntry: FulfilledRouteCacheEntry | null, routeCacheEntry: FulfilledRouteCacheEntry | null,
// The original navigation's push/replace intent. // The original navigation's push/replace intent.
originalNavigateType: 'push' | 'replace' originalNavigateType: 'push' | 'replace',
// Freshness policy for the retry navigation. `RefreshAll` re-fetches the
// tree's dynamic data (used for genuine tree mismatches). `HistoryTraversal`
// reuses the data already in the tree (used when only the URL needs
// correcting after a redirect).
retryFreshnessPolicy:
| FreshnessPolicy.RefreshAll
| FreshnessPolicy.HistoryTraversal
) { ) {
// If the navigation used a route prediction, mark it as having a dynamic // If the navigation used a route prediction, mark it as having a dynamic
// rewrite since it resulted in a mismatch. // rewrite since it resulted in a mismatch.
...@@ -1709,6 +1746,7 @@ function dispatchRetryDueToTreeMismatch( ...@@ -1709,6 +1746,7 @@ function dispatchRetryDueToTreeMismatch(
seed, seed,
mpa: isHardRetry, mpa: isHardRetry,
navigateType: retryNavigateType, navigateType: retryNavigateType,
freshnessPolicy: retryFreshnessPolicy,
} }
dispatchAppRouterAction(retryAction) dispatchAppRouterAction(retryAction)
} }
...@@ -1835,11 +1873,43 @@ async function fetchMissingDynamicData( ...@@ -1835,11 +1873,43 @@ async function fetchMissingDynamicData(
result.revealAfter result.revealAfter
) )
const resolvedUrl = new URL(result.canonicalUrl, location.origin)
// Decide whether the navigation needs to be retried.
//
// - A tree mismatch (unknown parallel route) means the data is incomplete,
// so we soft-retry and re-fetch the whole tree.
// - Otherwise, the navigation committed the canonical URL from the route
// cache entry it used (a prediction or prefetch). If the request resolved
// to a *different* canonical URL — e.g. a middleware/proxy redirect the
// prediction didn't account for — then the committed URL is wrong and the
// route cache it came from is no longer reliable (the redirect implies a
// server change the prediction couldn't know about, like logging in or
// out). We re-resolve the route to invalidate the stale cache and correct
// the browser URL, reusing the data we just received rather than
// re-fetching it. When the entry already reflects the redirect (e.g. a
// prefetch that followed it), the committed URL matches and no retry is
// needed. See issue #95195.
let didCommitWrongUrl = false
if (routeCacheEntry !== null) {
const committedUrl = new URL(
routeCacheEntry.canonicalUrl,
location.origin
)
didCommitWrongUrl =
committedUrl.pathname !== resolvedUrl.pathname ||
committedUrl.search !== resolvedUrl.search
}
const exitStatus = didReceiveUnknownParallelRoute
? NavigationTaskExitStatus.SoftRetry
: didCommitWrongUrl
? NavigationTaskExitStatus.RedirectRetry
: NavigationTaskExitStatus.Done
return { return {
exitStatus: didReceiveUnknownParallelRoute exitStatus,
? NavigationTaskExitStatus.SoftRetry url: resolvedUrl,
: NavigationTaskExitStatus.Done,
url: new URL(result.canonicalUrl, location.origin),
seed, seed,
} }
} catch { } catch {
......
...@@ -11,7 +11,7 @@ import { ...@@ -11,7 +11,7 @@ import {
navigateToKnownRoute, navigateToKnownRoute,
} from '../../segment-cache/navigation' } from '../../segment-cache/navigation'
import { refreshReducer } from './refresh-reducer' import { refreshReducer } from './refresh-reducer'
import { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations' import { getCurrentNavigationLock } from '../ppr-navigations'
export function serverPatchReducer( export function serverPatchReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
...@@ -40,6 +40,11 @@ export function serverPatchReducer( ...@@ -40,6 +40,11 @@ export function serverPatchReducer(
} }
// There have been no new navigations since the mismatched one. Refresh, // There have been no new navigations since the mismatched one. Refresh,
// using the tree we just received from the server. // using the tree we just received from the server.
//
// The freshness policy comes from the action: a genuine tree mismatch
// re-fetches the dynamic data (`RefreshAll`), whereas a redirect that only
// changed the canonical URL reuses the data already in the tree
// (`HistoryTraversal`), since the data we received is correct.
const retryCanonicalUrl = createHrefFromUrl(retryUrl) const retryCanonicalUrl = createHrefFromUrl(retryUrl)
const retryNextUrl = action.nextUrl const retryNextUrl = action.nextUrl
const scrollBehavior = ScrollBehavior.Default const scrollBehavior = ScrollBehavior.Default
...@@ -55,7 +60,7 @@ export function serverPatchReducer( ...@@ -55,7 +60,7 @@ export function serverPatchReducer(
currentRenderedSearch, currentRenderedSearch,
state.cache, state.cache,
state.tree, state.tree,
FreshnessPolicy.RefreshAll, action.freshnessPolicy,
retryNextUrl, retryNextUrl,
scrollBehavior, scrollBehavior,
navigateType, navigateType,
......
...@@ -2,6 +2,7 @@ import type { CacheNode, ScrollRef } from '../../../shared/lib/app-router-types' ...@@ -2,6 +2,7 @@ import type { CacheNode, ScrollRef } from '../../../shared/lib/app-router-types'
import type { FlightRouterState } from '../../../shared/lib/app-router-types' import type { FlightRouterState } from '../../../shared/lib/app-router-types'
import type { NavigationSeed } from '../segment-cache/navigation' import type { NavigationSeed } from '../segment-cache/navigation'
import type { FetchServerResponseResult } from './fetch-server-response' import type { FetchServerResponseResult } from './fetch-server-response'
import type { FreshnessPolicy } from './ppr-navigations'
export const ACTION_REFRESH = 'refresh' export const ACTION_REFRESH = 'refresh'
export const ACTION_NAVIGATE = 'navigate' export const ACTION_NAVIGATE = 'navigate'
...@@ -125,6 +126,13 @@ export interface ServerPatchAction { ...@@ -125,6 +126,13 @@ export interface ServerPatchAction {
seed: NavigationSeed | null seed: NavigationSeed | null
mpa: boolean mpa: boolean
navigateType: 'push' | 'replace' navigateType: 'push' | 'replace'
/**
* Freshness policy for the retry navigation. `RefreshAll` re-fetches the
* tree's dynamic data (genuine tree mismatch). `HistoryTraversal` reuses the
* data already in the tree (when only the URL needs correcting after a
* redirect).
*/
freshnessPolicy: FreshnessPolicy.RefreshAll | FreshnessPolicy.HistoryTraversal
} }
/** /**
......
import { connection } from 'next/server'
import { Suspense } from 'react'
import { LinkAccordion } from '../../components/link-accordion'
async function Content({ params }: { params: Promise<{ slug: string }> }) {
// Opt into dynamic rendering and read the `[slug]` param.
await connection()
const { slug } = await params
// slug === "a" means we're at / (proxy rewrites / -> /a).
const isHome = slug === 'a'
return (
<main>
{/* Build the string in JS-land so the literal "slug: a" appears in the
Flight response body (see router-act skill: JSX interpolation
splits the string in the wire format). */}
<h1 id="page" data-testid="page">{`slug: ${slug}`}</h1>
{isHome ? (
<p>
This is the home page (<code>/</code>), served via a proxy rewrite
from <code>/a</code>.
<LinkAccordion href="/two" prefetch={false}>
Go to /two
</LinkAccordion>
</p>
) : (
<p>
Click the link. The proxy redirects <code>/a</code> to <code>/</code>,
so the URL should change to <code>/</code>.
<LinkAccordion href="/a" prefetch={false}>
Go to /a
</LinkAccordion>
</p>
)}
</main>
)
}
export default function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
// The dynamic data access (connection/params) lives inside a Suspense
// boundary so the route can still be prerendered when cacheComponents is on.
return (
<Suspense fallback={<div id="loading">Loading...</div>}>
<Content params={params} />
</Suspense>
)
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children?: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
const resolvedChildren = children ?? href
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{resolvedChildren}
</Link>
) : (
<>{resolvedChildren} (link is hidden)</>
)}
</>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { NextRequest, NextResponse } from 'next/server'
// Reproduces https://github.com/vercel/next.js/issues/95195
//
// A plain proxy (formerly "middleware"):
// /a -> redirect to /
// / -> rewrite to /a (so `/` is served by the dynamic `/a` page)
//
// i.e. the redirect target (`/`) is rewritten to a dynamic, param-reading page.
export default function proxy(request: NextRequest) {
const { pathname } = request.nextUrl
if (pathname === '/a') {
return NextResponse.redirect(new URL('/', request.url))
}
if (pathname === '/') {
return NextResponse.rewrite(new URL('/a', request.url))
}
return NextResponse.next()
}
export const config = {
matcher: '/((?!_next|favicon.ico).*)',
}
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
// Reproduction for https://github.com/vercel/next.js/issues/95195
//
// Proxy rules:
// /a -> redirect to /
// / -> rewrite to /a (a dynamic, param-reading page)
//
// On a client-side navigation to `/a`, the proxy redirects to `/`. The URL in
// the address bar should update to `/` (the redirect destination), but on the
// 16.3 preview it stays at `/a`. Hard navigation (typing the URL / reload)
// works correctly; only client-side navigation regressed.
describe('redirect to a rewritten dynamic route (#95195)', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
test('disabled in development', () => {})
return
}
function relativeHref(href: string) {
const url = new URL(href)
return url.pathname + url.search + url.hash
}
it('hard navigation to /a redirects to /', async () => {
// Sanity check: the proxy redirect works on a full page load.
const browser = await next.browser('/a')
expect(await browser.elementById('page').text()).toBe('slug: a')
expect(relativeHref(await browser.url())).toBe('/')
})
it('client-side navigation to /a should update the URL to /', async () => {
let page: Playwright.Page
const browser = await next.browser('/two', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
// Starting page renders the dynamic `/two` route (slug === "two").
expect(await browser.elementById('page').text()).toBe('slug: two')
// Reveal the link (prefetch is disabled, so no request fires here) and
// click it to navigate to /a.
const toggle = await browser.elementByCss('input[data-link-accordion="/a"]')
await toggle.click()
const link = await browser.elementByCss('a[href="/a"]')
await link.click()
// The proxy redirects /a -> / (then rewrites / -> /a). Wait for the client
// router to settle on the redirect destination. This is an event-driven
// wait for the exact expected URL: if the redirect isn't reflected (the
// bug), it times out and fails, rather than being papered over by polling.
await page.waitForURL((url) => url.pathname === '/')
// The rewritten home page content rendered, and the URL reflects the
// redirect destination `/`, not the link target `/a`.
expect(await browser.elementById('page').text()).toBe('slug: a')
expect(relativeHref(await browser.url())).toBe('/')
})
})
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