Unverified Commit 016ba387 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

Only opt into navigation PPR flow if prefetched route was PPRed (#68815)

### What & Why
In the first iteration of `experimental.ppr`, we only supported it
either being fully on or off. When enabled, the client router would
check if the prefetch was fully static (rendered from the root) which
was guarded by the `flightDataPath.length === 3` check. This codepath
was only meant to be triggered in the PPR case.

When we introduced "incremental" PPR, we still opted into the forked PPR
router handling because the `__NEXT_PPR` env was still set. However, for
a page that _wasn't_ PPRed, we have a problem: a "full" prefetch
(whether it be from `prefetch={true}` or from the fact that it was a
static page and we were able to prerender it at build time) would opt
into the all of the PPR router handling.

This meant that the router would see the prefetch, assume it was a
static shell associated with PPR, and eagerly kick off a dynamic request
to fill in the data. This resulted in duplicate calls for the dynamic
data, and in some cases, a delay in navigating while waiting for the
second dynamic request even though the router already had all the data
it needed.

This ensures we don't opt into the PPR navigation logic unless we know
the prefetch we're working with postponed. If it did, then we need to
kick off a dynamic request. If it didn't, it's a no-op, and the existing
router logic can be applied.

In the next PR, I remove the unforking of the two reducer functions, as
there is no reason for them to be different since the only change in
behavior is this one line that calls into the `ppr-navigations`
behavior.

### How
This leverages a header that we already have (`x-nextjs-postponed`) to
signal to the router that it should enter the PPR cache node update
logic. On initial render, we use the `renderOpts.postponed` flag since
we do not have access to headers.

Closes NDX-178
parent 132c5cdb
......@@ -178,6 +178,7 @@ const pendingActionQueue: Promise<AppRouterActionQueue> = new Promise(
initialParallelRoutes: new Map(),
location: window.location,
couldBeIntercepted: initialRSCPayload.i,
postponed: initialRSCPayload.s,
})
)
)
......
......@@ -42,6 +42,7 @@ describe('createInitialRouterState', () => {
initialParallelRoutes,
location: new URL('/linking', 'https://localhost') as any,
couldBeIntercepted: false,
postponed: false,
})
const state2 = createInitialRouterState({
......@@ -52,6 +53,8 @@ describe('createInitialRouterState', () => {
initialCanonicalUrl,
initialParallelRoutes,
location: new URL('/linking', 'https://localhost') as any,
couldBeIntercepted: false,
postponed: false,
})
const expectedCache: CacheNode = {
......
......@@ -14,7 +14,8 @@ export interface InitialRouterStateParameters {
initialParallelRoutes: CacheNode['parallelRoutes']
initialFlightData: FlightDataPath[]
location: Location | null
couldBeIntercepted?: boolean
couldBeIntercepted: boolean
postponed: boolean
}
export function createInitialRouterState({
......@@ -24,6 +25,7 @@ export function createInitialRouterState({
initialParallelRoutes,
location,
couldBeIntercepted,
postponed,
}: InitialRouterStateParameters) {
// The initialFlightData is an array of FlightDataPath arrays.
// For the root render, there'll only be a top-level FlightDataPath array.
......@@ -107,6 +109,7 @@ export function createInitialRouterState({
couldBeIntercepted: !!couldBeIntercepted,
// TODO: the server should probably send a value for this. Default to false for now.
isPrerender: false,
postponed,
},
tree: initialState.tree,
prefetchCache: initialState.prefetchCache,
......
......@@ -25,6 +25,7 @@ import {
RSC_CONTENT_TYPE_HEADER,
NEXT_HMR_REFRESH_HEADER,
NEXT_IS_PRERENDER_HEADER,
NEXT_DID_POSTPONE_HEADER,
} from '../app-router-headers'
import { callServer } from '../../app-call-server'
import { PrefetchKind } from './router-reducer-types'
......@@ -61,6 +62,7 @@ function doMpaNavigation(url: string): FetchServerResponseResult {
canonicalUrl: undefined,
couldBeIntercepted: false,
isPrerender: false,
postponed: false,
}
}
......@@ -164,6 +166,7 @@ export async function fetchServerResponse(
const contentType = res.headers.get('content-type') || ''
const interception = !!res.headers.get('vary')?.includes(NEXT_URL)
const isPrerender = !!res.headers.get(NEXT_IS_PRERENDER_HEADER)
const postponed = !!res.headers.get(NEXT_DID_POSTPONE_HEADER)
let isFlightResponse = contentType === RSC_CONTENT_TYPE_HEADER
if (process.env.NODE_ENV === 'production') {
......@@ -210,6 +213,7 @@ export async function fetchServerResponse(
canonicalUrl: canonicalUrl,
couldBeIntercepted: interception,
isPrerender: isPrerender,
postponed,
}
} catch (err) {
console.error(
......@@ -224,6 +228,7 @@ export async function fetchServerResponse(
canonicalUrl: undefined,
couldBeIntercepted: false,
isPrerender: false,
postponed: false,
}
}
}
......@@ -353,7 +353,7 @@ function navigateReducer_PPR(
prefetchQueue.bump(data)
return data.then(
({ flightData, canonicalUrl: canonicalUrlOverride }) => {
({ flightData, canonicalUrl: canonicalUrlOverride, postponed }) => {
let isFirstRead = false
// we only want to mark this once
if (!prefetchValues.lastUsedTime) {
......@@ -428,15 +428,16 @@ function navigateReducer_PPR(
}
if (
// This is just a paranoid check. When PPR is enabled, the server
// will always send back a static response that's rendered from
// This is just a paranoid check. When a route is PPRed, the server
// will send back a static response that's rendered from
// the root. If for some reason it doesn't, we fall back to the
// non-PPR implementation.
// TODO: We should get rid of the else branch and do all navigations
// via updateCacheNodeOnNavigation. The current structure is just
// an incremental step.
flightDataPath.length === 3 &&
!prefetchValues.aliased
!prefetchValues.aliased &&
postponed
) {
const prefetchedTree: FlightRouterState = flightDataPath[0]
const seedData = flightDataPath[1]
......
......@@ -547,10 +547,11 @@ async function getRSCPayload(
b: ctx.renderOpts.buildId,
p: ctx.assetPrefix,
c: url.pathname + url.search,
i: couldBeIntercepted,
i: !!couldBeIntercepted,
f: [[initialTree, seedData, initialHead]],
m: missingSlots,
G: GlobalError,
s: typeof ctx.renderOpts.postponed === 'string',
} satisfies InitialRSCPayload & { P: React.ReactNode }
}
......@@ -662,6 +663,7 @@ function App<T>({
initialParallelRoutes: null!,
location: null,
couldBeIntercepted: response.i,
postponed: response.s,
})
const actionQueue = createMutableActionQueue(initialState)
......@@ -687,7 +689,7 @@ function App<T>({
)
}
// @TODO our error stream should be probably just use the same root component. But it was previosuly
// @TODO our error stream should be probably just use the same root component. But it was previously
// different I don't want to figure out if that is meaningful at this time so just keeping the behavior
// consistent for now.
function AppWithoutContext<T>({
......@@ -719,6 +721,7 @@ function AppWithoutContext<T>({
initialParallelRoutes: null!,
location: null,
couldBeIntercepted: response.i,
postponed: response.s,
})
const actionQueue = createMutableActionQueue(initialState)
......
......@@ -216,6 +216,8 @@ export type InitialRSCPayload = {
m: Set<string> | undefined
/** GlobalError */
G: React.ComponentType<any>
/** postponed */
s: boolean
}
// Response from `createFromFetch` for normal rendering
......@@ -241,6 +243,7 @@ export type FetchServerResponseResult = {
canonicalUrl: URL | undefined
couldBeIntercepted: boolean
isPrerender: boolean
postponed: boolean
}
export type RSCPayload =
......
......@@ -3140,7 +3140,7 @@ export default abstract class Server<
}
// Mark that the request did postpone if this is a data request.
if (cachedData.postponed && isRSCRequest) {
if (typeof cachedData.postponed === 'string' && isRSCRequest) {
res.setHeader(NEXT_DID_POSTPONE_HEADER, '1')
}
......
export default function Page() {
return <div id="static-page">Fully static page!</div>
}
......@@ -14,6 +14,7 @@ export default function Page() {
<Link href="/">Root</Link>
<Link href="/enabled">Enabled</Link>
<Link href="/disabled">Disabled</Link>
<Link href="/static">Static</Link>
</li>
<Suspense fallback={<div id="fallback">Loading...</div>}>
<Dynamic />
......
import { nextTestSetup, isNextDev } from 'e2e-utils'
import type { Route as PlaywrightRoute, Page } from 'playwright'
type Route = {
route: string
......@@ -149,6 +150,34 @@ describe('ppr-incremental', () => {
})
}
)
it('should not trigger a dynamic request for static pages', async () => {
let rscRequests = []
const browser = await next.browser('/', {
beforePageLoad(page: Page) {
page.route('**/static*', async (route: PlaywrightRoute) => {
const request = route.request()
const headers = await request.allHeaders()
const url = new URL(request.url())
if (headers['rsc'] === '1') {
rscRequests.push(url.pathname)
await route.continue()
}
})
},
})
await browser.waitForIdleNetwork()
// we should see an RSC request for the initial prefetch to the static page
expect(rscRequests).toEqual(expect.arrayContaining(['/static']))
rscRequests = []
await browser.elementByCss('[href="/static"]').click()
await browser.waitForElementByCss('#static-page')
expect(rscRequests.length).toBe(0)
})
})
describe('ppr enabled', () => {
......
import { unstable_noStore } from 'next/cache'
import Link from 'next/link'
import React from 'react'
import React, { Suspense } from 'react'
export default async function Page({ params }) {
return (
......@@ -10,6 +11,14 @@ export default async function Page({ params }) {
<Link href={`/catch-all/${i}`}>Go to /catch-all/{i}</Link>
</div>
))}
<Suspense fallback={<div id="fallback">Loading...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
function Dynamic() {
unstable_noStore()
return <div id="dynamic">Dynamic content</div>
}
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