Unverified Commit 9c99d792 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Fix prefetch only being applied once (#47797)

### What / why?

Currently there is a bug because the `subTreeData` can only be applied
once, however, we reuse the same response when a url was prefetched.
During the first render of the response we apply the cacheNodes and then
these should be reused for subsequent navigations. There's currently a
bug because `fillLazyItemsTillLeafWithHead` creates `LAZY_INITIALIZED`
cache nodes that don't copy the previous cache node `parallelRoutes` and
`subTreeData` value, causing the cache nodes below where the
`subTreeData` is applied to be deleted from the cache, even when they're
not affected by the navigation.

### How?

This PR adds copying of the cache node when it exists already, I've
added a marker for `wasPrefetched` to trigger that behavior but in
talking to @feedthejim about this it seems we can swap to this behavior
always when applying the server response, that needs to be discussed
further though, this is temporary implementation with the fix for routes
that were prefetched.

Fixes NEXT-402

<!-- 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(s) that you're making:

## For Contributors

### Improving Documentation or adding/fixing Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

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



## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->

---------
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 8e8eec3b
......@@ -7,7 +7,8 @@ import { ReadonlyReducerState } from './router-reducer-types'
export function applyFlightData(
state: ReadonlyReducerState,
cache: CacheNode,
flightDataPath: FlightDataPath
flightDataPath: FlightDataPath,
wasPrefetched?: boolean
): boolean {
// The one before last item is the router state tree patch
const [treePatch, subTreeData, head] = flightDataPath.slice(-3)
......@@ -20,7 +21,13 @@ export function applyFlightData(
if (flightDataPath.length === 3) {
cache.status = CacheStates.READY
cache.subTreeData = subTreeData
fillLazyItemsTillLeafWithHead(cache, state.cache, treePatch, head)
fillLazyItemsTillLeafWithHead(
cache,
state.cache,
treePatch,
head,
wasPrefetched
)
} else {
// Copy subTreeData for the root node of the cache.
cache.status = CacheStates.READY
......
......@@ -5,7 +5,8 @@ export function fillLazyItemsTillLeafWithHead(
newCache: CacheNode,
existingCache: CacheNode | undefined,
routerState: FlightRouterState,
head: React.ReactNode
head: React.ReactNode,
wasPrefetched?: boolean
): void {
const isLastSegment = Object.keys(routerState[1]).length === 0
if (isLastSegment) {
......@@ -26,19 +27,29 @@ export function fillLazyItemsTillLeafWithHead(
if (existingParallelRoutesCacheNode) {
let parallelRouteCacheNode = new Map(existingParallelRoutesCacheNode)
const existingCacheNode = parallelRouteCacheNode.get(cacheKey)
parallelRouteCacheNode.delete(cacheKey)
const newCacheNode: CacheNode = {
status: CacheStates.LAZY_INITIALIZED,
data: null,
subTreeData: null,
parallelRoutes: new Map(existingCacheNode?.parallelRoutes),
}
const newCacheNode: CacheNode =
wasPrefetched && existingCacheNode
? ({
status: existingCacheNode.status,
data: existingCacheNode.data,
subTreeData: existingCacheNode.subTreeData,
parallelRoutes: new Map(existingCacheNode.parallelRoutes),
} as CacheNode)
: {
status: CacheStates.LAZY_INITIALIZED,
data: null,
subTreeData: null,
parallelRoutes: new Map(existingCacheNode?.parallelRoutes),
}
// Overrides the cache key with the new cache node.
parallelRouteCacheNode.set(cacheKey, newCacheNode)
// Traverse deeper to apply the head / fill lazy items till the head.
fillLazyItemsTillLeafWithHead(
newCacheNode,
undefined,
wasPrefetched ? existingCacheNode : undefined,
parallelRouteState,
head
head,
wasPrefetched
)
newCache.parallelRoutes.set(key, parallelRouteCacheNode)
......@@ -64,7 +75,8 @@ export function fillLazyItemsTillLeafWithHead(
newCacheNode,
undefined,
parallelRouteState,
head
head,
wasPrefetched
)
}
}
......@@ -107,7 +107,7 @@ export function navigateReducer(
return handleExternalUrl(state, mutable, href, pendingPush)
}
const applied = applyFlightData(state, cache, flightDataPath)
const applied = applyFlightData(state, cache, flightDataPath, true)
const hardNavigate = shouldHardNavigate(
// TODO-APP: remove ''
......
import Link from 'next/link'
export default async function Page() {
return (
<>
<p id="static-page">Static Page</p>
<p>
<Link href="/" id="to-home">
To home
</Link>
</p>
</>
)
}
......@@ -75,6 +75,43 @@ createNextDescribe(
).toBe(1)
})
it('should not fetch again when a static page was prefetched when navigating to it twice', async () => {
const browser = await next.browser('/404')
let requests: string[] = []
browser.on('request', (req) => {
requests.push(new URL(req.url()).pathname)
})
await browser.eval('location.href = "/"')
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')
await browser
.elementByCss('#to-home')
// Go back to home page
.click()
// Wait for homepage to load
.waitForElementByCss('#to-static-page')
// Click on the link to the static page again
.click()
// Wait for the static page to load again
.waitForElementByCss('#static-page')
expect(
requests.filter((request) => request === '/static-page').length
).toBe(1)
})
it('should not prefetch for a bot user agent', async () => {
const browser = await next.browser('/404')
let requests: string[] = []
......
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