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