Unverified Commit b5d911c9 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

[ppr] Don't mark RSC requests as /_next/data requests (#66249)

Old logic from the pages router was previously being hit during
development. This was more apparent when PPR was enabled as it was
mixing dynamic + static rendering in development which propagated to
errors. This change ensures that requests that are made with `RSC: 1`
are not marked as `/_next/data` URL's, and don't use the same logic
paths.

Previously it was a bit confusing because we used the variable
`isDataReq` in a few places that made it hard to tell what it was
referring to. In this case, the `isDataReq` is actually only used by the
pages router. This renames the `isDataReq` to `isNextDataRequest` to
make it clearer, as well as refactors to ensure that it's not used in
the paths for app routes.

Also to better represent the rendering modes the `supportsDynamicHTML`
variable was renamed to `supportsDynamicResponse`.

Fixes #66241
parent 1b36d761
...@@ -30,7 +30,12 @@ module.exports = { ...@@ -30,7 +30,12 @@ module.exports = {
return [ return [
`prettier --with-node-modules --ignore-path .prettierignore --write ${escapedFileNames}`, `prettier --with-node-modules --ignore-path .prettierignore --write ${escapedFileNames}`,
`eslint --no-ignore --max-warnings=0 --fix ${escape(eslintFileNames.filter((filename) => filename !== null)).join(' ')}`, `eslint --no-ignore --max-warnings=0 --fix ${eslintFileNames
.filter((filename) => filename !== null)
.map((filename) => {
return `"${filename}"`
})
.join(' ')}`,
`git add ${escapedFileNames}`, `git add ${escapedFileNames}`,
] ]
}, },
......
...@@ -1389,7 +1389,7 @@ export async function buildAppStaticPaths({ ...@@ -1389,7 +1389,7 @@ export async function buildAppStaticPaths({
renderOpts: { renderOpts: {
originalPathname: page, originalPathname: page,
incrementalCache, incrementalCache,
supportsDynamicHTML: true, supportsDynamicResponse: true,
isRevalidate: false, isRevalidate: false,
experimental: { experimental: {
after: false, after: false,
......
...@@ -93,7 +93,7 @@ export function getRender({ ...@@ -93,7 +93,7 @@ export function getRender({
extendRenderOpts: { extendRenderOpts: {
buildId, buildId,
runtime: SERVER_RUNTIME.experimentalEdge, runtime: SERVER_RUNTIME.experimentalEdge,
supportsDynamicHTML: true, supportsDynamicResponse: true,
disableOptimizedLoading: true, disableOptimizedLoading: true,
serverActionsManifest, serverActionsManifest,
serverActions, serverActions,
......
...@@ -398,7 +398,7 @@ export async function exportAppImpl( ...@@ -398,7 +398,7 @@ export async function exportAppImpl(
domainLocales: i18n?.domains, domainLocales: i18n?.domains,
disableOptimizedLoading: nextConfig.experimental.disableOptimizedLoading, disableOptimizedLoading: nextConfig.experimental.disableOptimizedLoading,
// Exported pages do not currently support dynamic HTML. // Exported pages do not currently support dynamic HTML.
supportsDynamicHTML: false, supportsDynamicResponse: false,
crossOrigin: nextConfig.crossOrigin, crossOrigin: nextConfig.crossOrigin,
optimizeCss: nextConfig.experimental.optimizeCss, optimizeCss: nextConfig.experimental.optimizeCss,
nextConfigOutput: nextConfig.output, nextConfigOutput: nextConfig.output,
......
...@@ -75,7 +75,7 @@ export async function exportAppRoute( ...@@ -75,7 +75,7 @@ export async function exportAppRoute(
experimental: experimental, experimental: experimental,
originalPathname: page, originalPathname: page,
nextExport: true, nextExport: true,
supportsDynamicHTML: false, supportsDynamicResponse: false,
incrementalCache, incrementalCache,
waitUntil: undefined, waitUntil: undefined,
onClose: undefined, onClose: undefined,
......
...@@ -269,7 +269,7 @@ async function exportPageImpl( ...@@ -269,7 +269,7 @@ async function exportPageImpl(
disableOptimizedLoading, disableOptimizedLoading,
fontManifest: optimizeFonts ? requireFontManifest(distDir) : undefined, fontManifest: optimizeFonts ? requireFontManifest(distDir) : undefined,
locale, locale,
supportsDynamicHTML: false, supportsDynamicResponse: false,
originalPathname: page, originalPathname: page,
experimental: { experimental: {
...input.renderOpts.experimental, ...input.renderOpts.experimental,
......
...@@ -643,7 +643,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -643,7 +643,7 @@ async function renderToHTMLOrFlightImpl(
ComponentMod, ComponentMod,
dev, dev,
nextFontManifest, nextFontManifest,
supportsDynamicHTML, supportsDynamicResponse,
serverActions, serverActions,
appDirDevErrorLogger, appDirDevErrorLogger,
assetPrefix = '', assetPrefix = '',
...@@ -781,7 +781,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -781,7 +781,7 @@ async function renderToHTMLOrFlightImpl(
* These rules help ensure that other existing features like request caching, * These rules help ensure that other existing features like request caching,
* coalescing, and ISR continue working as intended. * coalescing, and ISR continue working as intended.
*/ */
const generateStaticHTML = supportsDynamicHTML !== true const generateStaticHTML = supportsDynamicResponse !== true
// Pull out the hooks/references from the component. // Pull out the hooks/references from the component.
const { tree: loaderTree, taintObjectReference } = ComponentMod const { tree: loaderTree, taintObjectReference } = ComponentMod
......
...@@ -129,7 +129,7 @@ export interface RenderOptsPartial { ...@@ -129,7 +129,7 @@ export interface RenderOptsPartial {
basePath: string basePath: string
trailingSlash: boolean trailingSlash: boolean
clientReferenceManifest?: DeepReadonly<ClientReferenceManifest> clientReferenceManifest?: DeepReadonly<ClientReferenceManifest>
supportsDynamicHTML: boolean supportsDynamicResponse: boolean
runtime?: ServerRuntime runtime?: ServerRuntime
serverComponents?: boolean serverComponents?: boolean
enableTainting?: boolean enableTainting?: boolean
......
...@@ -41,7 +41,7 @@ export type StaticGenerationContext = { ...@@ -41,7 +41,7 @@ export type StaticGenerationContext = {
// mirrored. // mirrored.
RenderOptsPartial, RenderOptsPartial,
| 'originalPathname' | 'originalPathname'
| 'supportsDynamicHTML' | 'supportsDynamicResponse'
| 'isRevalidate' | 'isRevalidate'
| 'nextExport' | 'nextExport'
| 'isDraftMode' | 'isDraftMode'
...@@ -77,7 +77,7 @@ export const StaticGenerationAsyncStorageWrapper: AsyncStorageWrapper< ...@@ -77,7 +77,7 @@ export const StaticGenerationAsyncStorageWrapper: AsyncStorageWrapper<
* coalescing, and ISR continue working as intended. * coalescing, and ISR continue working as intended.
*/ */
const isStaticGeneration = const isStaticGeneration =
!renderOpts.supportsDynamicHTML && !renderOpts.supportsDynamicResponse &&
!renderOpts.isDraftMode && !renderOpts.isDraftMode &&
!renderOpts.isServerAction !renderOpts.isServerAction
......
This diff is collapsed.
...@@ -1856,7 +1856,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -1856,7 +1856,7 @@ export default class NextNodeServer extends BaseServer<
} }
// For edge to "fetch" we must always provide an absolute URL // For edge to "fetch" we must always provide an absolute URL
const isDataReq = !!query.__nextDataReq const isNextDataRequest = !!query.__nextDataReq
const initialUrl = new URL( const initialUrl = new URL(
getRequestMeta(params.req, 'initURL') || '/', getRequestMeta(params.req, 'initURL') || '/',
'http://n' 'http://n'
...@@ -1867,7 +1867,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -1867,7 +1867,7 @@ export default class NextNodeServer extends BaseServer<
...params.params, ...params.params,
}).toString() }).toString()
if (isDataReq) { if (isNextDataRequest) {
params.req.headers['x-nextjs-data'] = '1' params.req.headers['x-nextjs-data'] = '1'
} }
initialUrl.search = queryString initialUrl.search = queryString
......
...@@ -246,7 +246,7 @@ export type RenderOptsPartial = { ...@@ -246,7 +246,7 @@ export type RenderOptsPartial = {
ampValidator?: (html: string, pathname: string) => Promise<void> ampValidator?: (html: string, pathname: string) => Promise<void>
ampSkipValidation?: boolean ampSkipValidation?: boolean
ampOptimizerConfig?: { [key: string]: any } ampOptimizerConfig?: { [key: string]: any }
isDataReq?: boolean isNextDataRequest?: boolean
params?: ParsedUrlQuery params?: ParsedUrlQuery
previewProps: __ApiPreviewProps | undefined previewProps: __ApiPreviewProps | undefined
basePath: string basePath: string
...@@ -268,7 +268,7 @@ export type RenderOptsPartial = { ...@@ -268,7 +268,7 @@ export type RenderOptsPartial = {
defaultLocale?: string defaultLocale?: string
domainLocales?: DomainLocale[] domainLocales?: DomainLocale[]
disableOptimizedLoading?: boolean disableOptimizedLoading?: boolean
supportsDynamicHTML: boolean supportsDynamicResponse: boolean
isBot?: boolean isBot?: boolean
runtime?: ServerRuntime runtime?: ServerRuntime
serverComponents?: boolean serverComponents?: boolean
...@@ -449,7 +449,7 @@ export async function renderToHTMLImpl( ...@@ -449,7 +449,7 @@ export async function renderToHTMLImpl(
getStaticProps, getStaticProps,
getStaticPaths, getStaticPaths,
getServerSideProps, getServerSideProps,
isDataReq, isNextDataRequest,
params, params,
previewProps, previewProps,
basePath, basePath,
...@@ -1170,7 +1170,7 @@ export async function renderToHTMLImpl( ...@@ -1170,7 +1170,7 @@ export async function renderToHTMLImpl(
// Avoid rendering page un-necessarily for getServerSideProps data request // Avoid rendering page un-necessarily for getServerSideProps data request
// and getServerSideProps/getStaticProps redirects // and getServerSideProps/getStaticProps redirects
if ((isDataReq && !isSSG) || metadata.isRedirect) { if ((isNextDataRequest && !isSSG) || metadata.isRedirect) {
return new RenderResult(JSON.stringify(props), { return new RenderResult(JSON.stringify(props), {
metadata, metadata,
}) })
......
...@@ -189,6 +189,11 @@ type NextQueryMetadata = { ...@@ -189,6 +189,11 @@ type NextQueryMetadata = {
__nextSsgPath?: string __nextSsgPath?: string
_nextBubbleNoFallback?: '1' _nextBubbleNoFallback?: '1'
/**
* When set to `1`, the request is for the `/_next/data` route using the pages
* router.
*/
__nextDataReq?: '1' __nextDataReq?: '1'
__nextCustomErrorRender?: '1' __nextCustomErrorRender?: '1'
[NEXT_RSC_UNION_QUERY]?: string [NEXT_RSC_UNION_QUERY]?: string
......
...@@ -125,9 +125,9 @@ export async function adapter( ...@@ -125,9 +125,9 @@ export async function adapter(
const buildId = requestUrl.buildId const buildId = requestUrl.buildId
requestUrl.buildId = '' requestUrl.buildId = ''
const isDataReq = params.request.headers['x-nextjs-data'] const isNextDataRequest = params.request.headers['x-nextjs-data']
if (isDataReq && requestUrl.pathname === '/index') { if (isNextDataRequest && requestUrl.pathname === '/index') {
requestUrl.pathname = '/' requestUrl.pathname = '/'
} }
...@@ -169,7 +169,7 @@ export async function adapter( ...@@ -169,7 +169,7 @@ export async function adapter(
* need to know about this property neither use it. We add it for testing * need to know about this property neither use it. We add it for testing
* purposes. * purposes.
*/ */
if (isDataReq) { if (isNextDataRequest) {
Object.defineProperty(request, '__isData', { Object.defineProperty(request, '__isData', {
enumerable: false, enumerable: false,
value: true, value: true,
...@@ -323,7 +323,7 @@ export async function adapter( ...@@ -323,7 +323,7 @@ export async function adapter(
) )
if ( if (
isDataReq && isNextDataRequest &&
// if the rewrite is external and external rewrite // if the rewrite is external and external rewrite
// resolving config is enabled don't add this header // resolving config is enabled don't add this header
// so the upstream app can set it instead // so the upstream app can set it instead
...@@ -367,7 +367,7 @@ export async function adapter( ...@@ -367,7 +367,7 @@ export async function adapter(
* it may end up with CORS error. Instead we map to an internal header so * it may end up with CORS error. Instead we map to an internal header so
* the client knows the destination. * the client knows the destination.
*/ */
if (isDataReq) { if (isNextDataRequest) {
response.headers.delete('Location') response.headers.delete('Location')
response.headers.set( response.headers.set(
'x-nextjs-redirect', 'x-nextjs-redirect',
......
...@@ -115,7 +115,7 @@ export class EdgeRouteModuleWrapper { ...@@ -115,7 +115,7 @@ export class EdgeRouteModuleWrapper {
notFoundRoutes: [], notFoundRoutes: [],
}, },
renderOpts: { renderOpts: {
supportsDynamicHTML: true, supportsDynamicResponse: true,
waitUntil, waitUntil,
onClose: closeController onClose: closeController
? closeController.onClose.bind(closeController) ? closeController.onClose.bind(closeController)
......
import { TestPage } from '../../../components/page'
export default function Page({ params: { locale } }) {
return <TestPage pathname={`/${locale}/about`} />
}
import { locales } from '../../components/page'
export async function generateStaticParams() {
return locales.map((locale) => ({ locale }))
}
export default function Layout({ children, params: { locale } }) {
return (
<html lang={locale}>
<body>{children}</body>
</html>
)
}
import { TestPage } from '../../components/page'
export default function Page({ params: { locale } }) {
return <TestPage pathname={`/${locale}`} />
}
export default ({ children }) => {
return children
}
import { redirect } from 'next/navigation'
import { locales } from '../components/page'
export default () => {
// Redirect to the default locale
return redirect(`/${locales[0]}`)
}
import { unstable_noStore } from 'next/cache'
import Link from 'next/link'
import { Suspense } from 'react'
export const locales = ['en', 'fr']
export const links = [
{ href: '/', text: 'Home' },
...locales
.map((locale) => {
return [
{ href: `/${locale}`, text: locale },
{ href: `/${locale}/about`, text: `${locale} - About` },
]
})
.flat(),
]
function Dynamic() {
unstable_noStore()
return <div id="dynamic">Dynamic</div>
}
export function TestPage({ pathname }) {
return (
<div>
<ul>
{links.map(({ href, text }) => (
<li key={href}>
<Link href={href}>{text}</Link>
</li>
))}
</ul>
<code data-value={pathname}>{pathname}</code>
<Suspense fallback={<div>Loading...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
module.exports = {
experimental: {
ppr: true,
},
}
import { nextTestSetup } from 'e2e-utils'
import { links, locales } from './components/page'
describe('ppr-navigations simple', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('can navigate between all the links and back', async () => {
const browser = await next.browser('/')
try {
for (const { href } of links) {
// Find the link element for the href and click it.
await browser.elementByCss(`a[href="${href}"]`).click()
// Wait for that page to load.
if (href === '/') {
// The root page redirects to the first locale.
await browser.waitForElementByCss(`[data-value="/${locales[0]}"]`)
} else {
await browser.waitForElementByCss(`[data-value="${href}"]`)
}
await browser.elementByCss('#dynamic')
}
} finally {
await browser.close()
}
})
})
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