Files
Nathan Nguyen abb1aa617c fix: eliminate double middleware execution in hybrid app+pages dev mode (#541)
* fix: eliminate double middleware execution in hybrid app+pages dev mode

In hybrid app+pages dev setups, middleware ran twice per App Router
request — once in the connect handler (SSR env) and again in the RSC
entry (RSC env). This caused double side effects for auth checks,
logging, analytics, and any middleware state mutations.

The connect handler now forwards its middleware results to the RSC entry
via an x-vinext-mw-ctx request header containing the response headers,
rewrite URL, and rewrite status. The RSC entry reconstructs _mwCtx from
the forwarded data instead of re-executing the middleware function.

Key details:
- Response headers are deferred (not applied to res) in the connect
  handler when hasAppDir is true, avoiding duplicates. They're applied
  to res only for Pages routes handled directly by the connect handler.
- The RSC plugin constructs its Request from the original HTTP request,
  not from req.url, so middleware rewrites must be forwarded explicitly
  (the connect handler's req.url rewrite is invisible to the RSC entry).
- Pure App Router (no pages/) and pure Pages Router (no app/) setups
  are unaffected — they already use a single middleware execution path.

* test: update entry template snapshot for middleware forwarding

* fix: address code review findings for middleware forwarding

- Guard x-vinext-mw-ctx check with NODE_ENV !== "production" so the
  forwarding header cannot be exploited in production builds
- Replace bare catch {} with error logging and fallback to running
  middleware normally when the forwarded context is malformed
- Filter x-middleware-next and x-middleware-rewrite from forwarded
  header entries to match the RSC entry's inline filtering behavior
- Apply deferred middleware response headers before all three
  proxyExternalRewriteNode call sites (beforeFiles, afterFiles,
  fallback external rewrites)

* test: update entry template snapshot for review fixes

* fix: extract deferred headers helper, clarify flag placement per review

- Extract applyDeferredMwHeaders() helper to deduplicate 6 identical
  inline blocks in the connect handler
- Add comment clarifying that __mwCtxApplied flag placement inside try
  block is intentional — falls back to re-running middleware on error
2026-03-16 09:28:59 +00:00
..
2026-03-09 14:56:14 +00:00
2026-03-09 14:56:14 +00:00
2026-03-09 14:56:14 +00:00