Unverified Commit 57b708a7 authored by Jan Kassens's avatar Jan Kassens Committed by GitHub

Pass request headers explicitly into App request stores (#100333)

## Summary

Continue decoupling App Router rendering from HTTP request objects by
passing request headers explicitly from the Node and Edge adapters into
request-store construction. The store retains the original headers
object and its lazy header/cookie views, middleware cookie precedence,
and cookie update callback behavior.

Adds a scoped lint guard against reading `req.headers` in
`app-render.tsx` and regression coverage for middleware cookies
overriding incoming cookies on both Node and Edge. Internal render/store
signatures change; supported public APIs are unchanged.

## Verification

173 test executions passed:

- Middleware, live header views, draft mode, and cache-components
cookies in `test-dev-turbo` and `test-start-turbo`; middleware, live
header views, and draft mode in `test-start-webpack`.
- Header static bailout in both production bundlers and standalone Edge
bundling in `test-start-webpack`.
- Five focused Server Action header/cookie cases in each of
`test-dev-webpack`, `test-start-turbo`, and `test-start-webpack`,
including redirect cookie writes and Edge async storage.

<!-- NEXT_JS_LLM -->
parent 5cd616fe
...@@ -473,6 +473,19 @@ export default defineConfig([ ...@@ -473,6 +473,19 @@ export default defineConfig([
{ {
files: ['packages/next/src/server/app-render/app-render.tsx'], files: ['packages/next/src/server/app-render/app-render.tsx'],
rules: { rules: {
'no-restricted-properties': [
'error',
{
object: 'req',
property: 'url',
message: 'Use the explicit `requestUrl` input instead.',
},
{
object: 'req',
property: 'headers',
message: 'Use the explicit `requestHeaders` input instead.',
},
],
'@typescript-eslint/no-restricted-imports': [ '@typescript-eslint/no-restricted-imports': [
'error', 'error',
{ {
......
...@@ -905,6 +905,7 @@ export function createAppPageEntrypoint({ ...@@ -905,6 +905,7 @@ export function createAppPageEntrypoint({
const dev: DevRenderContext | undefined = createDevRenderContext(req) const dev: DevRenderContext | undefined = createDevRenderContext(req)
const context: AppPageRouteHandlerContext = { const context: AppPageRouteHandlerContext = {
requestUrl: req.url!, requestUrl: req.url!,
requestHeaders: req.headers,
query, query,
params, params,
page: normalizedSrcPage, page: normalizedSrcPage,
......
...@@ -128,6 +128,7 @@ async function requestHandler( ...@@ -128,6 +128,7 @@ async function requestHandler(
'parsedRequestHeaders' 'parsedRequestHeaders'
> = { > = {
requestUrl: baseReq.url, requestUrl: baseReq.url,
requestHeaders: baseReq.headers,
serverActionRequestMetadata, serverActionRequestMetadata,
page: normalizedSrcPage, page: normalizedSrcPage,
routeMatch, routeMatch,
......
...@@ -15,6 +15,7 @@ import type { ...@@ -15,6 +15,7 @@ import type {
} from '../../shared/lib/app-router-types' } from '../../shared/lib/app-router-types'
import { PrefetchHint } from '../../shared/lib/app-router-types' import { PrefetchHint } from '../../shared/lib/app-router-types'
import type { Readable } from 'node:stream' import type { Readable } from 'node:stream'
import type { IncomingHttpHeaders } from 'http'
import { import {
workAsyncStorage, workAsyncStorage,
type WorkStore, type WorkStore,
...@@ -2913,6 +2914,7 @@ async function prerenderAppPage({ ...@@ -2913,6 +2914,7 @@ async function prerenderAppPage({
async function renderAppPage( async function renderAppPage(
req: BaseNextRequest, req: BaseNextRequest,
requestHeaders: IncomingHttpHeaders,
{ {
ctx, ctx,
metadata, metadata,
...@@ -2960,7 +2962,7 @@ async function renderAppPage( ...@@ -2960,7 +2962,7 @@ async function renderAppPage(
: null : null
const createRequestStore = createRequestStoreForRender.bind( const createRequestStore = createRequestStoreForRender.bind(
null, null,
req, requestHeaders,
res, res,
url, url,
rootParams, rootParams,
...@@ -3204,6 +3206,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -3204,6 +3206,7 @@ async function renderToHTMLOrFlightImpl(
req: BaseNextRequest, req: BaseNextRequest,
res: BaseNextResponse, res: BaseNextResponse,
requestUrl: string, requestUrl: string,
requestHeaders: IncomingHttpHeaders,
url: ReturnType<typeof parseRelativeUrl>, url: ReturnType<typeof parseRelativeUrl>,
pagePath: string, pagePath: string,
query: NextParsedUrlQuery, query: NextParsedUrlQuery,
...@@ -3250,7 +3253,14 @@ async function renderToHTMLOrFlightImpl( ...@@ -3250,7 +3253,14 @@ async function renderToHTMLOrFlightImpl(
supportsPerSegmentPrefetching: renderOpts.cacheComponents, supportsPerSegmentPrefetching: renderOpts.cacheComponents,
} }
) )
return renderAppPage(req, prepared, postponedState, dev, stagedFallbackParams) return renderAppPage(
req,
requestHeaders,
prepared,
postponedState,
dev,
stagedFallbackParams
)
} }
async function prerenderToHTMLOrFlightImpl( async function prerenderToHTMLOrFlightImpl(
...@@ -3307,6 +3317,7 @@ export type AppPageRender = ( ...@@ -3307,6 +3317,7 @@ export type AppPageRender = (
req: BaseNextRequest, req: BaseNextRequest,
res: BaseNextResponse, res: BaseNextResponse,
requestUrl: string, requestUrl: string,
requestHeaders: IncomingHttpHeaders,
pagePath: string, pagePath: string,
query: NextParsedUrlQuery, query: NextParsedUrlQuery,
fallbackRouteParams: OpaqueFallbackRouteParams | null, fallbackRouteParams: OpaqueFallbackRouteParams | null,
...@@ -3409,6 +3420,7 @@ export const renderToHTMLOrFlight: AppPageRender = ( ...@@ -3409,6 +3420,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
req, req,
res, res,
requestUrl, requestUrl,
requestHeaders,
pagePath, pagePath,
query, query,
fallbackRouteParams, fallbackRouteParams,
...@@ -3446,6 +3458,7 @@ export const renderToHTMLOrFlight: AppPageRender = ( ...@@ -3446,6 +3458,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
req, req,
res, res,
requestUrl, requestUrl,
requestHeaders,
url, url,
pagePath, pagePath,
query, query,
......
...@@ -182,7 +182,7 @@ function mergeMiddlewareCookies( ...@@ -182,7 +182,7 @@ function mergeMiddlewareCookies(
} }
export function createRequestStoreForRender( export function createRequestStoreForRender(
req: RequestContext['req'], headers: IncomingHttpHeaders,
res: RequestContext['res'], res: RequestContext['res'],
url: RequestContext['url'], url: RequestContext['url'],
rootParams: Params, rootParams: Params,
...@@ -198,7 +198,7 @@ export function createRequestStoreForRender( ...@@ -198,7 +198,7 @@ export function createRequestStoreForRender(
return createRequestStore({ return createRequestStore({
// Pages start in render phase by default // Pages start in render phase by default
phase: 'render', phase: 'render',
headers: req.headers, headers,
onUpdateCookies: onUpdateCookies:
onUpdateCookies ?? onUpdateCookies ??
(res (res
......
...@@ -38,7 +38,7 @@ import { isInterceptionRouteAppPath } from '../../../shared/lib/router/utils/int ...@@ -38,7 +38,7 @@ import { isInterceptionRouteAppPath } from '../../../shared/lib/router/utils/int
import { RSCPathnameNormalizer } from '../../normalizers/request/rsc' import { RSCPathnameNormalizer } from '../../normalizers/request/rsc'
import { SegmentPrefixRSCPathnameNormalizer } from '../../normalizers/request/segment-prefix-rsc' import { SegmentPrefixRSCPathnameNormalizer } from '../../normalizers/request/segment-prefix-rsc'
import type { UrlWithParsedQuery } from 'url' import type { UrlWithParsedQuery } from 'url'
import type { IncomingMessage } from 'http' import type { IncomingHttpHeaders, IncomingMessage } from 'http'
import { import {
applyAppPageRscRequestMetaFromHeaders, applyAppPageRscRequestMetaFromHeaders,
normalizeAppPageRequestUrl, normalizeAppPageRequestUrl,
...@@ -93,6 +93,8 @@ export interface AppPageRouteHandlerContext extends RouteModuleHandleContext { ...@@ -93,6 +93,8 @@ export interface AppPageRouteHandlerContext extends RouteModuleHandleContext {
// Exact path-relative URL (pathname plus search) after route preparation, // Exact path-relative URL (pathname plus search) after route preparation,
// preserving its encoded bytes for rendering and prerender request IDs. // preserving its encoded bytes for rendering and prerender request IDs.
requestUrl: string requestUrl: string
// Shared headers after request preparation; retain their live identity.
requestHeaders: IncomingHttpHeaders
page: string page: string
routeMatch: RouteMatch routeMatch: RouteMatch
query: NextParsedUrlQuery query: NextParsedUrlQuery
...@@ -191,6 +193,7 @@ export class AppPageRouteModule extends RouteModule< ...@@ -191,6 +193,7 @@ export class AppPageRouteModule extends RouteModule<
req, req,
res, res,
context.requestUrl, context.requestUrl,
context.requestHeaders,
context.page, context.page,
context.query, context.query,
context.fallbackRouteParams, context.fallbackRouteParams,
......
...@@ -182,6 +182,28 @@ describe('app-dir with middleware', () => { ...@@ -182,6 +182,28 @@ describe('app-dir with middleware', () => {
await browser.deleteCookies() await browser.deleteCookies()
}) })
it.each(['/rsc-cookies', '/rsc-cookies-edge'])(
'should prefer middleware cookies over request cookies in %s',
async (pathname) => {
const res = await next.fetch(pathname, {
headers: {
cookie: 'rsc-cookie-value-1=from-request; other-cookie=preserved',
},
})
expect(res.status).toBe(200)
const $ = cheerio.load(await res.text())
const setCookie = res.headers.get('set-cookie')
const cookie1 = setCookie.match(/rsc-cookie-value-1=([^;]+)/)[1]
const cookie2 = setCookie.match(/rsc-cookie-value-2=([^;]+)/)[1]
expect(cookie1).toMatch(/^\d+\.\d+$/)
expect(cookie2).toMatch(/^\d+\.\d+$/)
expect($('#rsc-cookie-1').text()).toBe(`Cookie 1: ${cookie1}`)
expect($('#rsc-cookie-2').text()).toBe(`Cookie 2: ${cookie2}`)
expect($('#total-cookies').text()).toBe('Total Cookie Length: 3')
}
)
it('should respect cookie options of merged middleware cookies', async () => { it('should respect cookie options of merged middleware cookies', async () => {
const browser = await next.browser('/rsc-cookies/cookie-options') const browser = await next.browser('/rsc-cookies/cookie-options')
......
export { default } from '../rsc-cookies/page'
export const runtime = 'edge'
...@@ -50,7 +50,10 @@ export async function middleware(request) { ...@@ -50,7 +50,10 @@ export async function middleware(request) {
return NextResponse.rewrite(request.nextUrl) return NextResponse.rewrite(request.nextUrl)
} }
if (request.nextUrl.pathname === '/rsc-cookies') { if (
request.nextUrl.pathname === '/rsc-cookies' ||
request.nextUrl.pathname === '/rsc-cookies-edge'
) {
const res = NextResponse.next() const res = NextResponse.next()
res.cookies.set('rsc-cookie-value-1', `${Math.random()}`) res.cookies.set('rsc-cookie-value-1', `${Math.random()}`)
res.cookies.set('rsc-cookie-value-2', `${Math.random()}`) res.cookies.set('rsc-cookie-value-2', `${Math.random()}`)
......
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