* fix(app-router): preserve useActionState form state after hydration
Progressive multipart server actions executed before the initial HTML render were dropping React form state. That meant useActionState hydrated from the JavaScript initializer instead of the server action result after a no-JS form submission.
The progressive action path now decodes React form state, carries it through the App Router render pipeline, passes it to React's server and client hydration APIs, and marks form-state HTML responses as uncacheable so action results cannot be replaced by stale ISR HTML.
Adds targeted unit coverage for action decoding, SSR forwarding, cache policy, cache read bypass, and a Playwright no-JS useActionState regression.
* fix(app-router): keep progressive action result type internal
Knip reported ProgressiveServerActionResult as an unused exported type. The type is only part of this module's implementation detail for the progressive action return path, so keep it module-local.
* fix(app-router): separate progressive action cache bypass
* chore(app-router): tighten form state bootstrap wiring
* feat(app-router): promote same-layout ancestor persistence
App Router soft commits previously preserved absent non-slot entries through the merge layer and kept root-layout hard-navigation policy split between browser state and planner. That made same-layout ancestor persistence implicit and allowed unknown root identity to behave like proof of reuse.
The planner now returns explicit preserveElementIds for proven same-root transitions, browser state stores layoutIds from wire metadata, and visible commits preserve only planner-approved ancestors while leaving parallel-slot persistence semantics intact.
Adds coverage for layout id metadata, unknown-root fallback, stale element removal, and visible layout persistence.
* fix(app-router): validate layout persistence proofs
App Router payload metadata treated every string in __layoutIds as planner preservation authority. That let a bad producer, stale payload, or future refactor pass a page, slot, or malformed key as proof for layout ancestor reuse.
The violated invariant is that layout persistence proof must be validated before it reaches the commit planner. Parse __layoutIds through the AppElements wire-key codec and accept only layout keys.
Also add dynamic segment browser coverage for /blog/[slug] navigation, proving param-sensitive layout and page content update while the layout client counter persists.
* fix(app-router): scope boundary layout proofs
HTTP access fallback payloads derived layout metadata from the full route definition. Layout-level access fallbacks can render only ancestor layouts, so the old proof could let the planner preserve child layouts that were absent from the response.
Derive boundary layout metadata from the rendered layout module subset and mark the root boundary unknown when no route layout is rendered.
* docs(app-router): document layout id ordering
Document the ancestor-first layoutIds invariant at the planner snapshot boundary so future payload producers do not break same-layout prefix persistence.
dynamic() currently renders the ssr:false server loading component with pastDelay=true. That disagrees with Next.js noSSR behavior and makes loading components that suppress UI before pastDelay render the opposite state during SSR.
The ssr:false server placeholder now passes pastDelay=false while the existing SSR-enabled and client Suspense fallback paths keep their current loading props. Tests cover both the raw prop contract and the observable null-until-delay loading behavior.
redirect() without an explicit type currently reaches shared digest parsing as an empty sentinel, but the parser resolves that sentinel to push before non-action callers can apply their own default. That makes SSR and route-handler redirect handling inherit the Server Action history behavior.
Preserve the omitted type as null at the digest boundary and resolve it to push only when packaging Server Action redirects. Add focused parser coverage for omitted, explicit, and non-empty raw type segments.
* fix(headers): make draft mode status live
draftMode().isEnabled captured the initial cookie state when the request API object was created. That diverged from Next.js, where DraftMode.isEnabled is a getter over mutable provider state, so reading the same object after enable() or disable() reflects the updated draft mode status.
Keep vinext's existing request cookie map as the draft mode provider and expose isEnabled as a getter over that map. Add focused regression tests for same-object enable and disable reads.
* remove unnecessary headersContext local const — state is ALS-isolated per request
* merge duplicate draftMode isEnabled tests into existing enable/disable tests
---------
Co-authored-by: James <james@eli.cx>
App Router middleware redirects skipped next.config.js headers because config header application only happened during final response finalization. Redirect responses bypass that finalizer, so matching config headers disappeared whenever middleware short-circuited with a redirect.
Apply the matched config header layer specifically for middleware redirects using the pre-middleware request context, then merge the redirect response over it so middleware headers keep precedence. Non-redirect middleware responses continue through finalization, with regression coverage to prevent duplicate additive headers.
vinext previously treated the first next/dynamic argument as a callable loader. That broke valid Next.js call shapes such as a direct import promise and an options object with loader because React.lazy eventually tried to call a non-function value.
The shim now normalizes the public dynamic input before rendering: promises become loader functions, function loaders stay unchanged, and options objects merge with the second options argument. Focused tests cover the legacy promise form and the options-object loader form against SSR output.
* fix: remove duplicate next-shims.d.ts from fixtures
Signed-off-by: Deepam Goyal <deepam02goyal@gmail.com>
* fix: use type intersections
Co-authored-by: ask-bonk[bot] <249159057+ask-bonk[bot]@users.noreply.github.com>
* fix: remove duplicate next-shims.d.ts from examples
Apply the same consolidation from fixtures to examples/realworld-api-rest
and examples/pages-router-cloudflare. Point their tsconfigs at the shared
packages/vinext/src/shims/next-shims.d.ts instead of keeping local copies.
* fix: declare Link value before default export in next/link shim
The deleted fixture copies all had `const Link: ComponentType<LinkProps>`
before the default export. Without it the default import resolves to `any`
(masked by skipLibCheck). Add the missing value declaration.
---------
Signed-off-by: Deepam Goyal <deepam02goyal@gmail.com>
Co-authored-by: ask-bonk[bot] <249159057+ask-bonk[bot]@users.noreply.github.com>
Co-authored-by: James <james@eli.cx>
* fix(router): preserve filesystem routes before afterFiles rewrites
afterFiles rewrites were evaluated before App and Pages filesystem route matches in several runtime paths. That let a rewrite override an existing non-dynamic page, which diverges from Next.js route ordering.
The fix checks the page/app match first and only applies afterFiles rewrites when no non-dynamic route wins, while still allowing afterFiles to run before dynamic routes. Regression coverage exercises App RSC handler, Pages dev/prod, and generated Worker wiring.
* test(router): align chained afterFiles rewrite expectations
The chained rewrite fixture expected an afterFiles rewrite to override a concrete /intermediate page. That is the route-ordering behavior this branch fixes.
Update the fixture to cover both intended contracts: middleware can chain into afterFiles when no page file wins, and concrete page files are not overridden by afterFiles rewrites.
* refactor(router): remove route-ordering type assertions
Validate generated Pages route metadata at the boundary instead of asserting its shape, and make the app handler test fixture route matching explicit.
* test(router): cover afterFiles order in Pages Worker
Add a built Cloudflare Pages Router regression where a concrete page route must win before an afterFiles rewrite. Align custom Pages Worker entries with the generated worker route-match gate.
vinext only passed isLoading, pastDelay, and error to next/dynamic loading components. Next.js includes retry and timedOut, so loading UIs that destructure those props observed an incompatible shape. The shim assumed the loading prop contract was limited to the values it currently used.
This aligns the runtime and ambient shim declarations with Next.js by passing the full loading props shape, preserving current delay defaults, and wiring client retry through a replaceable lazy component. The regression test covers the SSR loading object shape.
App Router responses can vary by RSC navigation headers. Route handlers returned custom responses through the outer finalizer without the shared RSC Vary set, so caches could reuse response variants across navigation modes.
The finalizer now merges the shared VINEXT_RSC_VARY_HEADER for non-redirect, non-static-file App Router responses. Existing page helpers that already set it are deduped by the shared Vary merge helper.
Tests cover route handler finalization, custom Vary preservation, duplicate avoidance, wildcard Vary, and static-file signal exclusion.
headers() and cookies() decorated a fresh Promise on every call even when they returned the same request headers or cookie store. React.use() tracks thenables by identity, so repeated calls in one request could look like uncached request API promises.
Cache the decorated thenable by the sealed request API object, matching Next.js's WeakMap-shaped contract while preserving vinext's existing middleware invalidation path. Add regression coverage for stable same-context identity and fresh identities after middleware request header overrides.
* feat(app-router): plan root-boundary navigation decisions
* test(app-router): cover unknown visible root planning
* test(app-router): cover stale root-boundary precedence
* fix(app-router): thread target href into navigation approval
Root-boundary hard-navigation planning could derive its decision URL from the pending route snapshot even though the browser executor navigated to the controller target href. That left planner traces able to disagree with the actual hard navigation target.
Require targetHref at visible commit approval boundaries, pass the controller target through navigation and same-url server-action approvals, and record it in lifecycle traces. The focused app-browser tests now assert the planner trace carries the executor URL for hard navigation decisions.
* docs(app-router): note route manifest planner follow-up
The planner input already carries routeManifest for the issue 726 route-graph slices, but CORE-07/08 always passes null and does not read it. Without a comment, the reserved field looks accidentally unused.
Document that routeManifest becomes non-null in CORE-09 and loosen the disposition test helper so render identity can diverge from navigation identity in future coverage.
* fix(image): support images.dangerouslyAllowLocalIP for private-IP rejections
Ports Next.js commit 5452439f3db2a78967178ca4180b27fb48393a19 (PR #91686)
to vinext's next/image shim and server-side image config.
Changes:
- Add isPrivateIp() helper in shims/image-config.ts (IPv4 + IPv6, no deps)
- Update validateRemoteUrl in shims/image.tsx to reject literal private-IP
hostnames unless dangerouslyAllowLocalIP is true
- Wire dangerouslyAllowLocalIP through next-config type, Vite define,
global.d.ts, and server-side ImageConfig
- Add unit tests for isPrivateIp and component-level private-IP guard
Closes#1065
* fix(image): use ipaddr.js for correct private-IP classification
Addresses review feedback on the SSRF guard:
- Replaces the hand-rolled isPrivateIp with ipaddr.js (same library Next.js
uses), eliminating bugs in IPv4/IPv6 range checks
- Fixes incorrect 2001:2f::/32 check (not a real range) and adds all missing
non-unicast ranges: CGNAT, multicast, reserved, benchmarking, teredo,
documentation, discard, NAT64
- Correctly handles ::ffff: IPv4-mapped addresses via isIPv4MappedAddress()
- Adds explanatory comments for best-effort client-side guard and
dangerouslyAllowLocalIP server-side config
- Adds comments in tests explaining the vi.resetModules() pattern
* fix(image): externalize ipaddr.js to prevent SSR crash
ipaddr.js is a CJS UMD module that assigns to `this.ipaddr` at the
bottom of its wrapper. When Vite's SSR module runner loads it with
`noExternal: true`, the UMD wrapper executes with `this = undefined`
(strict mode in ESM context), producing:
TypeError: Cannot set properties of undefined (setting 'ipaddr')
This crashed every page render that imports `next/image` (via the
image-config.ts shim). The image-optimization-parity tests failed
with 500 errors.
Fix: add `ipaddr.js` to `ssr.external` in all 3 Vite environment
configs (top-level, RSC, SSR) so Node's native loader handles the
CJS module correctly.
* feat(router): expose RouteManifest default and segment boundary facts
RouteManifest slot facts only exposed whether a default existed, and boundary facts were limited to layout-aligned outcomes. That left later #726 planner work without graph-owned IDs for default-rendering slot bindings or layoutless route-group error segments.
Add explicit default entries keyed by semantic slot ID, thread default IDs through slot declarations and default-rendering bindings, and materialize segment-level error boundaries even when no sibling layout owns that segment.
Validation: vp test run tests/app-route-graph.test.ts; vp test run tests/app-route-graph.test.ts tests/routing.test.ts; vp check packages/vinext/src/routing/app-route-graph.ts tests/app-route-graph.test.ts; vp run vinext#build.
* ci: rerun flaked checks
* ci: rerun flaked checks again
* fix(router): avoid duplicate RouteManifest error boundary writes
RouteManifest now exposes layoutless segment error boundaries, but the segment pass also revisited layout-bearing error.tsx files that the layout pass had already written.
Skip segment error entries with an owning layout so layout-owned boundaries remain single-sourced, while layoutless route-group boundaries still materialize as ownerless facts.
Validation: vp test run tests/app-route-graph.test.ts; vp check packages/vinext/src/routing/app-route-graph.ts tests/app-route-graph.test.ts.
* feat(server): add waitForAllReady forkpoint for prerender/ISR parity
Mirrors Next.js PR #93376: adds a waitForAllReady option that defers
emitting the HTML stream until React's onAllReady fires, ensuring the
full tree (including resolved Suspense boundaries) is present before
serialization.
Changes:
- app-ssr-entry.ts: accept waitForAllReady and await stream.allReady
- app-page-stream.ts: thread waitForAllReady through the pipeline
- app-page-render.ts: pass waitForAllReady: isPrerender to the HTML render
Closes#1011
* test(app-page-stream): use toHaveBeenCalledWith for waitForAllReady forwarding
Replaces the positional-tuple type cast with expect.objectContaining,
which reads more clearly and stays robust if handleSsr's signature
gains new positional args.
---------
Co-authored-by: James <james@eli.cx>
## Summary
- Skip static generation context setup for draft mode requests in app-page-dispatch.ts, matching Next.js behavior where draft mode opts into dynamic HTML rendering.
- Port test fixture and streaming test from Next.js PR #93417 to verify draft-mode pages stream their loading.tsx / Suspense fallbacks.
## Test plan
- Added streaming test to tests/nextjs-compat/draft-mode.test.ts
- Added fixture pages at tests/fixtures/app-basic/app/nextjs-compat/draftmode/streaming/
- Verified draft-mode requests show Suspense fallback text in HTML response
Fixes#1009
* chore(lint): enable stricter promise and error rules
The lint config did not enforce several promise, exhaustive switch, template expression, self-import, and error-construction checks on source files. That let void callback promise boundaries and empty Error fixtures slip through review.
Enable the rules for vinext source files, apply the useful test subset, and make the existing async callback boundaries explicit. Also remove the redundant unknown union and close response bodies in the affected Pages Router tests so server teardown remains deterministic.
* chore(lint): require exhaustive test switches
Test files already enforce strict async callback and error construction checks, but exhaustive switch checking was source-only.
Enable switch exhaustiveness for tests and make the Pages Router response decoder handle the undefined encoding case explicitly. Tighten the allowedDevOrigins suite cleanup so the temporary dev server closes deterministically.
* fix(fetch-cache): dedupe identical render fetches
Uncached and no-store fetches currently bypass the persistent fetch cache by calling the original fetch directly. That diverges from Next.js, where the patched fetch wraps the original fetch in a request-scoped dedupe layer before persistent cache policy runs, so repeated GET and HEAD fetches during a render share one network response.
Add request-scoped fetch dedupe state to the fetch cache context and route network misses and cache-bypass fetches through it. The dedupe key follows the Next.js method, header, mode, redirect, credentials, referrer, referrerPolicy, and integrity semantics while still opting out for abort signals, keepalive, and side-effecting methods.
Update fetch-cache coverage for uncached render dedupe, independent response bodies, request-scope isolation, trace header exclusion, and the changed no-store/no-cache interaction.
* fix(fetch-cache): give each cloned dedupe response its own Headers
Pass `new Headers(response.headers)` per clone instead of sharing the same
Headers object across both branches and the dedupe entry. Matches Next.js'
`cloneResponse` and avoids a future-correctness trap if any code path mutates
response headers post-fetch.
Also drops two redundant `runWithFetchDedupe` calls inside `dispatchAppPage`
(the ISR revalidation render path and the intercept stream render path) — both
sites are inline anonymous functions that already inherit the dedupe scope from
the outer `dispatchAppPage` / `runAppPageRevalidationContext` wrap, so the
inner calls were no-ops and just obscured that inheritance.
* test(fetch-cache): cover Request input dedupe + always clone bodyless responses
Always construct fresh Response objects in cloneDedupeResponse, including the
bodyless path that previously returned the same `response` reference for both
tuple slots. Mirrors Next.js' cloneResponse and avoids any "disturbed response"
surprise if a runtime tracks consumption state on the shared reference. Factor
the per-clone construction into buildDedupeClone() so bodied and bodyless
clones share the headers-copy + url-restore + finalizer-register treatment.
Adds a comment near entry.response assignment noting that the unconsumed tee
branch is bounded by the render scope: when runWithFetchDedupe exits, the
dedupe map becomes unreachable and the FinalizationRegistry cancels any
still-unconsumed branch.
Also adds two tests covering the Request-object input path of
createFetchDedupeCandidate — one verifying dedupe applies for identical
Request inputs, one verifying differing non-trace headers on Request inputs
prevent dedupe.
* fix(fetch-cache): drop failed dedupe entries so later callers can retry
When the original fetch rejects, the dedupe entry stayed in the map with
response: null. Subsequent callers within the same render scope chained on
the rejected promise — propagation was correct, but they could never retry,
because the failed entry blocked fresh attempts for the rest of the scope.
React.cache() (which Next.js uses) avoids this because each call site
naturally retries on failure.
Splice the entry out of the URL bucket on rejection so a later fetch to the
same URL within the same render scope creates a fresh entry and re-issues
the upstream request.
Also align the fetch-dedupe-metadata fixture with fetch-dedupe-isr-metadata
by replacing the `as CountBody` cast with a runtime assertCountBody check.
* docs(fetch-cache): document scope inheritance + harden ISR test stabilization
Rename `dispatchAppPageWithDedupe` to `dispatchAppPageInner` so the name
reflects that it runs *inside* the dedupe scope rather than activating it.
Add comments at the four `runWithFetchDedupe` / `renderToReadableStream`
sites explaining how each one relates to the surrounding dedupe scope:
- app-page-render and app-page-boundary: defensive wrap, no-op under
dispatch; standalone callers must keep an outer scope alive across async
stream consumption since `runWithFetchDedupe` of a synchronous fn only
covers the synchronous portion.
- ISR revalidation render and intercept render in dispatch: explicitly note
why no inner wrap is needed (the outer revalidation context / dispatch
wrapper already activated dedupe).
- runWithFetchDedupe doc: document the ALS-scope-vs-async-consumption
caveat that ties this together.
Replace the fixed 200ms post-condition sleep in the ISR background dedupe
test with a 500ms count-stabilization poll. A stray third upstream fetch
(which would betray dedupe leaking across the metadata + page render
boundary) is now caught regardless of when it fires.
---------
Co-authored-by: James <james@eli.cx>
* fix(app-router): schedule link navigations as transitions
App Router link clicks could commit cross-route payloads synchronously because the browser entry passed route path equality into the navigation controller as a transition toggle. That diverged from Next.js, where app-router push and replace enter React.startTransition for every app navigation.
Remove the transition override from normal navigation payload commits, keep synchronous commits private for HMR and same-URL server-action handling, and start RSC Link navigations through the same programmatic transition path used by useRouter().
* test(app-router): cover link transition scheduling behavior
* docs(navigation): drop stale isSameRoute references in comments
The isSameRoute concept was removed from app-browser-entry.ts in this PR;
update two comments in navigation.ts that still referenced it.
---------
Co-authored-by: James <james@eli.cx>
* fix(cache): scope use cache keys by deployment id
Shared "use cache" entries only used the vinext build ID as their cache-key seed. That diverges from the upstream Next.js change for cacheHandlers and can let a Cloudflare Worker deployment reuse entries from another deployment when the deployment identity changes independently of the build fallback.
The cache runtime now resolves a deployment-aware key seed at execution time, with request-scoped Worker version metadata or NEXT_DEPLOYMENT_ID taking precedence over the build ID. Generated Wrangler config includes the CF_VERSION_METADATA binding, and the App Router Worker entry threads it into the runtime without process-global request races.
Tests cover deployment ID precedence, concurrent deployment scope isolation, build ID fallback, and generated Worker config wiring.
* fix(config): resolve deployment id for cache seeds
Deployment-aware "use cache" keys had runtime Worker and NEXT_DEPLOYMENT_ID support, but vinext did not resolve the Next.js deploymentId config field. That left config-defined deployment identity out of the build-time cache seed.
Resolve deploymentId from next.config.js before NEXT_DEPLOYMENT_ID, validate the same string shape Next.js documents, and feed the resolved value into the __VINEXT_DEPLOYMENT_ID define. The process-wide cache-runtime setter is also documented as a fallback rather than the per-request API.
Tests cover config precedence, env fallback, empty config values, and invalid deploymentId shapes.
* refactor(cache): carry deployment id through request context
The Worker version metadata path still needs request-scoped state, but cache-runtime should not own a cache-specific deployment ALS or public-looking setter.
Move runtime deployment ID storage into the unified request-context layer. The Worker boundary now writes deploymentId into request runtime context, cache-runtime reads that generic request metadata before falling back to inlined deployment/build IDs, and the tests cover direct runtime scopes plus inheritance into unified request contexts.
* refactor(cache): reuse request context for deployment id
* test(app-elements): expect artifact compatibility metadata
* refactor(cache): inline deployment id seed
* chore: rerun ci
Tags with non-ASCII characters (Hebrew, Arabic, CJK, emoji) can crash ISR
responses with ERR_INVALID_CHAR when written to x-next-cache-tags, and
silently break invalidation when storage form diverges from the form
revalidateTag/revalidatePath produce.
Add encodeCacheTag/encodeCacheTags helper (matches behavior of
vercel/next.js#93601) and apply it at every public boundary: cacheTag,
revalidateTag, revalidatePath, updateTag, unstable_cache options.tags,
fetch next.tags, and the path-derived _N_T_ tag builders.
Closes#1138
* feat(cache): export stable `io` from next/cache, deprecate `unstable_io`
Next.js stabilized `unstable_io` as `io` in vercel/next.js#93621 without a
deprecation alias. vinext shipped the unstable name longer than upstream
canaries (since #805), so keep `unstable_io` as a transitional alias that
emits a one-time deprecation warning.
Closes#1139
* chore: apply formatter
* fix(app-router): emit action revalidation headers
Server Actions that call revalidatePath, revalidateTag, updateTag, refresh, or mutate cookies currently return RSC responses without x-action-revalidated. The client router therefore keeps stale cached payloads after an action invalidates data.
The action execution path assumed cache invalidation only needed to touch the server-side cache handler. Record action-scoped revalidation in the cache shim, consume it when building action responses, and preserve Next.js' static-and-dynamic versus dynamic-only header values.
Tests cover normal action rerenders, redirecting actions, and refresh dynamic-only invalidation.
* fix(app-router): match profiled tag action revalidation
Server Actions using revalidateTag with a cacheLife profile should not trigger x-action-revalidated. Next.js treats profiled tag revalidation as stale-while-revalidate and does not force immediate client router cache invalidation.
Only record action revalidation for the no-profile revalidateTag form, keep the action marker cleanup symmetric on error, and cover the profiled tag case in server action tests.
* fix(app-router): notify actions for immediate tag expiry
Server Actions that call revalidateTag with an inline profile of expire zero immediately expire server cache data, but the client router still needs x-action-revalidated to drop stale RSC payloads.
Resolve revalidateTag profiles before deciding whether to mark action revalidation, matching Next.js' no-profile or expire-zero condition. Also clear the action marker on progressive action errors for symmetry with the RSC action path.
* fix(app-router): notify on revalidateTag with unknown profile
Address review feedback:
- revalidateTag with an unrecognized profile string resolves to no
durations and the handler treats it as a full invalidation, but the
client router was not being notified. Mark action revalidation when
durations is missing too.
- Document the cookie override path in resolveActionRevalidationKind so
future readers see why it bypasses the max-escalation pattern used in
markActionRevalidation.
---------
Co-authored-by: James <james@eli.cx>
* perf(prerender): reuse embedded RSC payload
* fix(prerender): address RSC extraction review
* fix(test): include artifact compatibility metadata
* fix(prerender): document RSC extraction invariants
* refactor(prerender): simplify RSC extractor and remove dead fallback
Cleanups on top of #1097:
1. Drop the legacy `__VINEXT_RSC__` extractor. The browser entry still
recognizes that format for in-the-wild cached HTML, but prerender
parses HTML it just emitted in this build, where the writer always
emits the chunked form. The legacy branch is unreachable here.
2. Remove the silent fallback to a second `RSC: 1` invocation. The
writer is in-tree, so a missing-marker case is a vinext-internal
regression we want to surface loudly rather than mask by
double-rendering. `extractRscPayloadFromPrerenderedHtml` now
returns `string` and throws on any anomaly.
3. Replace the manual JSON-string tokenizer (parseEmbeddedJsonString +
assertOnlyTrailingSemicolon + isWhitespace, ~80 lines) with a
~12-line slice + JSON.parse. Relies on the same safeJsonStringify
invariant the original parser relied on; tampering with trailing
code now surfaces as 'invalid chunk JSON' instead of a separate
diagnostic, which is fine for an internal protocol.
4. Remove the obsolete TODO marker ("Extract RSC payload from the
first response instead of invoking the handler twice") — the PR
resolves it.
7. Tighten the chunk-presence assertion: empty HTML or HTML with only
the done marker now throw 'no chunk scripts found in HTML' instead
of returning the fallback sentinel.
Test updates mirror these:
- Drop the two legacy-format tests.
- Drop the "falls back to a separate RSC request" integration test
(the fallback no longer exists).
- Update error-message assertions where the diagnostic text changed.
* fix(prerender): fall back to second invocation for non-render HTML responses
The previous cleanup made `extractRscPayloadFromPrerenderedHtml` throw
on any HTML lacking RSC embed chunks. That's wrong for one legitimate
case: middleware that short-circuits the App Router pipeline with a
custom 200 HTML response — that HTML never went through
createRscEmbedTransform, so it has no chunks and no done marker.
Distinguish two cases at the extractor level:
- No chunks AND no done marker → middleware short-circuit. Return null
so the caller falls back to a second invocation with `RSC: 1`.
- Done marker present without chunks → real bug, throw.
- Chunks present without done marker → real bug, throw.
- Malformed/tampered chunk JSON → real bug, throw.
The driver checks for null and recovers by issuing a second handler
invocation with RSC headers, writing whatever that returns as the
.rsc file.
Adds an integration test alongside the existing dedup test:
- Middleware short-circuit: server returns 200 HTML without chunks for
page requests, valid Flight for RSC: 1 → driver writes the fallback
payload as .rsc, with exactly one of each request kind.
* fix(prerender): fail non-ok RSC fallback responses
---------
Co-authored-by: James <james@eli.cx>
* fix: add `shell: true` on Windows for execFileSync calls
On Windows, `execFileSync` cannot execute `.bin/wrangler` (a shell
script) or package manager commands like `npm`/`npx` (which are `.cmd`
wrappers) without enabling the shell. This causes `ENOENT` errors
during `vinext deploy`, `vinext build`, and `vinext lint`.
Fix by adding `shell: process.platform === "win32"` to all
`execFileSync` options. This only enables the shell on Windows where
it's required, preserving the no-shell-injection guarantee on other
platforms.
Fixes `spawnSync ENOENT` on Windows for:
- `runWranglerDeploy` (deploy.ts)
- `installDeps` (deploy.ts)
- React upgrade in `deploy()` (deploy.ts)
- React upgrade in `buildApp()` (cli.ts)
- Lint commands in `lint()` (cli.ts)
* style: break long execFileSync lines to fit printWidth: 100
* fix: use ExecFileSyncOptions for execFileSync opts type
ExecSyncOptions.shell is typed as `string | undefined`, while
ExecFileSyncOptions.shell is `boolean | string | undefined`. The
explicit annotation rejected the new `shell: process.platform === "win32"`
boolean. Switching to the matching options type resolves the TS2322
error reported by `vp check` in CI.
* docs: update execFileSync comment for cross-platform shell behavior
Reflects shell: true on win32 — the array form still prevents trivial
injection, but the older comment implied shell-free execution everywhere.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Middleware could consume the same ReadableStream that downstream App Router handling later needed to read. This broke POST route handlers when middleware inspected request.json() and then returned NextResponse.next().
The root cause was constructing middleware NextRequest instances from the caller-owned Request body. Clone the request body branch before wrapping or pathname-normalizing middleware requests, and cover both the constructor and middleware pipeline behavior with regression tests.
* fix(app-router): read indefinite app page cache entries
App pages with revalidate=false currently normalize to Infinity, but the app-page cache read gate excludes Infinity. Pre-rendered static app pages can be seeded into the ISR cache and still miss that cache on every production request.
The cache read policy now treats positive Infinity as read-eligible while preserving force-dynamic, production, RSC, and nonce guards. Cached indefinite responses are normalized to the same static one-year Cache-Control header used by fresh revalidate=false responses, so cache hits do not emit s-maxage=Infinity.
Tests cover the dispatch cache hit path and the shared cached Cache-Control helper.
* chore: rerun ci
* chore: rerun ci
The create-next-app job was failing with ERR_PNPM_UNEXPECTED_STORE.
create-next-app's bundled pnpm (10.x) installs node_modules linked to
the v10 store; vp's bundled pnpm recently bumped to v11, which then
refuses to add packages to the v10-linked node_modules.
Anchor the scaffolded project to vinext's own pinned pnpm version
(read from root package.json's packageManager field) and invoke that
pnpm directly via npx for the install step. This:
- keeps store layouts aligned between create-next-app's install and
the subsequent vinext add
- stays in sync with future pnpm bumps without further CI edits
- bypasses vp's bundled pnpm only for this layering step; the rest of
the job (vp exec, vp dlx) is unchanged
Middleware request-header overrides could rebuild forwarded external rewrite requests from only the override set. That drops cookie and authorization when middleware reports a partial override, so proxied upstream requests lose credentials.
Keep Next.js-compatible deletion semantics by default, and make credential preservation an explicit opt-in for external proxy boundaries. Cover both partial preservation and explicit credential deletion.
App Page ISR could serve a cached production response to a request carrying a valid __prerender_bypass cookie. That violates Next.js draft-mode semantics because preview users must render dynamically and must not populate shared page cache entries.
The dispatch layer now identifies draft-mode requests with the same cookie parser and secret used by draftMode(), skips App Page cache reads, and passes that state into render response policy. HTML and RSC render paths now treat draft mode as no-store and avoid cache capture/write work.
Tests cover valid draft cookies bypassing cached HTML, arbitrary cookie values preserving cache hits, and response-policy no-store behavior.
RSC fetch actions that threw notFound() or another HTTP access fallback still returned a Flight payload with status 200. That diverged from Next.js, which sets the response status to the access fallback status before generating Flight for fetch actions.
The server action path now extracts the fallback status while preserving the action error in the Flight return value. The regression test covers legacy NEXT_NOT_FOUND, modern NEXT_HTTP_ERROR_FALLBACK;404, and another fallback status.
* feat(router): expose RouteManifest semantic facts
RouteManifest only exposed minimal route, layout, template, and slot lookup maps. That left later #726 planner and cache-proof work without stable graph-owned facts for slot ownership, slot defaults, template reset scope, or boundary outcomes.
The graph builder now derives declaration-level slot facts, per-route slot bindings, template remount facts, and layout-boundary outcome facts from existing App Router metadata. The manifest graphVersion includes the new maps so downstream compatibility checks can detect semantic topology changes.
Tests cover route groups, slots, defaults, templates, and boundaries in one fixture.
* test(router): align CI fixtures with graph facts
Full CI checks more App Router fixtures than the targeted RouteManifest test run. The new ParallelSlot declaration fields must be present in hand-built fixtures, otherwise typecheck fails even though production graph scanning populates them.
The app browser trace tests also still asserted the stale reason at entry zero, but no-commit transaction tracing is prepended before the reason entry. Update those assertions to inspect the stale reason entry without changing runtime behavior.
* fix(app-router): guard repeated hard navigation targets
Root-boundary changes currently trigger a hard navigation without remembering the target. If an old client keeps receiving an incompatible new-server payload for the same URL, the recovery path can re-enter the same hard navigation instead of stopping the loop.
Persist the attempted hard-navigation target in sessionStorage, block a repeated same-target attempt once the browser is already on that URL, and clear the guard after a successful initial RSC bootstrap. Add old-client/new-server future compatibility coverage so unknown metadata remains a render-fresh fallback, not reuse proof.
* test(app-router): cover cross-page hard navigation guard
Bonk noted that the hard-navigation guard allows cross-URL recovery even when sessionStorage cannot persist the guard, and that same-URL server-action hard navigation intentionally ignores the guard result.
Document those invariants in the controller and add coverage proving a stored guard target does not block a hard navigation when the browser is currently on a different URL.
NextResponse.next({ status }) currently continues routing but drops the middleware response status. That diverges from Next.js middleware handling and makes successful route rendering mask middleware-selected statuses such as 404.
The middleware runtime now exposes a status override for continue responses, and App Router plus Pages Router dev/prod consumers feed that value into their existing middleware response contexts. Rewrite status behavior remains covered by the same path.
Tests cover the middleware runtime contract, App Router context propagation, and a Pages Router dev integration case with a real matched page.
Stale App Router RSC cache entries currently schedule background regeneration with only the clean pathname. That violates the cache-key invariant because RSC app-page entries include the mounted slot variant, so concurrent stale variants for one pathname can collapse into one pending regeneration.
HTML ISR cache writes also read late dynamic usage from the cache branch after the client branch can clear request context. When dynamic APIs are discovered while streaming, the cache writer can miss that signal and persist personalized output.
Use the actual app-page ISR cache key as the regeneration dedup key, and snapshot late dynamic usage immediately before request context cleanup so the HTML cache writer can still skip writes after stream teeing. Add focused regression coverage for slot-specific stale regeneration and pre-cleanup dynamic usage.
* fix(config): exclude React from ssr optimizeDeps when ssr.external: true
When users set `ssr.external: true` in vite.config.ts (the only practical
way to keep CJS-quirky packages like pg, protobufjs, keyv,
@launchdarkly/js-server-sdk-common, @opentelemetry/otlp-transformer
working in dev), `'use client'` components calling React.useContext from
external packages (nuqs, next-themes, launchdarkly-react, etc.) crashed
in dev with `Cannot read properties of null (reading 'useContext')`.
Root cause: @vitejs/plugin-rsc populates
environments.ssr.optimizeDeps.include with React entries via
crawlFrameworkPkgs. With external: true, the SSR env loads React via
Node's resolver, but Vite still pre-bundles a duplicate React copy into
deps_ssr/ because optimizeDeps.include overrides external: true.
react-dom-server.edge then sets the dispatcher on its bundled React
while externalized callers (vinext's runtime) see a different React,
leaving React.H null and crashing every hook call from a 'use client'
module SSR'd through it.
Fix: when userSsrExternal === true, add React entries to
environments.ssr.optimizeDeps.exclude so plugin-rsc's auto-includes
cannot pre-bundle a duplicate copy. The renderer and the runtime then
share one Node-loaded React.
The RSC env is unaffected (it still pre-bundles React with the
react-server condition), and the default mode (`noExternal: true`) is
unaffected since external: true gating the strip.
Closes#1103
* fix(config): also skip top-level ssr.noExternal: true when ssr.external: true
The previous fix only stripped React entries from
environments.ssr.optimizeDeps.exclude, but Vite uses top-level `ssr.*`
as defaults for `environments.ssr.*`. With vinext setting top-level
`ssr.noExternal: true` unconditionally (when not Cloudflare/Nitro),
that `true` leaked into `environments.ssr.resolve.noExternal` and
@vitejs/plugin-rsc's later expansion to an array (or the user's own
configResolved mirror) brought React back into the bundled list,
recreating the duplicate-React crash.
Two changes:
1. When `config.ssr.external === true`, vinext only sets the top-level
`ssr: { external: true }` block — no `noExternal: true` to leak into
the per-env config.
2. Defensive configResolved hook that strips React entries from
`environments.ssr.resolve.noExternal` if a later plugin (or
plugin-rsc itself) added them back. The strip is gated on
`external === true` so it only applies in the all-external mode.
Verified against a real-world App Router app (~80 deps including nuqs,
next-themes, launchdarkly-react, blocknote, opentelemetry, pg,
protobufjs, keyv, etc.): with ssr.external: true and these fixes
applied, 'use client' routes now render correctly in dev — the
`Cannot read properties of null (reading 'useContext')` /
`Invalid hook call` crashes are gone.
Refs #1103
App Router middleware currently receives internal Flight request headers, and external middleware rewrite proxy responses can return upstream x-middleware-* control headers when no middleware header context exists. That exposes internal protocol state at request and response boundaries.
The middleware entry now clones requests with the Next.js Flight header set removed before middleware execution or middleware-owned external rewrites. External middleware rewrite proxy responses are always sanitized with the existing middleware header scrubber before any middleware headers are merged.
Regression coverage asserts middleware cannot observe Flight headers and that upstream proxy x-middleware-* headers are stripped without context.