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

Fix route cache keying for unprefetched navigations (#90400)

When navigating to a route that wasn't previously prefetched (e.g. via a
Link with prefetch={false}, or router.push()), the client stores the
route data from the server response in the cache so it can be reused by
future navigations and prefetches to the same URL.

These entries were being stored with a null "nextUrl" cache key, but
lookups use the real nextUrl from router state, so every subsequent
lookup missed. This caused redundant requests for route data the client
already had.

The fix threads the nextUrl through the route discovery path so it
reaches the cache write with the correct value. For non-intercepted
routes the entry is keyed with a wildcard (reusable regardless of
nextUrl); for intercepted routes it uses the specific nextUrl, since the
route structure varies by referrer.

Also cleans up how interception routes interact with the optimistic
route matching system: patterns are now always stored during discovery
(previously they were skipped), and the interception bailout happens in
a single place during matching rather than being duplicated across
multiple check sites.

Closes #88863 
Co-authored-by: 's avatarHendrik Liebau <mail@hendrik-liebau.de>
Co-authored-by: 's avatarHamidreza Hanafi <hamidreza.hanafi@faire.com>

---------
Co-authored-by: 's avatarHendrik Liebau <mail@hendrik-liebau.de>
Co-authored-by: 's avatarHamidreza Hanafi <hamidreza.hanafi@faire.com>
parent 426d0d2e
...@@ -76,6 +76,7 @@ export function createInitialRouterState({ ...@@ -76,6 +76,7 @@ export function createInitialRouterState({
discoverKnownRoute( discoverKnownRoute(
Date.now(), Date.now(),
location.pathname, location.pathname,
null, // nextUrl — initial render is never an interception
null, // No pending entry null, // No pending entry
initialRouteTree, initialRouteTree,
metadataVaryPath, metadataVaryPath,
......
...@@ -1470,6 +1470,7 @@ function dispatchRetryDueToTreeMismatch( ...@@ -1470,6 +1470,7 @@ function dispatchRetryDueToTreeMismatch(
discoverKnownRoute( discoverKnownRoute(
now, now,
retryUrl.pathname, retryUrl.pathname,
retryNextUrl,
null, null,
seed.routeTree, seed.routeTree,
metadataVaryPath, metadataVaryPath,
......
...@@ -419,6 +419,7 @@ export function serverActionReducer( ...@@ -419,6 +419,7 @@ export function serverActionReducer(
discoverKnownRoute( discoverKnownRoute(
now, now,
redirectUrl.pathname, redirectUrl.pathname,
nextUrl,
null, // No pending entry null, // No pending entry
redirectSeed.routeTree, redirectSeed.routeTree,
metadataVaryPath, metadataVaryPath,
......
...@@ -57,6 +57,7 @@ import { createHrefFromUrl } from '../router-reducer/create-href-from-url' ...@@ -57,6 +57,7 @@ import { createHrefFromUrl } from '../router-reducer/create-href-from-url'
import type { import type {
NormalizedPathname, NormalizedPathname,
NormalizedSearch, NormalizedSearch,
NormalizedNextUrl,
RouteCacheKey, RouteCacheKey,
} from './cache-key' } from './cache-key'
import { createCacheKey as createPrefetchRequestKey } from './cache-key' import { createCacheKey as createPrefetchRequestKey } from './cache-key'
...@@ -1040,6 +1041,7 @@ export function fulfillRouteCacheEntry( ...@@ -1040,6 +1041,7 @@ export function fulfillRouteCacheEntry(
export function writeRouteIntoCache( export function writeRouteIntoCache(
now: number, now: number,
pathname: NormalizedPathname, pathname: NormalizedPathname,
nextUrl: string | null,
tree: RouteTree, tree: RouteTree,
metadataVaryPath: PageVaryPath, metadataVaryPath: PageVaryPath,
couldBeIntercepted: boolean, couldBeIntercepted: boolean,
...@@ -1056,10 +1058,13 @@ export function writeRouteIntoCache( ...@@ -1056,10 +1058,13 @@ export function writeRouteIntoCache(
canonicalUrl, canonicalUrl,
isPPREnabled isPPREnabled
) )
// nextUrl is always null here because we only write to the route cache for
// non-intercepted routes. Intercepted routes are deopted in attemptOptimisticRouting.
const renderedSearch = fulfilledEntry.renderedSearch const renderedSearch = fulfilledEntry.renderedSearch
const varyPath = getRouteVaryPath(pathname, renderedSearch, null) const varyPath = getFulfilledRouteVaryPath(
pathname,
renderedSearch,
nextUrl as NormalizedNextUrl | null,
couldBeIntercepted
)
const isRevalidation = false const isRevalidation = false
setInCacheMap(routeCacheMap, varyPath, fulfilledEntry, isRevalidation) setInCacheMap(routeCacheMap, varyPath, fulfilledEntry, isRevalidation)
return fulfilledEntry return fulfilledEntry
...@@ -1701,6 +1706,7 @@ export async function fetchRouteOnCacheMiss( ...@@ -1701,6 +1706,7 @@ export async function fetchRouteOnCacheMiss(
discoverKnownRoute( discoverKnownRoute(
Date.now(), Date.now(),
pathname, pathname,
nextUrl,
entry, entry,
routeTree, routeTree,
metadataVaryPath, metadataVaryPath,
...@@ -1760,7 +1766,8 @@ export async function fetchRouteOnCacheMiss( ...@@ -1760,7 +1766,8 @@ export async function fetchRouteOnCacheMiss(
canonicalUrl, canonicalUrl,
routeIsPPREnabled, routeIsPPREnabled,
headVaryParams, headVaryParams,
pathname pathname,
nextUrl
) )
} }
...@@ -2098,7 +2105,8 @@ function writeDynamicTreeResponseIntoCache( ...@@ -2098,7 +2105,8 @@ function writeDynamicTreeResponseIntoCache(
canonicalUrl: string, canonicalUrl: string,
routeIsPPREnabled: boolean, routeIsPPREnabled: boolean,
headVaryParams: VaryParams | null, headVaryParams: VaryParams | null,
originalPathname: string originalPathname: string,
nextUrl: string | null
): void { ): void {
const renderedSearch = getRenderedSearch(response) const renderedSearch = getRenderedSearch(response)
...@@ -2147,6 +2155,7 @@ function writeDynamicTreeResponseIntoCache( ...@@ -2147,6 +2155,7 @@ function writeDynamicTreeResponseIntoCache(
const fulfilledEntry = discoverKnownRoute( const fulfilledEntry = discoverKnownRoute(
now, now,
originalPathname, originalPathname,
nextUrl,
entry, entry,
routeTree, routeTree,
metadataVaryPath, metadataVaryPath,
......
...@@ -390,6 +390,7 @@ async function navigateToUnknownRoute( ...@@ -390,6 +390,7 @@ async function navigateToUnknownRoute(
discoverKnownRoute( discoverKnownRoute(
now, now,
url.pathname, url.pathname,
nextUrl,
null, // No pending entry null, // No pending entry
navigationSeed.routeTree, navigationSeed.routeTree,
metadataVaryPath, metadataVaryPath,
......
...@@ -36,7 +36,11 @@ ...@@ -36,7 +36,11 @@
* *
* Current limitations (deopt to server resolution): * Current limitations (deopt to server resolution):
* - Rewrites: Detected during traversal (tree not populated, but route cached) * - Rewrites: Detected during traversal (tree not populated, but route cached)
* - Intercepted routes: Routes using (.), (..), (...) patterns * - Intercepted routes: The route tree varies by referrer (Next-Url header),
* so we can't predict the correct structure from the URL alone. Patterns are
* still stored during discovery (so the trie stays populated for non-
* intercepted siblings), but matching bails out when the pattern is marked
* as interceptable.
*/ */
import type { DynamicParamTypesShort } from '../../../shared/lib/app-router-types' import type { DynamicParamTypesShort } from '../../../shared/lib/app-router-types'
...@@ -167,6 +171,7 @@ let knownRouteTreeRoot: KnownRoutePart = createEmptyPart() ...@@ -167,6 +171,7 @@ let knownRouteTreeRoot: KnownRoutePart = createEmptyPart()
export function discoverKnownRoute( export function discoverKnownRoute(
now: number, now: number,
pathname: string, pathname: string,
nextUrl: string | null,
pendingEntry: PendingRouteCacheEntry | null, pendingEntry: PendingRouteCacheEntry | null,
routeTree: RouteTree, routeTree: RouteTree,
metadataVaryPath: PageVaryPath, metadataVaryPath: PageVaryPath,
...@@ -206,6 +211,7 @@ export function discoverKnownRoute( ...@@ -206,6 +211,7 @@ export function discoverKnownRoute(
fulfilledEntry, fulfilledEntry,
now, now,
pathname, pathname,
nextUrl,
tree, tree,
metadataVaryPath, metadataVaryPath,
couldBeIntercepted, couldBeIntercepted,
...@@ -226,6 +232,7 @@ export function discoverKnownRoute( ...@@ -226,6 +232,7 @@ export function discoverKnownRoute(
null, null,
now, now,
pathname, pathname,
nextUrl,
tree, tree,
metadataVaryPath, metadataVaryPath,
couldBeIntercepted, couldBeIntercepted,
...@@ -281,6 +288,7 @@ function discoverKnownRoutePart( ...@@ -281,6 +288,7 @@ function discoverKnownRoutePart(
// These are passed through unchanged for entry creation at the leaf // These are passed through unchanged for entry creation at the leaf
now: number, now: number,
pathname: string, pathname: string,
nextUrl: string | null,
fullTree: RouteTree, fullTree: RouteTree,
metadataVaryPath: PageVaryPath, metadataVaryPath: PageVaryPath,
couldBeIntercepted: boolean, couldBeIntercepted: boolean,
...@@ -321,6 +329,7 @@ function discoverKnownRoutePart( ...@@ -321,6 +329,7 @@ function discoverKnownRoutePart(
return writeRouteIntoCache( return writeRouteIntoCache(
now, now,
pathname as NormalizedPathname, pathname as NormalizedPathname,
nextUrl,
fullTree, fullTree,
metadataVaryPath, metadataVaryPath,
couldBeIntercepted, couldBeIntercepted,
...@@ -399,6 +408,7 @@ function discoverKnownRoutePart( ...@@ -399,6 +408,7 @@ function discoverKnownRoutePart(
existingEntry, existingEntry,
now, now,
pathname, pathname,
nextUrl,
fullTree, fullTree,
metadataVaryPath, metadataVaryPath,
couldBeIntercepted, couldBeIntercepted,
...@@ -421,6 +431,7 @@ function discoverKnownRoutePart( ...@@ -421,6 +431,7 @@ function discoverKnownRoutePart(
return writeRouteIntoCache( return writeRouteIntoCache(
now, now,
pathname as NormalizedPathname, pathname as NormalizedPathname,
nextUrl,
fullTree, fullTree,
metadataVaryPath, metadataVaryPath,
couldBeIntercepted, couldBeIntercepted,
...@@ -450,6 +461,7 @@ function discoverKnownRoutePart( ...@@ -450,6 +461,7 @@ function discoverKnownRoutePart(
entry = writeRouteIntoCache( entry = writeRouteIntoCache(
now, now,
pathname as NormalizedPathname, pathname as NormalizedPathname,
nextUrl,
fullTree, fullTree,
metadataVaryPath, metadataVaryPath,
couldBeIntercepted, couldBeIntercepted,
...@@ -493,8 +505,18 @@ export function matchKnownRoute( ...@@ -493,8 +505,18 @@ export function matchKnownRoute(
const matchedPart = match.part const matchedPart = match.part
const pattern = match.pattern const pattern = match.pattern
// If the pattern could be intercepted, we can't safely use it for prediction // If the pattern could be intercepted, we can't safely use it for prediction.
// because the route structure may vary based on the Next-Url header. // Interception routes resolve to different route trees depending on the
// referrer (the Next-Url header), which means the same URL can map to
// different page components depending on where the navigation originated.
// Since the known route tree only stores a single pattern per URL shape, we
// can't distinguish between the intercepted and non-intercepted cases, so we
// bail out to server resolution.
//
// TODO: We could store interception behavior in the known route tree itself
// (e.g., which segments use interception markers and what they resolve to).
// With enough information embedded in the trie, we could match interception
// routes entirely on the client without a server round-trip.
if (pattern.couldBeIntercepted) { if (pattern.couldBeIntercepted) {
return null return null
} }
......
...@@ -609,9 +609,13 @@ async function generateDynamicRSCPayload( ...@@ -609,9 +609,13 @@ async function generateDynamicRSCPayload(
).map((path) => path.slice(1)) // remove the '' (root) segment ).map((path) => path.slice(1)) // remove the '' (root) segment
} }
// In dev, the Vary header may not reliably reflect whether a route can
// be intercepted, because interception routes are compiled on demand.
// Default to true so the client doesn't cache a stale Fallback entry.
const varyHeader = ctx.res.getHeader('vary') const varyHeader = ctx.res.getHeader('vary')
const couldBeIntercepted = const couldBeIntercepted =
typeof varyHeader === 'string' && varyHeader.includes(NEXT_URL) !!process.env.__NEXT_DEV_SERVER ||
(typeof varyHeader === 'string' && varyHeader.includes(NEXT_URL))
// If we have an action result, then this is a server action response. // If we have an action result, then this is a server action response.
// We can rely on this because `ActionResult` will always be a promise, even if // We can rely on this because `ActionResult` will always be a promise, even if
...@@ -1473,9 +1477,13 @@ async function getRSCPayload( ...@@ -1473,9 +1477,13 @@ async function getRSCPayload(
// When the `vary` response header is present with `Next-URL`, that means there's a chance // When the `vary` response header is present with `Next-URL`, that means there's a chance
// it could respond differently if there's an interception route. We provide this information // it could respond differently if there's an interception route. We provide this information
// to `AppRouter` so that it can properly seed the prefetch cache with a prefix, if needed. // to `AppRouter` so that it can properly seed the prefetch cache with a prefix, if needed.
// In dev, the Vary header may not reliably reflect whether a route can
// be intercepted, because interception routes are compiled on demand.
// Default to true so the client doesn't cache a stale Fallback entry.
const varyHeader = ctx.res.getHeader('vary') const varyHeader = ctx.res.getHeader('vary')
const couldBeIntercepted = const couldBeIntercepted =
typeof varyHeader === 'string' && varyHeader.includes(NEXT_URL) !!process.env.__NEXT_DEV_SERVER ||
(typeof varyHeader === 'string' && varyHeader.includes(NEXT_URL))
const initialHead = createElement( const initialHead = createElement(
Fragment, Fragment,
......
...@@ -82,18 +82,15 @@ describe('force stale', () => { ...@@ -82,18 +82,15 @@ describe('force stale', () => {
await browser.back() await browser.back()
// Now reveal a link with prefetch={true} to the same page. Because we've // Now reveal a link with prefetch={true} to the same page. Because we've
// already navigated to this page, the data should be in the bfcache. // already navigated to this page, the route entry and segment data
// The prefetch should reuse the bfcache data instead of making a new // should already be in the cache. The prefetch should reuse the cached
// request to the server. // data instead of making a new request to the server.
await act( await act(async () => {
async () => { const toggleLinkVisibility = await browser.elementByCss(
const toggleLinkVisibility = await browser.elementByCss( 'input[data-link-accordion="/dynamic"]'
'input[data-link-accordion="/dynamic"]' )
) await toggleLinkVisibility.click()
await toggleLinkVisibility.click() }, 'no-requests')
},
{ includes: 'Dynamic page content', block: 'reject' }
)
} }
) )
}) })
import Link from 'next/link'
import { LinkAccordion } from '../../components/link-accordion'
export default function FeedPage() {
return (
<div>
<div id="feed-page">Feed page</div>
<h2>Step 1: Navigate without prefetch</h2>
<p style={{ color: '#666', fontSize: 14 }}>
Click this link to navigate to the photo page. Since prefetching is
disabled, the client has no cached data for this route and will fetch
everything from the server. The response is then stored in the route
cache for future use.
</p>
<p>
<Link href="/photo/1" prefetch={false} id="link-no-prefetch">
Go to photo 1 (no prefetch)
</Link>
</p>
<h2>Step 3: Reveal a prefetched link</h2>
<p style={{ color: '#666', fontSize: 14 }}>
After navigating to the photo page and back, toggle this checkbox to
reveal a prefetched link to the same URL. The prefetch system should
find the route data already in the cache from step 1 — no new network
requests should be needed. If the cache key was stored incorrectly, this
will trigger a redundant prefetch request.
</p>
<p>
<LinkAccordion href="/photo/1">
Go to photo 1 (prefetched)
</LinkAccordion>
</p>
</div>
)
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>
<div style={{ maxWidth: 600, margin: '0 auto', padding: 20 }}>
<h1>Route Cache Keying Regression Test</h1>
<p style={{ color: '#666', fontSize: 14 }}>
Reproduces a bug where navigating to an unprefetched route stored
the route cache entry with an incorrect key, causing subsequent
prefetches to the same URL to miss the cache and make redundant
requests. See{' '}
<a href="https://github.com/vercel/next.js/pull/88863">#88863</a>.
</p>
<p style={{ color: '#666', fontSize: 14 }}>
This test relies on the staleTimes feature to keep route cache
entries alive across navigations. The client cache currently only
writes segment data during prefetches, not navigations, so
staleTimes is needed to preserve the entries for reuse. Once
navigation-time caching is supported more broadly, this test could
use a simpler pattern.
</p>
<hr />
{children}
</div>
</body>
</html>
)
}
import { connection } from 'next/server'
import { Suspense } from 'react'
import Link from 'next/link'
async function PhotoContent({ params }: { params: Promise<{ id: string }> }) {
// connection() opts this page into dynamic rendering. This is important
// because the test uses staleTimes.dynamic to control when cache entries
// expire. Without dynamic rendering, the page would use the static stale
// time (which is long by default and would mask the bug).
await connection()
const { id } = await params
return <div id="photo-page">Photo {id}</div>
}
export default function PhotoPage({
params,
}: {
params: Promise<{ id: string }>
}) {
return (
<div>
<Suspense fallback={<div>Loading photo...</div>}>
<PhotoContent params={params} />
</Suspense>
<h2>Step 2: Navigate back</h2>
<p style={{ color: '#666', fontSize: 14 }}>
Click this link to go back to the feed page. The route and segment data
from this page remain in the client cache.
</p>
<p>
<Link href="/feed" prefetch={false} id="link-back-to-feed">
Back to feed
</Link>
</p>
</div>
)
}
'use client'
import Link from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
}: {
href: string
children: React.ReactNode
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href}>{children}</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
// The client segment cache currently only writes segment data during
// prefetches, not during navigations. The staleTimes feature is an
// exception: it preserves route cache entries for reuse across
// navigations. We rely on this to reproduce the bug — without it,
// dynamic route cache entries expire immediately, so the second lookup
// would always miss regardless of whether the key is correct.
//
// Once the client cache writes segment data during navigations more
// broadly, this test could be rewritten without this config.
staleTimes: {
dynamic: 180,
},
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { createRouterAct } from 'router-act'
describe('optimistic routing - route cache keying regression', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
test('skipped in dev mode', () => {})
return
}
// Regression test for https://github.com/vercel/next.js/pull/88863
//
// When navigating to a route that was not previously prefetched (e.g. via
// a Link with prefetch={false}, or router.push()), the client creates a
// route cache entry from the server response so it can be reused by future
// navigations and prefetches to the same URL.
//
// A bug caused these entries to be stored with an incorrect cache key: the
// "nextUrl" dimension (which tracks the referring page for interception
// route purposes) was always set to null, even though the rest of the
// system uses the real nextUrl value when looking up entries. This meant
// every subsequent cache lookup missed, and the client would make
// redundant requests for route data it already had.
//
// To reproduce:
//
// 1. Navigate to a dynamic page via a non-prefetched link. The client
// receives the route tree and segment data from the server and stores
// them in the cache.
//
// 2. Navigate back to the original page.
//
// 3. Reveal a prefetched link pointing to the same URL from step 1. The
// prefetch system should find the route tree and segment data already
// in the cache — no new network requests needed.
//
// Without the fix, step 3 triggers a redundant route tree prefetch because
// the cache lookup misses due to the key mismatch.
//
// NOTE: This test relies on the staleTimes.dynamic config to keep route
// cache entries alive across navigations. This is necessary because the
// client segment cache currently only writes segment data during
// prefetches, not during navigations — with the exception of the stale
// times feature, which preserves entries for reuse. Once the client cache
// writes segment data during navigations more broadly, this test could be
// rewritten using a more idiomatic pattern without the staleTimes config.
//
// The target page calls connection() to opt into dynamic rendering, which
// is what makes the staleTimes.dynamic config relevant (static pages use a
// different, longer stale time that would mask the bug).
it('regression: route cache entries from navigation are reusable by subsequent prefetches', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/feed', {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
// Navigate to the photo page. This link has prefetch={false}, so the
// client has no cached data for this route. It fetches the route tree
// and page data from the server in a single request, then stores both
// in the cache for future use.
const unprefetchedLink = await browser.elementByCss('#link-no-prefetch')
await act(async () => {
await unprefetchedLink.click()
})
const photoPage = await browser.elementById('photo-page')
expect(await photoPage.text()).toBe('Photo 1')
// Navigate back to the feed page.
const backLink = await browser.elementByCss('#link-back-to-feed')
await backLink.click()
await browser.elementByCss('#feed-page')
// Reveal a prefetched link to the same photo page. This triggers the
// prefetch system to look up the route cache. If the entry from the
// first navigation was stored correctly, the prefetch finds it (along
// with the segment data in the back/forward cache) and no network
// requests are needed. If the cache key was wrong, this would trigger
// a redundant route tree prefetch.
await act(async () => {
const reveal = await browser.elementByCss(
'input[data-link-accordion="/photo/1"]'
)
await reveal.click()
}, 'no-requests')
// Navigate using the now-prefetched link. The page should render
// immediately from the cache.
const prefetchedLink = await browser.elementByCss('a[href="/photo/1"]')
await act(async () => {
await prefetchedLink.click()
const page = await browser.elementById('photo-page')
expect(await page.text()).toBe('Photo 1')
}, 'no-requests')
})
})
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