Files
James Anderson 619e5c0f73 fix: rebuild reqCtx for rewrites after middleware (#303)
* fix: rebuild reqCtx for afterFiles/fallback rewrites after middleware

afterFiles and fallback rewrites run after middleware in the App Router
execution order. Their has/missing conditions should evaluate against
middleware-modified headers, not the original pre-middleware request.

Introduces postMwReqCtx (prod-server, deploy.ts) and __postMwReqCtx
(app-dev-server) built after x-middleware-request-* headers are unpacked.
headers, redirects, and beforeFiles rewrites keep using the original
pre-middleware reqCtx, matching Next.js execution order.

Adds getHeadersContext() to the headers shim so app-dev-server can read
the ALS-mutated headers context for the post-middleware snapshot.

Test: afterFiles rewrite with has:[cookie:mw-user] is skipped without
middleware injection and matches after middleware injects the cookie.

* fix: also use postMwReqCtx for beforeFiles rewrites in deploy.ts

In App Router execution order, beforeFiles rewrites run after middleware
(step 4 vs step 3). deploy.ts processes them after middleware runs, so
they should use postMwReqCtx like afterFiles and fallback.

prod-server.ts (Pages Router) correctly keeps reqCtx for beforeFiles —
the Pages Router order has no middleware step before beforeFiles.

* fix: resolve merge conflict - keep Vary header test and afterFiles rewrite test

* fix: move beforeFiles rewrites after middleware in app-dev-server; add has/missing regression tests

- Move beforeFiles rewrite block after middleware execution so it sees
  middleware-injected cookies/headers (matches Next.js App Router order:
  middleware → beforeFiles → filesystem → afterFiles → fallback)
- Fix Map→Record bug in __buildPostMwRequestContext: ctx.cookies is a
  Map<string,string> but RequestContext.cookies must be Record<string,string>;
  convert with Object.fromEntries() so cookie lookups work correctly
- Update .rsc-suffix stripping test to reflect new code path (cleanPathname
  is now used directly by beforeFiles rather than a separate __rewritePathname)
- Add regression tests: beforeFiles and fallback rewrite has/missing conditions
  see middleware-injected cookies (app-router); fixtures wire up mw-gated-before
  and mw-gated-fallback routes + middleware cookie injection

* Apply suggestion from @james-elicx

* fix: use postMwReqCtx for beforeFiles in prod-server (Pages Router)

Per Next.js docs, the execution order is: headers → redirects → Middleware
→ beforeFiles → filesystem → afterFiles → fallback. This applies to both
App Router and Pages Router. prod-server.ts was incorrectly using the
pre-middleware reqCtx for beforeFiles matching; switch to postMwReqCtx.

Add regression test: beforeFiles has/missing conditions on the production
Pages Router server now correctly see middleware-injected cookies.
2026-03-06 22:06:09 +00:00
..
2026-02-24 09:29:39 -06:00