Unverified Commit a79d85d1 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Make static page prefetch apply on navigation in app dir (#44502)

The initial prefetching implementation was based on the response
returning below the common layout, however when static generation was
added the RSC payload for these changed to only include the router tree
patch and the fully rendered page.

Currently the flow for prefetch is this:

- `router.prefetch`
- Fetch RSC payload
- Dispatch `ACTION_PREFETCH` with RSC payload. Note: the fetch is
intentionally not in the reducer as the fetch happens during an event or
effect, e.g. hover or `useEffect`
- Reducer handles `ACTION_PREFETCH`, creates the router tree, applies
the `subTreeData` to the cache append-only. Saves the new router tree in
the `prefetchCache` part of the reducer state.
- Then, on navigation, the `subTreeData` should be already available so
there's no additional apply. The router state is applied based on the
`prefetchCache`.

This approach is fine when the RSC payload returned never overrides the
`subTreeData` of an already existing node, however that does happen in
case of static pages because the subTreeData is for the root cache node
instead of a deeper node.

The new flow for prefetching:

- `router.prefetch`
- Fetch RSC payload
- Dispatch `ACTION_PREFETCH` with RSC payload
- Reducer handles `ACTION_PREFETCH`, creates the router tree, Saves the
new router tree and `subTreeData` in the `prefetchCache` part of the
reducer state.
- Then, on navigation, the `subTreeData` and router state are applied
based on the `prefetchCache`.

<!--
Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change that you're making:
-->

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [ ]
[e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 862deb5a
......@@ -284,61 +284,6 @@ function invalidateCacheBelowFlightSegmentPath(
)
}
/**
* Fill cache with subTreeData based on flightDataPath that was prefetched
* This operation is append-only to the existing cache.
*/
function fillCacheWithPrefetchedSubTreeData(
existingCache: CacheNode,
flightDataPath: FlightDataPath
): void {
const isLastEntry = flightDataPath.length <= 5
const [parallelRouteKey, segment] = flightDataPath
const segmentForCache = Array.isArray(segment) ? segment[1] : segment
const existingChildSegmentMap =
existingCache.parallelRoutes.get(parallelRouteKey)
if (!existingChildSegmentMap) {
// Bailout because the existing cache does not have the path to the leaf node
return
}
const existingChildCacheNode = existingChildSegmentMap.get(segmentForCache)
if (isLastEntry) {
if (!existingChildCacheNode) {
const childCacheNode: CacheNode = {
status: CacheStates.READY,
data: null,
subTreeData: flightDataPath[3],
parallelRoutes: new Map(),
}
fillLazyItemsTillLeafWithHead(
childCacheNode,
existingChildCacheNode,
flightDataPath[2],
flightDataPath[4]
)
existingChildSegmentMap.set(segmentForCache, childCacheNode)
}
return
}
if (!existingChildCacheNode) {
// Bailout because the existing cache does not have the path to the leaf node
return
}
fillCacheWithPrefetchedSubTreeData(
existingChildCacheNode,
flightDataPath.slice(2)
)
}
/**
* Kick off fetch based on the common layout between two routes. Fill cache with data property holding the in-progress fetch.
*/
......@@ -747,7 +692,7 @@ type AppRouterState = {
prefetchCache: Map<
string,
{
flightSegmentPath: FlightSegmentPath
flightData: FlightData
tree: FlightRouterState
canonicalUrlOverride: URL | undefined
}
......@@ -835,11 +780,25 @@ function clientReducer(
if (prefetchValues) {
// The one before last item is the router state tree patch
const {
flightSegmentPath,
flightData,
tree: newTree,
canonicalUrlOverride,
} = prefetchValues
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === 'string') {
return {
canonicalUrl: flightData,
// Enable mpaNavigation
pushRef: { pendingPush: true, mpaNavigation: true },
// Don't apply scroll and focus management.
focusAndScrollRef: { apply: false },
cache: state.cache,
prefetchCache: state.prefetchCache,
tree: state.tree,
}
}
if (newTree !== null) {
mutable.previousTree = state.tree
mutable.patchedTree = newTree
......@@ -848,6 +807,43 @@ function clientReducer(
newTree
)
if (newTree === null) {
throw new Error('SEGMENT MISMATCH')
}
const canonicalUrlOverrideHrefVal = canonicalUrlOverride
? createHrefFromUrl(canonicalUrlOverride)
: undefined
if (canonicalUrlOverrideHrefVal) {
mutable.canonicalUrlOverride = canonicalUrlOverrideHrefVal
}
mutable.mpaNavigation = isNavigatingToNewRootLayout(
state.tree,
newTree
)
// TODO-APP: Currently the Flight data can only have one item but in the future it can have multiple paths.
const flightDataPath = flightData[0]
const flightSegmentPath = flightDataPath.slice(
0,
-3
) as unknown as FlightSegmentPath
// The one before last item is the router state tree patch
const [treePatch, subTreeData, head] = flightDataPath.slice(-3)
// Handles case where prefetch only returns the router tree patch without rendered components.
if (subTreeData !== null) {
if (flightDataPath.length === 3) {
cache.subTreeData = subTreeData
fillLazyItemsTillLeafWithHead(cache, state.cache, treePatch, head)
} else {
// Copy subTreeData for the root node of the cache.
cache.subTreeData = state.cache.subTreeData
// Create a copy of the existing cache with the subTreeData applied.
fillCacheWithNewSubTreeData(cache, state.cache, flightDataPath)
}
}
const hardNavigate =
// TODO-APP: Revisit if this is correct.
search !== location.search ||
......@@ -867,7 +863,8 @@ function clientReducer(
state.cache,
flightSegmentPath
)
} else {
// Ensure the existing cache value is used when the cache was not invalidated.
} else if (subTreeData === null) {
mutable.useExistingCache = true
}
......@@ -1324,13 +1321,7 @@ function clientReducer(
const flightDataPath = flightData[0]
// The one before last item is the router state tree patch
const [treePatch, subTreeData] = flightDataPath.slice(-3)
// TODO-APP: Verify if `null` can't be returned from user code.
// If subTreeData is null the prefetch did not provide a component tree.
if (subTreeData !== null) {
fillCacheWithPrefetchedSubTreeData(state.cache, flightDataPath)
}
const [treePatch] = flightDataPath.slice(-3)
const flightSegmentPath = flightDataPath.slice(0, -3)
......@@ -1348,8 +1339,7 @@ function clientReducer(
// Create new tree based on the flightSegmentPath and router state patch
state.prefetchCache.set(href, {
// Path without the last segment, router state, and the subTreeData
flightSegmentPath,
flightData,
// Create new tree based on the flightSegmentPath and router state patch
tree: newTree,
canonicalUrlOverride,
......
import { use } from 'react'
export const revalidate = 0
async function getData() {
......@@ -8,8 +6,8 @@ async function getData() {
message: 'Welcome to the dashboard',
}
}
export default function DashboardPage(props) {
const { message } = use(getData())
export default async function DashboardPage(props) {
const { message } = await getData()
return (
<>
......
......@@ -5,6 +5,9 @@ export default function HomePage() {
<Link href="/dashboard" id="to-dashboard">
To Dashboard
</Link>
<Link href="/static-page" id="to-static-page">
To Static Page
</Link>
</>
)
}
export default async function Page() {
return (
<>
<p id="static-page">Static Page</p>
</>
)
}
import { createNextDescribe } from 'e2e-utils'
import { waitFor } from 'next-test-utils'
import { check, waitFor } from 'next-test-utils'
createNextDescribe(
'app dir prefetching',
......@@ -48,5 +48,30 @@ createNextDescribe(
expect(next.cliOutput).not.toContain('ReferenceError')
expect(next.cliOutput).not.toContain('is not defined')
})
it('should not fetch again when a static page was prefetched', async () => {
const browser = await next.browser('/', { waitHydration: false })
let requests: string[] = []
browser.on('request', (req) => {
requests.push(new URL(req.url()).pathname)
})
await browser.eval('window.nd.router.prefetch("/static-page")')
await check(() => {
return requests.some((req) => req.includes('static-page'))
? 'success'
: JSON.stringify(requests)
}, 'success')
await browser
.elementByCss('#to-static-page')
.click()
.waitForElementByCss('#static-page')
expect(
requests.filter((request) => request === '/static-page').length
).toBe(1)
})
}
)
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