Unverified Commit 41b002e5 authored by vercel[bot]'s avatar vercel[bot] Committed by GitHub

Fix scroll to top after a redirect during client navigation

When a proxy redirected a client-side navigation to a route that optimistic routing did not predict, the retry that corrects the URL used FreshnessPolicy.HistoryTraversal. That policy never assigns a ScrollRef to new segments and reads the BFCache regardless of staleness, so the destination kept the previous scroll position and could render stale content.

Use FreshnessPolicy.Default for the redirect retry, like a seeded redirect from a Server Action: the received data is still reused instead of re-fetched, and new segments scroll into view.

Fixes #98172
Co-Authored-By: 's avatarMarcos Hernanz <96699542+marcoshernanz@users.noreply.github.com>
parent 65c832c8
......@@ -1599,7 +1599,15 @@ async function finishNavigationTask(
// 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.
// instead of re-fetching it.
//
// This is a forward navigation to the redirect destination that happens
// to be seeded with the response, so it uses the Default policy (like a
// redirect from a Server Action): segments that changed are created from
// the seed and scrolled into view like any other navigation. It must not
// use HistoryTraversal, which suppresses the scroll and reads the BFCache
// regardless of staleness, because back/forward restores a previous
// state rather than rendering a new one. See issues #95195 and #98172.
const isHardRetry = false
const primaryRequestResult = await primaryRequestPromise
dispatchRetryDueToTreeMismatch(
......@@ -1610,7 +1618,7 @@ async function finishNavigationTask(
task.route,
routeCacheEntry,
navigateType,
FreshnessPolicy.HistoryTraversal
FreshnessPolicy.Default
)
return
}
......@@ -1705,12 +1713,10 @@ function dispatchRetryDueToTreeMismatch(
// The original navigation's push/replace intent.
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
// tree's dynamic data (used for genuine tree mismatches). `Default` reuses
// the data already in the tree (used when only the URL needs correcting
// after a redirect).
retryFreshnessPolicy: FreshnessPolicy.RefreshAll | FreshnessPolicy.Default
) {
// If the navigation used a route prediction, mark it as having a dynamic
// rewrite since it resulted in a mismatch.
......
......@@ -44,8 +44,8 @@ export function serverPatchReducer(
//
// 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.
// changed the canonical URL reuses the data already in the tree (`Default`),
// since the data we received is correct.
const retryCanonicalUrl = createHrefFromUrl(retryUrl)
const retryNextUrl = action.nextUrl
const scrollBehavior = ScrollBehavior.Default
......
......@@ -129,11 +129,10 @@ export interface ServerPatchAction {
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).
* tree's dynamic data (genuine tree mismatch). `Default` reuses the data
* already in the tree (when only the URL needs correcting after a redirect).
*/
freshnessPolicy: FreshnessPolicy.RefreshAll | FreshnessPolicy.HistoryTraversal
freshnessPolicy: FreshnessPolicy.RefreshAll | FreshnessPolicy.Default
}
/**
......
export default function AboutPage() {
return (
<main>
<h1 id="about-page">About</h1>
{/* Tall filler so a preserved scroll offset keeps the heading off-screen. */}
<div style={{ height: 5000 }} />
</main>
)
}
import Link from 'next/link'
export default function HomePage() {
return (
<main>
<h1 id="home-page">Home</h1>
{/* Tall filler so the links are far below the fold. */}
<div style={{ height: 5000 }} />
{/* The proxy redirects /about (no locale prefix) to /en/about. */}
<Link href="/about" id="link-redirected">
Go to /about (redirected to /en/about)
</Link>
{/* Control: same destination, no redirect. */}
<Link href="/en/about" id="link-direct">
Go to /en/about
</Link>
</main>
)
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { NextResponse, type NextRequest } from 'next/server'
// Redirects paths without a locale prefix to the `en` locale, e.g.
// /about -> /en/about.
export default function proxy(request: NextRequest) {
const { pathname } = request.nextUrl
if (pathname === '/en' || pathname.startsWith('/en/')) {
return NextResponse.next()
}
return NextResponse.redirect(new URL(`/en${pathname}`, request.url), 308)
}
export const config = {
matcher: '/((?!_next|favicon.ico).*)',
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import type * as Playwright from 'playwright'
// Reproduction for https://github.com/vercel/next.js/issues/98172
//
// The proxy redirects paths without a locale prefix to the `en` locale
// (/about -> /en/about). A client-side navigation to `/about` is predicted by
// optimistic routing as the `/[locale]` page, so the redirect is only
// discovered when the dynamic data arrives. The router then re-resolves the
// route to correct the URL. Like any other navigation to a new page, that
// correction must scroll the new page into view.
describe('scroll to top after a proxy redirect (#98172)', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
// Optimistic routing is a production-build feature. In dev mode there is
// no route prediction, so the redirect is followed before the navigation
// commits and the retry path is never taken.
test('disabled in development', () => {})
return
}
async function navigateFromBottomOfHomePage(linkId: string) {
let page: Playwright.Page
const browser = await next.browser('/en', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
// Scroll away from the top of the page before navigating.
await browser.eval('window.scrollTo(0, 2500)')
await retry(async () => {
expect(await browser.eval('window.scrollY')).toBe(2500)
})
await browser.elementById(linkId).click()
await page.waitForURL((url) => url.pathname === '/en/about')
expect(await browser.elementById('about-page').text()).toBe('About')
// The new page should be scrolled into view.
await retry(async () => {
expect(await browser.eval('window.scrollY')).toBe(0)
})
}
it('scrolls to the top when the proxy redirects the navigation', async () => {
await navigateFromBottomOfHomePage('link-redirected')
})
it('scrolls to the top when the navigation is not redirected', async () => {
await navigateFromBottomOfHomePage('link-direct')
})
})
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