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