Unverified Commit 252d9cf4 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Navigation Signals in PPR (#60450)

### What

This adds support for navigation signals like `notFound()` and
`redirect(url)` when Partial Prerendering has been enabled.

### Why

Navigation API's like `notFound()` and `redirect(url)` throw errors in
order to interrupt the rendering of components. When a page both invokes
API's that cause the render to be marked as dynamic (like
`unstable_noStore()`) and also a navigation API, these errors may race
to the end. In the case where the navigation error does not beat out the
error emitted by dynamic API's will still trigger the detection warning
that's present to warn you about situations where you may have
accidentally caught the error.

### How

This resolves this issue by explicitly checking for navigation signals
(errors) thrown during the render, and not displaying the "caught
dynamic API" error and console warning.

Closes NEXT-2037
parent 300cf76c
...@@ -129,7 +129,7 @@ export function isRedirectError<U extends string>( ...@@ -129,7 +129,7 @@ export function isRedirectError<U extends string>(
export function getURLFromRedirectError<U extends string>( export function getURLFromRedirectError<U extends string>(
error: RedirectError<U> error: RedirectError<U>
): U ): U
export function getURLFromRedirectError(error: any): string | null { export function getURLFromRedirectError(error: unknown): string | null {
if (!isRedirectError(error)) return null if (!isRedirectError(error)) return null
// Slices off the beginning of the digest that contains the code and the // Slices off the beginning of the digest that contains the code and the
......
import { isDynamicServerError } from '../../client/components/hooks-server-context' import { isDynamicServerError } from '../../client/components/hooks-server-context'
import { isNotFoundError } from '../../client/components/not-found'
import { isRedirectError } from '../../client/components/redirect'
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr' import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { isNavigationSignalError } from './is-navigation-signal-error'
export const isDynamicUsageError = (err: unknown) => export const isDynamicUsageError = (err: unknown) =>
isDynamicServerError(err) || isDynamicServerError(err) ||
isBailoutToCSRError(err) || isBailoutToCSRError(err) ||
isNotFoundError(err) || isNavigationSignalError(err)
isRedirectError(err)
import { isNotFoundError } from '../../client/components/not-found'
import { isRedirectError } from '../../client/components/redirect'
/**
* Returns true if the error is a navigation signal error. These errors are
* thrown by user code to perform navigation operations and interrupt the React
* render.
*/
export const isNavigationSignalError = (err: unknown) =>
isNotFoundError(err) || isRedirectError(err)
import type { OutgoingHttpHeaders } from 'node:http'
import type { ExportRouteResult, FileWriter } from '../types' import type { ExportRouteResult, FileWriter } from '../types'
import type { RenderOpts } from '../../server/app-render/types' import type { RenderOpts } from '../../server/app-render/types'
import type { NextParsedUrlQuery } from '../../server/request-meta' import type { NextParsedUrlQuery } from '../../server/request-meta'
...@@ -106,7 +107,13 @@ export async function exportAppPage( ...@@ -106,7 +107,13 @@ export async function exportAppPage(
) )
} }
const headers = { ...metadata.headers } const headers: OutgoingHttpHeaders = { ...metadata.headers }
// When PPR is enabled, we should grab the headers from the mocked response
// and add it to the headers.
if (renderOpts.experimental.ppr) {
Object.assign(headers, res.getHeaders())
}
if (fetchTags) { if (fetchTags) {
headers[NEXT_CACHE_TAGS_HEADER] = fetchTags headers[NEXT_CACHE_TAGS_HEADER] = fetchTags
...@@ -122,7 +129,10 @@ export async function exportAppPage( ...@@ -122,7 +129,10 @@ export async function exportAppPage(
// Writing the request metadata to a file. // Writing the request metadata to a file.
const meta: RouteMetadata = { const meta: RouteMetadata = {
status: undefined, // When PPR is enabled, we don't always send 200 for routes that have been
// pregenerated, so we should grab the status code from the mocked
// response.
status: renderOpts.experimental.ppr ? res.statusCode : undefined,
headers, headers,
postponed, postponed,
} }
......
...@@ -86,6 +86,7 @@ import { useFlightResponse } from './use-flight-response' ...@@ -86,6 +86,7 @@ import { useFlightResponse } from './use-flight-response'
import { isStaticGenBailoutError } from '../../client/components/static-generation-bailout' import { isStaticGenBailoutError } from '../../client/components/static-generation-bailout'
import { isInterceptionRouteAppPath } from '../future/helpers/interception-routes' import { isInterceptionRouteAppPath } from '../future/helpers/interception-routes'
import { getStackWithoutErrorMessage } from '../../lib/format-server-error' import { getStackWithoutErrorMessage } from '../../lib/format-server-error'
import { isNavigationSignalError } from '../../export/helpers/is-navigation-signal-error'
export type GetDynamicParamFromSegment = ( export type GetDynamicParamFromSegment = (
// [slug] / [[slug]] / [...slug] // [slug] / [[slug]] / [...slug]
...@@ -725,14 +726,18 @@ async function renderToHTMLOrFlightImpl( ...@@ -725,14 +726,18 @@ async function renderToHTMLOrFlightImpl(
req.headers[NEXT_ROUTER_PREFETCH_HEADER.toLowerCase()] !== undefined req.headers[NEXT_ROUTER_PREFETCH_HEADER.toLowerCase()] !== undefined
/** /**
* Router state provided from the client-side router. Used to handle rendering from the common layout down. * Router state provided from the client-side router. Used to handle rendering
* from the common layout down. This value will be undefined if the request
* is not a client-side navigation request or if the request is a prefetch
* request (except when it's a prefetch request for an interception route
* which is always dynamic).
*/ */
const shouldProvideFlightRouterState = const shouldProvideFlightRouterState =
isRSCRequest && isRSCRequest &&
(!isPrefetchRSCRequest || (!isPrefetchRSCRequest ||
!renderOpts.experimental.ppr || !renderOpts.experimental.ppr ||
// interception routes currently depend on the flight router state to extract dynamic params // Interception routes currently depend on the flight router state to
// extract dynamic params.
isInterceptionRouteAppPath(pagePath)) isInterceptionRouteAppPath(pagePath))
let providedFlightRouterState = shouldProvideFlightRouterState let providedFlightRouterState = shouldProvideFlightRouterState
...@@ -1234,14 +1239,15 @@ async function renderToHTMLOrFlightImpl( ...@@ -1234,14 +1239,15 @@ async function renderToHTMLOrFlightImpl(
digestErrorsMap.size > 0 ? digestErrorsMap.values().next().value : null digestErrorsMap.size > 0 ? digestErrorsMap.values().next().value : null
// If PPR is enabled and the postpone was triggered but lacks the postponed // If PPR is enabled and the postpone was triggered but lacks the postponed
// state information then we should error out unless the client side rendering // state information then we should error out unless the error was a
// bailout error was also emitted which indicates that part of the stream was // navigation signal error or a client-side rendering bailout error.
// not rendered.
if ( if (
staticGenerationStore.prerenderState && staticGenerationStore.prerenderState &&
staticGenerationStore.prerenderState.hasDynamic && staticGenerationStore.prerenderState.hasDynamic &&
!metadata.postponed && !metadata.postponed &&
(!response.err || !isBailoutToCSRError(response.err)) (!response.err ||
(!isBailoutToCSRError(response.err) &&
!isNavigationSignalError(response.err)))
) { ) {
// a call to postpone was made but was caught and not detected by Next.js. We should fail the build immediately // a call to postpone was made but was caught and not detected by Next.js. We should fail the build immediately
// as we won't be able to generate the static part // as we won't be able to generate the static part
......
...@@ -2801,7 +2801,10 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -2801,7 +2801,10 @@ export default abstract class Server<ServerOptions extends Options = Options> {
) )
} }
if (cachedData.status) { // If the request is a data request, then we shouldn't set the status code
// from the response because it should always be 200. This should be gated
// behind the experimental PPR flag.
if (cachedData.status && (!isDataReq || !opts.experimental.ppr)) {
res.statusCode = cachedData.status res.statusCode = cachedData.status
} }
......
...@@ -71,69 +71,71 @@ createNextDescribe( ...@@ -71,69 +71,71 @@ createNextDescribe(
}) })
describe('useParams identity between renders', () => { describe('useParams identity between renders', () => {
async function runTests(page: string, waitForNEffects: number) { it.each([
const browser = await next.browser(page) {
router: 'app',
// Expect to see the params changed message at least twice. pathname: '/search-params/foo',
let lastLogIndex = await retry(async () => { // App Router doesn't re-render on initial load (the params are baked
const logs: Array<{ message: string }> = await browser.log() // server side). In development, effects will render twice.
waitForNEffects: isNextDev ? 2 : 1,
expect( },
logs.filter(({ message }) => message === 'params changed') {
).toHaveLength(waitForNEffects) router: 'pages',
pathname: '/search-params-pages/foo',
return logs.length // Pages Router re-renders on initial load and after hydration, the
}) // params when initially loaded are null.
waitForNEffects: 2,
await browser.elementById('rerender-button').click() },
await browser.elementById('rerender-button').click() ])(
await browser.elementById('rerender-button').click() 'should be stable in $router',
async ({ pathname, waitForNEffects }) => {
await retry(async () => { const browser = await next.browser(pathname)
const rerender = await browser.elementById('rerender-button').text()
// Expect to see the params changed message at least twice.
expect(rerender).toBe('Re-Render 3') let lastLogIndex = await retry(async () => {
}) const logs: Array<{ message: string }> = await browser.log()
let logs: Array<{ message: string }> = await browser.log() expect(
expect(logs.slice(lastLogIndex)).not.toContainEqual( logs.filter(({ message }) => message === 'params changed')
expect.objectContaining({ ).toHaveLength(waitForNEffects)
message: 'params changed',
return logs.length
}) })
)
lastLogIndex = logs.length await browser.elementById('rerender-button').click()
await browser.elementById('rerender-button').click()
await browser.elementById('rerender-button').click()
await browser.elementById('change-params-button').click() await retry(async () => {
const rerender = await browser
.elementById('rerender-button')
.text()
await retry(async () => { expect(rerender).toBe('Re-Render 3')
logs = await browser.log() })
expect(logs.slice(lastLogIndex)).toContainEqual( let logs: Array<{ message: string }> = await browser.log()
expect(logs.slice(lastLogIndex)).not.toContainEqual(
expect.objectContaining({ expect.objectContaining({
message: 'params changed', message: 'params changed',
}) })
) )
})
}
it('should be stable in app', async () => { lastLogIndex = logs.length
await runTests(
'/search-params/foo',
// App Router doesn't re-render on initial load (the params are baked
// server side). In development, effects will render twice.
isNextDev ? 2 : 1
)
})
it('should be stable in pages', async () => { await browser.elementById('change-params-button').click()
await runTests(
'/search-params-pages/foo', await retry(async () => {
// Pages Router re-renders on initial load and after hydration, the logs = await browser.log()
// params when initially loaded are null.
2 expect(logs.slice(lastLogIndex)).toContainEqual(
) expect.objectContaining({
}) message: 'params changed',
})
)
})
}
)
}) })
}) })
......
import { Suspense } from 'react'
import { notFound } from 'next/navigation'
import { Dynamic } from '../../../../components/dynamic'
const NotFound = () => {
notFound()
}
export default function NotFoundPage() {
return (
<>
<Suspense
fallback={<Dynamic pathname="/navigation/not-found/dynamic" fallback />}
>
<Dynamic pathname="/navigation/not-found/dynamic" />
</Suspense>
<NotFound />
</>
)
}
import { notFound } from 'next/navigation'
export default function NotFoundPage() {
notFound()
}
import { Suspense } from 'react'
import { redirect } from 'next/navigation'
import { Dynamic } from '../../../../components/dynamic'
const Redirect = () => {
redirect('/navigation/redirect/location')
}
export default function RedirectPage() {
return (
<>
<Suspense
fallback={<Dynamic pathname="/navigation/redirect/dynamic" fallback />}
>
<Dynamic pathname="/navigation/redirect/dynamic" />
</Suspense>
<Redirect />
</>
)
}
export default function RedirectTargetPage() {
return (
<div data-pathname="/navigation/redirect/location">Redirect Target</div>
)
}
import { redirect } from 'next/navigation'
export default function RedirectPage() {
redirect('/navigation/redirect/location')
}
export default function NotFoundPage() {
return <div id="not-found-page">Not Found</div>
}
...@@ -39,6 +39,10 @@ const links = [ ...@@ -39,6 +39,10 @@ const links = [
{ href: '/edge/no-suspense/a', tag: 'edge, no suspense, pre-generated' }, { href: '/edge/no-suspense/a', tag: 'edge, no suspense, pre-generated' },
{ href: '/edge/no-suspense/b', tag: 'edge, no suspense, on-demand' }, { href: '/edge/no-suspense/b', tag: 'edge, no suspense, on-demand' },
{ href: '/edge/no-suspense/c', tag: 'edge, no suspense, on-demand' }, { href: '/edge/no-suspense/c', tag: 'edge, no suspense, on-demand' },
{ href: '/navigation/not-found', tag: 'not-found' },
{ href: '/navigation/not-found/no-store', tag: 'not-found, dynamic' },
{ href: '/navigation/redirect', tag: 'redirect' },
{ href: '/navigation/redirect/no-store', tag: 'redirect, dynamic' },
{ href: '/pages', tag: 'pages' }, { href: '/pages', tag: 'pages' },
] ]
......
...@@ -256,6 +256,72 @@ createNextDescribe( ...@@ -256,6 +256,72 @@ createNextDescribe(
) )
}) })
describe('Navigation Signals', () => {
const delay = 500
describe.each([
{
signal: 'notFound()' as const,
pathnames: ['/navigation/not-found', '/navigation/not-found/dynamic'],
},
{
signal: 'redirect()' as const,
pathnames: ['/navigation/redirect', '/navigation/redirect/dynamic'],
},
])('$signal', ({ signal, pathnames }) => {
describe.each(pathnames)('for %s', (pathname) => {
it('should have correct headers', async () => {
const res = await next.fetch(pathname, {
redirect: 'manual',
})
expect(res.status).toEqual(signal === 'redirect()' ? 307 : 404)
expect(res.headers.get('content-type')).toEqual(
'text/html; charset=utf-8'
)
if (!isNextDev) {
expect(res.headers.get('cache-control')).toEqual(
's-maxage=31536000, stale-while-revalidate'
)
}
if (signal === 'redirect()') {
const location = res.headers.get('location')
expect(typeof location).toEqual('string')
// The URL returned in `Location` is absolute, so we need to parse it
// to get the pathname.
const url = new URL(location)
expect(url.pathname).toEqual('/navigation/redirect/location')
}
})
if (pathname.endsWith('/dynamic')) {
it('should cache the static part', async () => {
const start = Date.now()
const res = await next.fetch(pathname, {
redirect: 'manual',
headers: {
'X-Delay': delay.toString(),
},
})
const result = await measure(res.body)
expect(result.streamFirstChunk - start).toBeLessThan(delay)
if (isNextDev) {
// This is because the signal should throw and interrupt the
// delay timer.
expect(result.streamEnd - start).toBeGreaterThanOrEqual(delay)
} else {
expect(result.streamEnd - start).toBeLessThan(delay)
}
})
}
})
})
})
if (!isNextDev) { if (!isNextDev) {
describe('Prefetch RSC Response', () => { describe('Prefetch RSC Response', () => {
describe.each(pages)('for $pathname', ({ pathname, revalidate }) => { describe.each(pages)('for $pathname', ({ pathname, revalidate }) => {
......
...@@ -44,8 +44,7 @@ ...@@ -44,8 +44,7 @@
"app dir - navigation redirect status code should respond with 308 status code if permanent flag is set", "app dir - navigation redirect status code should respond with 308 status code if permanent flag is set",
"app dir - navigation redirect status code should respond with 307 status code in client component", "app dir - navigation redirect status code should respond with 307 status code in client component",
"app dir - navigation redirect status code should respond with 307 status code in server component", "app dir - navigation redirect status code should respond with 307 status code in server component",
"app dir - navigation bots should block rendering for bots and return 404 status", "app dir - navigation bots should block rendering for bots and return 404 status"
"app dir - navigation navigation between pages and app should not continously initiate a mpa navigation to the same URL when router state changes"
] ]
}, },
"test/e2e/app-dir/app-static/app-static-custom-handler.test.ts": { "test/e2e/app-dir/app-static/app-static-custom-handler.test.ts": {
......
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