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([
{
files: ['packages/next/src/server/app-render/app-render.tsx'],
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': [
'error',
{
......
......@@ -905,6 +905,7 @@ export function createAppPageEntrypoint({
const dev: DevRenderContext | undefined = createDevRenderContext(req)
const context: AppPageRouteHandlerContext = {
requestUrl: req.url!,
requestHeaders: req.headers,
query,
params,
page: normalizedSrcPage,
......
......@@ -128,6 +128,7 @@ async function requestHandler(
'parsedRequestHeaders'
> = {
requestUrl: baseReq.url,
requestHeaders: baseReq.headers,
serverActionRequestMetadata,
page: normalizedSrcPage,
routeMatch,
......
......@@ -15,6 +15,7 @@ import type {
} from '../../shared/lib/app-router-types'
import { PrefetchHint } from '../../shared/lib/app-router-types'
import type { Readable } from 'node:stream'
import type { IncomingHttpHeaders } from 'http'
import {
workAsyncStorage,
type WorkStore,
......@@ -2913,6 +2914,7 @@ async function prerenderAppPage({
async function renderAppPage(
req: BaseNextRequest,
requestHeaders: IncomingHttpHeaders,
{
ctx,
metadata,
......@@ -2960,7 +2962,7 @@ async function renderAppPage(
: null
const createRequestStore = createRequestStoreForRender.bind(
null,
req,
requestHeaders,
res,
url,
rootParams,
......@@ -3204,6 +3206,7 @@ async function renderToHTMLOrFlightImpl(
req: BaseNextRequest,
res: BaseNextResponse,
requestUrl: string,
requestHeaders: IncomingHttpHeaders,
url: ReturnType<typeof parseRelativeUrl>,
pagePath: string,
query: NextParsedUrlQuery,
......@@ -3250,7 +3253,14 @@ async function renderToHTMLOrFlightImpl(
supportsPerSegmentPrefetching: renderOpts.cacheComponents,
}
)
return renderAppPage(req, prepared, postponedState, dev, stagedFallbackParams)
return renderAppPage(
req,
requestHeaders,
prepared,
postponedState,
dev,
stagedFallbackParams
)
}
async function prerenderToHTMLOrFlightImpl(
......@@ -3307,6 +3317,7 @@ export type AppPageRender = (
req: BaseNextRequest,
res: BaseNextResponse,
requestUrl: string,
requestHeaders: IncomingHttpHeaders,
pagePath: string,
query: NextParsedUrlQuery,
fallbackRouteParams: OpaqueFallbackRouteParams | null,
......@@ -3409,6 +3420,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
req,
res,
requestUrl,
requestHeaders,
pagePath,
query,
fallbackRouteParams,
......@@ -3446,6 +3458,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
req,
res,
requestUrl,
requestHeaders,
url,
pagePath,
query,
......
......@@ -182,7 +182,7 @@ function mergeMiddlewareCookies(
}
export function createRequestStoreForRender(
req: RequestContext['req'],
headers: IncomingHttpHeaders,
res: RequestContext['res'],
url: RequestContext['url'],
rootParams: Params,
......@@ -198,7 +198,7 @@ export function createRequestStoreForRender(
return createRequestStore({
// Pages start in render phase by default
phase: 'render',
headers: req.headers,
headers,
onUpdateCookies:
onUpdateCookies ??
(res
......
......@@ -38,7 +38,7 @@ import { isInterceptionRouteAppPath } from '../../../shared/lib/router/utils/int
import { RSCPathnameNormalizer } from '../../normalizers/request/rsc'
import { SegmentPrefixRSCPathnameNormalizer } from '../../normalizers/request/segment-prefix-rsc'
import type { UrlWithParsedQuery } from 'url'
import type { IncomingMessage } from 'http'
import type { IncomingHttpHeaders, IncomingMessage } from 'http'
import {
applyAppPageRscRequestMetaFromHeaders,
normalizeAppPageRequestUrl,
......@@ -93,6 +93,8 @@ export interface AppPageRouteHandlerContext extends RouteModuleHandleContext {
// Exact path-relative URL (pathname plus search) after route preparation,
// preserving its encoded bytes for rendering and prerender request IDs.
requestUrl: string
// Shared headers after request preparation; retain their live identity.
requestHeaders: IncomingHttpHeaders
page: string
routeMatch: RouteMatch
query: NextParsedUrlQuery
......@@ -191,6 +193,7 @@ export class AppPageRouteModule extends RouteModule<
req,
res,
context.requestUrl,
context.requestHeaders,
context.page,
context.query,
context.fallbackRouteParams,
......
......@@ -182,6 +182,28 @@ describe('app-dir with middleware', () => {
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 () => {
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) {
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()
res.cookies.set('rsc-cookie-value-1', `${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