Unverified Commit 2ebafcbc authored by Josh Story's avatar Josh Story Committed by GitHub

Hoist resolved pathname into app page route match (#99259)

This PR was authored by codex but I'll share the motivation here in my
own words. In an effort to improve the architectural underpinnings of
Next.js we need to move away from a request/response dominated interface
for rendering in Next.js. The legacy of this style is code that in some
cases targets a fake Request or Response object even in cases where we
are prerendering and no such objects actually exist. This PR adds a new
concept of RouteMatch which seems overkill for only containing the
resolvedPathname however we will be migrating more properties out of
catchall context such as renderOpts and other request local context into
more semantically meaningful packaging.

## Summary

Introduce a required `RouteMatch` containing the route-prepared
`resolvedPathname` and pass it explicitly through the Node, Edge, direct
server, and static export app-page render entrypoints.

The type is owned by the app-page route-module handler boundary rather
than app-render. `resolvedPathname` is no longer written to or read from
request metadata, preventing downstream code with request access from
depending on that side channel while preserving the existing
delimiter-safe pathname representation.

## Verification

- `pnpm prettier --with-node-modules --ignore-path .prettierignore
--write <changed files>`
- `npx eslint --config eslint.config.mjs --fix <changed files>`
- `git diff --cached --check`
- Source grep confirming there are no `resolvedPathname`
request-metadata reads, writes, or fields
- Could not complete: `pnpm --filter=next types` (this fresh worktree
lacks per-package dependencies and compiled declarations; the check
failed broadly on unrelated missing modules)

<!-- NEXT_JS_LLM -->
parent 779e73eb
......@@ -5,6 +5,7 @@ import type { FallbackRouteParam } from '../static-paths/types'
import {
AppPageRouteModule,
type AppPageRouteHandlerContext,
type RouteMatch,
} from '../../server/route-modules/app-page/module.compiled' with { 'turbopack-transition': 'next-ssr' }
import { RouteKind } from '../../server/route-kind' with { 'turbopack-transition': 'next-server-utility' }
......@@ -855,10 +856,12 @@ export function createAppPageEntrypoint({
renderOperation: AppPageRenderOperation
}): Promise<ResponseCacheEntry | PrerenderFailure> => {
const routeMatch: RouteMatch = { resolvedPathname }
const context: AppPageRouteHandlerContext = {
query,
params,
page: normalizedSrcPage,
routeMatch,
sharedContext: {
buildId,
deploymentId,
......
......@@ -22,6 +22,7 @@ import type { NextFetchEvent } from '../../server/web/spec-extension/fetch-event
import type {
AppPageRouteHandlerContext,
AppPageRouteModule,
RouteMatch,
} from '../../server/route-modules/app-page/module.compiled'
import type { AppPageRenderResultMetadata } from '../../server/render-result'
import type RenderResult from '../../server/render-result'
......@@ -110,8 +111,10 @@ async function requestHandler(
const closeController = new CloseController()
const routeMatch: RouteMatch = { resolvedPathname }
const renderContext: AppPageRouteHandlerContext = {
page: normalizedSrcPage,
routeMatch,
query,
params,
......
......@@ -27,6 +27,7 @@ import type { OpaqueFallbackRouteParams } from '../../server/request/fallback-pa
import { AfterRunner } from '../../server/after/run-with-after'
import type { RequestLifecycleOpts } from '../../server/base-server'
import type { AppSharedContext } from '../../server/app-render/app-render'
import type { RouteMatch } from '../../server/route-modules/app-page/module'
import type { MultiFileWriter } from '../../lib/multi-file-writer'
import {
deflateResumeDataCache,
......@@ -53,7 +54,8 @@ export async function exportAppPage(
debugOutput: boolean,
isDynamicError: boolean,
fileWriter: MultiFileWriter,
sharedContext: AppSharedContext
sharedContext: AppSharedContext,
routeMatch: RouteMatch
): Promise<ExportRouteResult> {
const afterRunner = new AfterRunner()
......@@ -86,7 +88,8 @@ export async function exportAppPage(
fallbackRouteParams,
renderOpts,
undefined,
sharedContext
sharedContext,
routeMatch
)
if ('error' in result) {
......
......@@ -7,7 +7,10 @@ import type {
ExportPagesResult,
ExportPathEntry,
} from './types'
import type { AppPageModule } from '../server/route-modules/app-page/module'
import type {
AppPageModule,
RouteMatch,
} from '../server/route-modules/app-page/module'
import type { PagesModule } from '../server/route-modules/pages/module.compiled'
import '../server/node-environment'
......@@ -189,8 +192,8 @@ async function exportPageImpl(
req.url += '/'
}
// Set the resolved pathname without trailing slash as request metadata.
addRequestMeta(req, 'resolvedPathname', removeTrailingSlash(updatedPath))
// Resolve the pathname without a trailing slash for app page rendering.
const resolvedPathname = removeTrailingSlash(updatedPath)
if (
locale &&
......@@ -291,6 +294,7 @@ async function exportPageImpl(
// Handle App Pages
if (isAppDir) {
const routeMatch: RouteMatch = { resolvedPathname }
const sharedContext: AppSharedContext = {
buildId,
deploymentId,
......@@ -310,7 +314,8 @@ async function exportPageImpl(
debugOutput,
isDynamicError,
fileWriter,
sharedContext
sharedContext,
routeMatch
)
} else {
const sharedContext: PagesSharedContext = {
......
......@@ -33,7 +33,10 @@ import { getTurbopackChunkGroupBootstrap } from '../get-page-files'
import { UNDERSCORE_NOT_FOUND_ROUTE_ENTRY } from '../../shared/lib/entry-constants'
import type { LoaderTree } from '../lib/app-dir-module'
import { MIN_PRERENDERABLE_EXPIRE } from '../use-cache/constants'
import type { AppPageModule } from '../route-modules/app-page/module'
import type {
AppPageModule,
RouteMatch,
} from '../route-modules/app-page/module'
import type { BaseNextRequest, BaseNextResponse } from '../base-http'
import type { IncomingHttpHeaders } from 'http'
import * as ReactClient from 'react'
......@@ -2691,6 +2694,7 @@ async function prepareAppPageRender(
sharedContext: AppSharedContext,
interpolatedParams: Params,
fallbackRouteParams: OpaqueFallbackRouteParams | null,
routeMatch: RouteMatch,
generateRequestId: GenerateRequestId,
missingPrefetchHintPolicy: MissingPrefetchHintPolicy,
renderCapabilities: AppRenderCapabilities
......@@ -2841,16 +2845,9 @@ async function prepareAppPageRender(
const isPossibleActionRequest = getIsPossibleServerAction(req)
// For implicit tags, we use the resolved pathname which has dynamic params
// interpolated, is decoded, and has trailing slash removed.
const resolvedPathname = getRequestMeta(req, 'resolvedPathname')
if (!resolvedPathname) {
throw new InvariantError('resolvedPathname must be set in request metadata')
}
const implicitTags = await getImplicitTags(
workStore.page,
resolvedPathname,
routeMatch.resolvedPathname,
fallbackRouteParams
)
......@@ -3280,7 +3277,8 @@ async function renderToHTMLOrFlightImpl(
serverComponentsHmrCache: ServerComponentsHmrCache | undefined,
sharedContext: AppSharedContext,
interpolatedParams: Params,
fallbackRouteParams: OpaqueFallbackRouteParams | null
fallbackRouteParams: OpaqueFallbackRouteParams | null,
routeMatch: RouteMatch
) {
const prepared = await prepareAppPageRender(
req,
......@@ -3294,6 +3292,7 @@ async function renderToHTMLOrFlightImpl(
sharedContext,
interpolatedParams,
fallbackRouteParams,
routeMatch,
generateRenderRequestId,
getMissingPrefetchHintPolicy(
renderOpts.isBuildTimePrerendering ?? false,
......@@ -3319,7 +3318,8 @@ async function prerenderToHTMLOrFlightImpl(
parsedRequestHeaders: ParsedRequestHeaders,
sharedContext: AppSharedContext,
interpolatedParams: Params,
fallbackRouteParams: OpaqueFallbackRouteParams | null
fallbackRouteParams: OpaqueFallbackRouteParams | null,
routeMatch: RouteMatch
) {
const isRoutePPREnabled = renderOpts.experimental.isRoutePPREnabled === true
const prepared = await prepareAppPageRender(
......@@ -3334,6 +3334,7 @@ async function prerenderToHTMLOrFlightImpl(
sharedContext,
interpolatedParams,
fallbackRouteParams,
routeMatch,
generatePrerenderRequestId,
getMissingPrefetchHintPolicy(
renderOpts.isBuildTimePrerendering ?? false,
......@@ -3356,7 +3357,8 @@ export type AppPageRender = (
fallbackRouteParams: OpaqueFallbackRouteParams | null,
renderOpts: RenderOpts,
serverComponentsHmrCache: ServerComponentsHmrCache | undefined,
sharedContext: AppSharedContext
sharedContext: AppSharedContext,
routeMatch: RouteMatch
) => Promise<RenderResult<AppPageRenderResultMetadata>>
export type AppPagePrerender = (
......@@ -3452,7 +3454,8 @@ export const renderToHTMLOrFlight: AppPageRender = (
fallbackRouteParams,
renderOpts,
serverComponentsHmrCache,
sharedContext
sharedContext,
routeMatch
) => {
const { url, parsedRequestHeaders, interpolatedParams, postponedState } =
prepareAppPage(req, pagePath, fallbackRouteParams, renderOpts)
......@@ -3484,7 +3487,8 @@ export const renderToHTMLOrFlight: AppPageRender = (
serverComponentsHmrCache,
sharedContext,
interpolatedParams,
fallbackRouteParams
fallbackRouteParams,
routeMatch
)
}
......@@ -3496,7 +3500,8 @@ export const prerenderToHTMLOrFlight: AppPagePrerender = (
fallbackRouteParams,
renderOpts,
_serverComponentsHmrCache,
sharedContext
sharedContext,
routeMatch
) => {
const { url, parsedRequestHeaders, interpolatedParams } = prepareAppPage(
req,
......@@ -3530,7 +3535,8 @@ export const prerenderToHTMLOrFlight: AppPagePrerender = (
parsedRequestHeaders,
sharedContext,
interpolatedParams,
fallbackRouteParams
fallbackRouteParams,
routeMatch
)
}
......
......@@ -37,6 +37,7 @@ import type { ClientReferenceManifest } from '../build/webpack/plugins/flight-ma
import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'
import type { PagesAPIRouteMatch } from './route-matches/pages-api-route-match'
import type { RouteMatch } from './route-matches/route-match'
import type { RouteMatch as AppRenderRouteMatch } from './route-modules/app-page/module'
import type { RouteDefinition } from './route-definitions/route-definition'
import type { AppPageRouteDefinition } from './route-definitions/app-page-route-definition'
import type { AppRouteRouteDefinition } from './route-definitions/app-route-route-definition'
......@@ -414,7 +415,8 @@ export default abstract class Server<
res: ServerResponse,
pathname: string,
query: NextParsedUrlQuery,
renderOpts: LoadedRenderOpts
renderOpts: LoadedRenderOpts,
routeMatch: AppRenderRouteMatch
): Promise<RenderResult>
protected abstract getIncrementalCache(options: {
......
......@@ -25,6 +25,7 @@ import type {
import type { Params } from './request/params'
import type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher'
import type { RouteMatch } from './route-matches/route-match'
import type { RouteMatch as AppRenderRouteMatch } from './route-modules/app-page/module'
import type { IncomingMessage, ServerResponse } from 'http'
import type { ParsedUrlQuery } from 'querystring'
import type { ParsedUrl } from '../shared/lib/router/utils/parse-url'
......@@ -633,10 +634,11 @@ export default class NextNodeServer extends BaseServer<
res: NodeNextResponse,
pathname: string,
query: NextParsedUrlQuery,
renderOpts: LoadedRenderOpts
renderOpts: LoadedRenderOpts,
routeMatch: AppRenderRouteMatch
): Promise<RenderResult> {
return getTracer().trace(NextNodeServerSpan.renderHTML, async () =>
this.renderHTMLImpl(req, res, pathname, query, renderOpts)
this.renderHTMLImpl(req, res, pathname, query, renderOpts, routeMatch)
)
}
......@@ -645,7 +647,8 @@ export default class NextNodeServer extends BaseServer<
res: NodeNextResponse,
pathname: string,
query: NextParsedUrlQuery,
renderOpts: LoadedRenderOpts
renderOpts: LoadedRenderOpts,
routeMatch: AppRenderRouteMatch
): Promise<RenderResult> {
if (process.env.NEXT_MINIMAL) {
throw new Error(
......@@ -682,7 +685,8 @@ export default class NextNodeServer extends BaseServer<
clientAssetToken: this.nextConfig.supportsImmutableAssets
? ''
: this.deploymentId,
}
},
routeMatch
)
if ('error' in result) {
throw result.error
......
......@@ -88,12 +88,6 @@ export interface RequestMeta {
*/
rewrittenPathname?: string
/**
* The resolved pathname for the request. Dynamic route params are
* interpolated, the pathname is decoded, and the trailing slash is removed.
*/
resolvedPathname?: string
/**
* The cookies that were added by middleware and were added to the response.
*/
......
......@@ -72,8 +72,15 @@ type AppPageUserlandModule = {
loaderTree: LoaderTree
}
export type RouteMatch = {
// The pathname produced by route preparation, including its delimiter-safe
// encoding for path parameters.
readonly resolvedPathname: string
}
export interface AppPageRouteHandlerContext extends RouteModuleHandleContext {
page: string
routeMatch: RouteMatch
query: NextParsedUrlQuery
fallbackRouteParams: OpaqueFallbackRouteParams | null
renderOpts: RenderOpts
......@@ -169,7 +176,8 @@ export class AppPageRouteModule extends RouteModule<
context.fallbackRouteParams,
context.renderOpts,
context.serverComponentsHmrCache,
context.sharedContext
context.sharedContext,
context.routeMatch
)
}
......@@ -186,7 +194,8 @@ export class AppPageRouteModule extends RouteModule<
context.fallbackRouteParams,
context.renderOpts,
context.serverComponentsHmrCache,
context.sharedContext
context.sharedContext,
context.routeMatch
)
}
......
......@@ -1093,7 +1093,6 @@ export abstract class RouteModule<
} catch (_) {}
resolvedPathname = removeTrailingSlash(resolvedPathname)
addRequestMeta(req, 'resolvedPathname', resolvedPathname)
let deploymentId
if (nextConfig.experimental?.runtimeServerDeploymentId) {
......
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