Commit Graph

1286 Commits

Author SHA1 Message Date
Nathan Nguyen 66519412c3 fix(app-router): reuse pending prefetched RSC payloads (#1704) 2026-05-31 20:08:13 +01:00
Divanshu Chauhan (divkix) 19dfd5e009 feat(config): add experimental.appShells config plumbing and validation (#1692) 2026-05-31 18:22:15 +01:00
Nathan Nguyen f36959dea6 fix(app-router): preserve middleware headers on metadata routes (#1700)
App Router metadata routes returned their generated response before the middleware response context was merged. That let static metadata defaults such as Cache-Control: public, max-age=0, must-revalidate overwrite a middleware Cache-Control header for app/favicon.ico.

Apply the same middleware response-header and status merge used by other App Router response paths before returning metadata route responses, and cover the upstream Next.js no-duplicate-headers fixture.
2026-05-31 11:40:37 +01:00
Nathan Nguyen a35e43cef3 feat(skip): add layout safety observation foundations (#1672)
* feat(skip): add layout safety observation foundations

Introduce the per-layout observation primitives that later slices need
to decide whether retained static layouts can be reused. This slice
adds the machinery only; nothing reads the observations yet, so
behavior is unchanged.

- app-layout-param-observation: per-layout completeness, param keys,
  structural scope, finite revalidate, request API, cacheLife, cache
  tag, cacheable fetch, dynamic fetch, and unstable_cache observation
  tracker.
- app-page-probe: bounded React server subtree probe that walks
  layout-returned children including memo, forwardRef, and React.lazy
  wrappers, enforces depth and node limits, and refuses single-use
  iterable children.
- shims: thenable params observer for sync, await, destructure, and
  enumeration. Cache, fetch, and unified request context record
  unstable_cache, cacheable fetch, and request-scoped observation
  state.
- app-page-params: structural segment-param scope so empty optional
  catch-all targets are not treated as param-free downstream.

No skip transport behavior. Later slices wire the planner, manifest,
and encoder onto these observations.

* fix(skip): address review feedback on observation foundations

- Add currentFetchSoftTags reset in runWithIsolatedProbeDependencies to prevent soft tag leak from parent scope (matches runWithFetchCache isolation)
- Replace unnecessary JSON.stringify in cacheLife check with direct null comparison
- Add comment documenting intentional omission of markProbeComplete on probe errors (keeps completeness as unknown, safe fallback to render-and-send)

* fix(skip): record cacheable-fetch observation synchronously before first await

The patched fetch deferred observation and tag collection past
await buildFetchCacheKey(). If a layout probe started a cacheable
fetch and returned synchronously without awaiting it, the probe
snapshot would see cacheableFetchCount: 0 -- a false proof that
could let the skip planner reuse a stale retained layout.

Move observation and tag recording before the first await in the
cacheable branch. If key generation later fails and the fetch falls
back to dynamic, recording both is conservative (false unsafe costs
performance, not correctness).

Add an integration test that exercises the real patched fetch shim
without mocks to verify synchronous observation capture.

* fix(test): remove polluting fetch restore and catch background promise

Do not restore globalThis.fetch in test cleanup. ensureFetchPatch
sets a global _PATCH_KEY guard; restoring fetch without clearing
that marker makes later calls skip reinstallation silently.

Catch the background fetch promise inside the probe so the patched
fetch continuation (cache lookup, network fetch) cannot produce an
unhandled rejection after the synchronous assertions complete.

* chore: empty commit to trigger CI

* chore: empty commit to trigger CI
2026-05-31 11:39:47 +01:00
Nathan Nguyen b1f2e57bc4 fix(pages): preserve import.meta.url source paths (#1598)
* fix(pages): preserve import.meta.url source paths

Pages Router production bundles previously left direct import.meta.url expressions for the bundler to evaluate from generated output. Server renders could expose dist/server/entry.js, and prerendered Pages output could miss the client entry needed for hydration to replace the server value with the Turbopack-style browser source URL.

The fix rewrites direct import.meta.url reads in user modules to source-file URLs at transform time, keeps new URL asset bases intact, and loads the Pages client entry from the build manifest for Node production and prerender servers.

Regression coverage ports the Next.js import-meta deploy test, including the prerender and hydrated browser path.

* fix(tests): run import.meta browser coverage in e2e

The import-meta regression test launched Playwright from a Vitest integration shard. That shard does not install Playwright browser binaries in CI, so it failed before exercising the runtime behavior.

Move the browser assertion into the existing pages-router-prod Playwright project, keep the lower-boundary server and client chunk assertions in Vitest, and cache the import-meta plugin root paths after an early source-text bailout to address review feedback.

* refactor(import-meta-url): canonicalize each module once per transform

The transform path canonicalized the same module id twice: once in the
eligibility check and again when computing the replacement value, so every
rewritten module paid for two fs.realpathSync.native() syscalls.

The eligibility check now returns the canonical id and threads it through to
the value computation, leaving a single realpath per module.

Also widens the extension match to .cts/.mts/.cjs and documents that the
new URL() skip only covers the bare URL identifier, matching Vite's own
asset-detection scope.

* test(pages): drop unrelated prerender from top-level-await setup

The top-level-await production test ran runPrerender in its setup, but the
assertions pass identically whether the routes are prerendered or rendered on
demand. The step added unrelated build work to a test that is not about
prerendering or client-entry injection.

* fix(pages): share client entry fallback

* fix(import-meta-url): address PR review feedback

- Handle ChainExpression (import.meta?.url) in new URL() asset-detection
  skip so the optional-chain variant preserves Vite asset resolution
- Add explicit ChainExpression check in visit() to avoid fragile
  reliance on coincident inner-node start/end ranges
- Add test for new URL('./file', import.meta?.url) preservation
- Fix decodeHtmlText entity ordering (& before ") in both
  unit and E2E test helpers
- Add doc comments: excluded prefixes rationale, node_modules
  early-exit optimization intent

* fix(pages): select client entry by marker in build manifest

findClientEntryFileFromManifest returned the first chunk flagged
isEntry, but a client build can emit several entry chunks (client
entry plus instrumentation/middleware) and manifest order is not
guaranteed. The on-disk fallback already disambiguates by the
vinext-client-entry / vinext-app-browser-entry marker; apply the
same check to the manifest path so both lookups agree, falling back
to the first entry only when nothing is marked.

* refactor(pages): address review feedback on client-entry/import-meta-url

- prod-server: hoist findClientEntryFile out of the manifest if/else
  since it already handles a missing manifest via the on-disk fallback
- import-meta-url: document the two known limitations (destructured
  access, aliased new URL() base) that match Vite's own behavior
- import-meta-url: drop the dead visit(value.callee) for new URL() —
  the callee is always the bare URL identifier

---------

Co-authored-by: James <james@eli.cx>
2026-05-31 11:37:09 +01:00
James Anderson 7bb669c0e9 test(routing): regression for parallel slot page-over-default priority (#1339) (#1689)
Issue #1339 reported parallel route slots falling back to default.tsx
instead of the matched page. That gap was already closed on main by
#1389 (resolve nested slot pages over default.tsx) and #1659/#1535
(treat @children as transparent). This adds a regression test mirroring
the Next.js parallel-routes-layouts fixture — the canonical
"Hello from Nested" vs "default page" case — asserting that:

- the children slot at /nested resolves nested/page.tsx, not
  nested/default.tsx;
- sibling @foo/@bar slots that each own both a page and a default pick
  their page; and
- at /nested/subroute (only @bar matches) the children slot falls back
  to default, @bar mirrors its subroute page, and @foo keeps its default.

Locks in page-over-default priority across sibling slots so the
behavior cannot silently regress.
2026-05-31 09:29:30 +01:00
Steve Faulkner 87479df147 fix: bound default memory cache size with LRU eviction (#1699)
MemoryCacheHandler used an unbounded Map for default ISR/fetch/cache
storage. Add a Next-style memory cap with approximate byte sizing and
least-recently-used eviction.

Behavior:
- default max size is 50 MiB, matching Next.js cacheMaxMemorySize default
- cacheMaxMemorySize: 0 disables default memory storage
- entries larger than the configured cap are not stored
- get() refreshes LRU order
- tag invalidation metadata is capped to 10k entries

Wire next.config.js cacheMaxMemorySize into both App and Pages generated
entries via configureMemoryCacheHandler(). Add focused unit coverage for
LRU eviction, get() recency refresh, and disabled storage.
2026-05-30 21:37:42 -05:00
Steve Faulkner 0c1193fd76 fix: include i18n context in Pages ISR cache keys (#1698)
Pages Router ISR cache entries were keyed only by pathname. With i18n
domain routing, the same pathname can render different content depending
on the matched domain and default locale. A cache entry created for one
domain could be reused for another domain.

Add an i18n cache variant to the Pages ISR key when i18n is configured:
- domain:<domain> for matched domain-locales
- locale:<locale> for locale-prefix/default-locale routing

Adds a Pages i18n production fixture page with getStaticProps +
revalidate and verifies example.fr and example.com maintain separate
ISR entries for the same pathname.
2026-05-30 15:33:17 -05:00
Steve Faulkner 534487a5bf fix: reject server-only imports from client-reachable modules (#1697)
Match Next.js handling for the server-only marker: imports are allowed
from App Router Server Components and middleware/server targets, but
client-reachable modules must fail instead of silently resolving the
empty shim.

Add an AST-based client-environment transform guard so comments or
string literals do not false-positive. The existing middleware test
continues to prove server-only remains allowed from middleware graphs,
and the new Pages Router fixture mirrors Next.js's compiler error test
for server-only imported from a Pages client graph.
2026-05-30 14:46:47 -05:00
Nathan Nguyen e8c188ce13 feat(skip): add static layout reuse proof model (#1674)
* feat(skip): add static layout reuse proof model

Add the proof/planner vocabulary that decides whether a verified
static layout entry from a client reuse manifest is reusable.
Nothing renders this decision yet, so no payload is omitted.

- skip-cache-proof: static layout reuse planner with per-entry budget,
  exact artifact-compatibility check, payload hash, route id, and
  invalidation proof. Preserves rejection traces. Returns the existing
  disabled disposition when not authorized.
- static-layout-client-reuse-proof: static layout payload hash, route
  id, and artifact compatibility helpers used by the planner.
- client-reuse-manifest: extends the rejection code union with the
  layout-safety rejection codes the planner emits, and adds the
  enabled skip disposition variant so future slices can carry an
  authorized result without retyping the union.

This slice is the proof vocabulary only. The planner is callable but
not invoked from the render path; encoder behavior is unchanged.

* fix(skip): address review — budget counts all wire entries, default enforcement, triple-walk justification, hash stability comment, forward declarations comment, absent-manifest test

* fix(skip): replace as const with explicit return type annotation

* fix(skip): replace as const with ProofFieldPair type alias

* fix(skip): address copilot review — pairs serialization, budget disambiguation, skip-ineligible tracking, compatibility-bridged test

* fix(skip): remove routeId from renderEpoch, bind verifier entryId, add sibling-route test

* fix(skip): exclude routeId from payload hash, add end-to-end sibling-route proof test

* chore(skip): move proof fields to artifact-compatibility, rename to maxWireEntriesToVerify, short-circuit exact check

* chore(skip): address review comments — fix hash comment, remove redundant guard, drop budget alias, dedupe exact-compatibility check
2026-05-29 11:31:20 +01:00
Divanshu Chauhan (divkix) 00f585969d feat: recognize Sparkle experimental flags (varyParams, optimisticRouting, cachedNavigations) (#1655)
* feat(check): recognize Sparkle experimental flags in CONFIG_SUPPORT

* test(check): add tests for Sparkle experimental flags

* feat(config): warn when cachedNavigations is set without cacheComponents

* test: address ask-bonk review on cachedNavigations tests

- Remove redundant mockRestore() calls (afterEach handles it)
- Add negative test cases for cachedNavigations not set / false
- Match existing swcEnvOptions test style (warn.mock.calls.find())
2026-05-29 11:27:42 +01:00
James Anderson 88b1152eb2 fix(app-router): include static-sibling info in SSR response (#1525) (#1686)
Next.js's loader-tree dynamic-segment tuple includes a `staticSiblings`
list (the static sibling segment names at the dynamic URL level) so the
client router can decide whether a cached prefetch of a dynamic route
can be reused when navigating to a static sibling URL. vinext was not
emitting this metadata, so the static-siblings e2e suite failed all four
substring assertions against the RSC payload.

This change:

- Adds `computeAppRouteStaticSiblings(allRoutes, matchedRoute)` to the
  app route graph. Ported from Next.js's `getStaticSiblingSegments` in
  the next-app-loader. For each dynamic URL level in the matched route,
  it collects the names of routes whose corresponding segment is
  static and whose preceding URL prefix matches literally.
- Pre-computes the result per route at entry-generator time
  (`buildRouteEntries` in app-rsc-manifest) so the runtime carries a
  static list instead of recomputing for every request.
- Threads it through `AppPageRouteWiringRoute` and emits it on the
  wire as a new `__staticSiblings` metadata key when non-empty. The
  Flight serializer already spreads the elements record into the
  outgoing payload, so the key lands on the RSC response unchanged.

The new `tests/app-static-siblings.test.ts` covers the helper's
sibling-collection rules (cross-route-group, same-directory, deeply-
nested non-leak, dedup) and asserts `buildAppPageElements` emits
`__staticSiblings` on dynamic routes and omits it when empty — matching
the four sub-cases of Next.js's static-siblings e2e suite.

Ported from Next.js:
test/e2e/app-dir/static-siblings/static-siblings.test.ts

Refs cloudflare/vinext#1328
v0.0.54
2026-05-29 10:05:43 +01:00
James Anderson 6d4dd949f6 test(link): cover Pages Router onClick/preventDefault semantics (#1470) (#1685)
Adds regression coverage mirroring Next.js's
`test/e2e/new-link-behavior/index.test.ts` so the Pages Router `<Link>`
shim is guarded against ever regressing on:

  1. `onClick` firing on click with the synthetic event
  2. `event.preventDefault()` inside `onClick` cancelling the Link's
     own client-side navigation (no router.push, no history mutation,
     no popstate dispatch)

The unit-level invariants in the current Link shim match Next.js's
`linkClicked` ordering — call user onClick, check defaultPrevented,
only navigate if not prevented — so these tests pass against the
current implementation and lock that behaviour in place.
2026-05-29 09:56:12 +01:00
James Anderson 0859b07b96 test(pages-router): regression test for /api/* dispatch when middleware runs (#1477) (#1687)
The Next.js Deploy Suite flagged `test/e2e/proxy-request-with-middleware`
as a Pages Router failure where API routes appeared to return 500 when a
middleware was present. The reported failure cannot be reproduced
against the prod-server: GET, POST, query strings, custom request
headers, the bare `/api` index handler, and middleware-injected request
headers all return 200 today.

The existing `pages-basic` fixture explicitly excludes `/api` from its
middleware matcher, so the existing E2E tests never drive this
combination directly. Add a focused regression test that builds a
tmpdir Pages Router fixture whose middleware DOES match `/api/*`,
boots the prod-server, and asserts the full matrix above.

The Next.js fixture's actual API handler proxies via `req.pipe(...)`,
which depends on Node `IncomingMessage` stream methods that vinext's
prod-server does not yet expose on the `req` object created by
`createPagesReqRes`. That's a separate Node-compat gap (closer to
#1338) and is out of scope for this regression coverage — leaving a
test that locks down the middleware/API handoff so the deploy suite's
underlying claim is no longer ambiguous.
2026-05-29 09:55:57 +01:00
Jerry Zhao 5b58cb9be9 refactor: move normalizePathSeparators to utils/path (#1606)
* refactor: move normalizePathSeparators to utils/path

* update from other pr

---------

Co-authored-by: James <james@eli.cx>
2026-05-29 08:37:32 +00:00
Jerry Zhao 879698b0bc refactor(static-file-cache): reuse normalizePathSeparators for path handling (#1604) 2026-05-29 09:29:36 +01:00
James Anderson 1d26b2b229 fix(shims/script): emit <link rel="stylesheet"> for next/script stylesheets prop (#1646)
Refs #1517.

The vinext `next/script` shim ignored the `stylesheets` prop, so an
`<Script src="/x.js" stylesheets={['/x.css']} />` element emitted only the
`<script>`/preload and silently dropped the associated stylesheet (and
worse, leaked the prop onto the rendered `<script>` as a `stylesheets="..."`
attribute on the beforeInteractive branch).

Mirror the App-Router branch of Next.js's component
(`.nextjs-ref/packages/next/src/client/script.tsx:309-313` and
`:48-59`):

- SSR: call `ReactDOM.preinit(href, { as: 'style' })` for each entry —
  React Float hoists `<link rel="stylesheet">` into `<head>`.
- Client load path (`loadClientScript` + `handleClientScriptLoad`): same
  preinit preferred; fall back to direct `document.head.appendChild` of
  `<link rel="stylesheet">` when `ReactDOM.preinit` is unavailable.
- Destructure `stylesheets` out of `rest` everywhere so it never lands
  as an attribute on the emitted `<script>`.
- Add `stylesheets` to the `RESERVED` set used by the hoisted-script
  attribute collector for inline beforeInteractive scripts.

Scope: stylesheets prop only. Nonce propagation (the other half of #1517)
is already handled across SSR (`buildBeforeInteractiveScriptProps`,
`ReactDOM.preload`) and client (`loadClientScript`) paths — see the
existing "Script nonce resolution" suite. Bootstrap-script preinit is a
separate, larger change tracked under #1328.

Tests: extend `tests/script.test.ts` with a `Script stylesheets prop`
suite covering SSR emission, multi-entry lists, prop leakage on the
rendered `<script>`, omitted/empty lists, and the imperative
`handleClientScriptLoad` path.
2026-05-28 21:18:17 +01:00
James Anderson a6a279509c fix(shims): throw Pages Router parity error from unstable_retry (#1448) (#1670)
Closes the Pages Router parity gap noted as a follow-up in #1206. When
`unstable_catchError`'s boundary is rendered under the Pages Router,
`unstable_retry()` now throws Next.js's verbatim error message
("`unstable_retry()` can only be used in the App Router. Use `reset()`
in the Pages Router.") instead of calling App Router's `refresh()`
(which is a no-op there and leaves the user stuck on the error).

Detection mirrors Next.js's own implementation in
`packages/next/src/client/components/catch-error.tsx`: the inner class
component reads `RouterContext` via `static contextType`. The wrapper
stays a pure JSX factory so existing introspection-style unit tests
that invoke it as a bare function continue to work.

Regression test ported from
`test/e2e/app-dir/catch-error/catch-error.test.ts` —
"should throw when unstable_retry is called on Pages Router".
2026-05-28 21:16:51 +01:00
James Anderson f4687b3537 fix(app-router): treat module-only Vite ref errors as action-not-found (#1340) (#1668)
When a server action id resolved from request headers carries the
`#<exportName>` suffix (e.g. `/app/foo.ts#bar`), `loadServerAction()`
splits the id at `#` and calls `requireModule(file)` with the module
path only. `@vitejs/plugin-rsc`'s reference-validation virtual module
therefore emits `[vite-rsc] invalid server reference '/app/foo.ts'`,
omitting the `#<exportName>` portion. The previous match in
`isServerActionNotFoundError` compared the full actionId against the
Vite error string, so missing/stale references surfaced as a generic
500 instead of the Next.js-compatible 404 with the
`x-nextjs-action-not-found` header.

Also accept the pre-`#` module-path form for both the dev-time
`[vite-rsc] invalid server reference '<id>'` and prod-time
`server reference not found '<id>'` error shapes.

Adds a focused unit test reproducing the dev-mode case and integration
tests asserting that throwing `notFound()` from a server action returns
404 (both fetch and progressive form paths), porting fixture from
Next.js: test/e2e/app-dir/actions/app/server/form.js.
2026-05-28 21:12:59 +01:00
James Anderson c2f9f5b53f fix(app-router): cache pages with revalidate=Infinity/false (#1487) (#1666)
* fix(app-router): cache pages with revalidate=Infinity/false (#1487)

App Router pages exporting `revalidate = Infinity` (or `revalidate = false`,
which resolves to Infinity in segment config) were re-rendered on every
request: the HTML response policy returned `shouldWriteToCache: false`, and
the cache-write policy rejected non-finite revalidate values outright. The
downstream Cache-Control header was correct (1y s-maxage), but vinext itself
never served identical bytes for repeat requests inside the same process.

This change treats `revalidate = Infinity` as "cache indefinitely" rather
than "never write to cache":

- `resolveAppPageHtmlResponsePolicy` now writes the cached HTML/RSC bundle
  in production and reports `MISS` on first render, matching the standard
  ISR write flow. Dev mode continues to emit `STATIC` with no cache write.
- `resolveAppPageCacheWritePolicy` accepts `Infinity` as a valid revalidate
  interval; only `null`, `NaN`, and non-positive values reject the write.

The MemoryCacheHandler (used by tests and as the default) already handles
Infinity correctly: `revalidateAt = now + Infinity` keeps the entry fresh
forever until `revalidatePath`/`revalidateTag` invalidates it.

Adds two production-server regression tests:

- `export const revalidate = 60` returns HIT with identical timestamp on
  the second request (covers the standard finite case).
- `export const revalidate = Infinity` returns HIT with identical timestamp
  on the second request (covers the previously broken indefinite case).

Refs #1487. Other symptoms listed in the issue (`unstable_cache`, fetch
cache directives, force-static, force-no-store, on-demand revalidate) are
out of scope here and tracked separately.

* test(app-page-response): update Infinity revalidate assertions

Production + revalidateSeconds: Infinity now writes to the ISR cache
(cacheState: "MISS", shouldWriteToCache: true). Update the existing
assertion to match, and add a dev-mode case asserting Infinity stays
as a no-write STATIC response in development.
2026-05-28 21:12:23 +01:00
James Anderson 2354ca6e60 test(trailing-slash): pin core enforcement contract for App Router (#1332) (#1635)
* test(trailing-slash): pin core enforcement contract for App Router (#1332)

Adds focused integration tests against a dev-server fixture built from
app-basic with a minimal `next.config.ts` overriding `trailingSlash`.

The core enforcement contract documented in Next.js
test/e2e/trailing-slashes and test/e2e/app-dir/trailingslash was already
implemented across the dev server, prod-server, app-rsc-handler, and the
deploy worker entry by #1395 and #1413, but no end-to-end test asserted
the full contract end-to-end through the dev server. These regression
tests close that gap so future refactors of the trailing-slash redirect
or `<Link>` normalisation paths fail loudly.

Coverage:
- trailingSlash: true
  - GET /about → 308 Location: /about/
  - GET /about/ → 200
  - <Link href="/about"> renders href="/about/"
- trailingSlash: false (default)
  - GET /about/ → 308 Location: /about
  - GET /about → 200
  - <Link href="/about"> renders href="/about" (no trailing slash)

Refs #1332.

* test(trailing-slash): address bonk review nits

- Rename tests/trailing-slash-1332.test.ts → tests/trailing-slash.test.ts
  to match repo naming convention (the issue ref lives in the header
  comment and describe titles).
- Switch to the shared `startFixtureServer` helper from tests/helpers.ts;
  drop the local `startServer` and the now-unused `createServer` / `Server`
  imports.
- Tighten the second describe title to "trailingSlash: false" — the
  fixture explicitly sets `false`, not omits the field. The default-vs-
  explicit behaviour is identical today, so the merged-name was misleading.
- Document why we keep `fs.cpSync` rather than `createIsolatedFixture`:
  app-basic's node_modules carries fixture-local symlinks
  (fake-context-lib, fake-css-lib, …) that `createIsolatedFixture` would
  break by replacing node_modules with a workspace symlink, and the
  isolated copy also gets its own `.vite` optimizer cache (preventing
  races against the workspace cache used by other tests). Verified
  empirically: the bot-suggested `createIsolatedFixture` swap reproduces
  500s on every request, mirroring the rationale already captured in
  tests/favicon-short-circuit.test.ts.

Refs #1332.

* test(trailing-slash): bump 200-serve timeouts to 30s for dev-mode compile

CI showed both 200-serve cases hitting the 5s default while the dev server
was compiling the /about route on first hit. Match the headroom we already
use elsewhere (e.g. tests/app-router.test.ts).

* style: apply biome formatter to trailing-slash.test.ts
2026-05-28 21:07:58 +01:00
James Anderson 5d9548dc92 fix(pages-router): invoke Document.getInitialProps so docProps reach SSR (#1633)
* fix(pages-router): invoke Document.getInitialProps so docProps reach SSR (#1361)

`pages/_document.tsx` files that override `static async getInitialProps`
to inject extra props were rendered with an empty `this.props`, because
both the dev-server and the production pages response builder created
the Document element with `React.createElement(DocumentComponent)` and
never called the hook.

The Next.js async-modules e2e fixture
(`test/e2e/async-modules/pages/_document.jsx`) uses exactly that pattern
to surface a `docValue` from `await Document.getInitialProps(ctx)` plus
a top-level `await` constant. PR #1381 (issue #1361) fixed the class
construction crash, but the deploy-suite continued to fail
"csr async page modules" because `<div id="doc-value">` rendered empty.

This change adds a small `loadUserDocumentInitialProps` helper used by
both the Pages Router dev-server (`streamPageToResponse` shell and the
custom-error-page shell) and the production response builder
(`buildPagesShellHtml`). It invokes the override (if any) and spreads
the resolved props on the Document element, mirroring Next.js's
`render.tsx` `<Document {...htmlProps} {...docProps} />` call. The
helper short-circuits when the user did not override the base shim, so
the existing fast path keeps the same number of awaits.

Reference: vercel/next.js packages/next/src/server/render.tsx
(`loadDocumentInitialProps`, `documentElement`).

Tests:
- Adds a new pages-router production e2e case that builds a
  `_document.tsx` with `static async getInitialProps` + top-level
  `await`, plus a custom `404.tsx` that uses top-level `await`, and
  asserts the resolved values reach the rendered HTML.
- Unit-tests `loadUserDocumentInitialProps` directly for the override,
  no-override, and throwing-override cases.

Refs #1361

* fix(pages-router): address bonk review on Document.getInitialProps helper

Two changes from review feedback on PR #1633:

1. Cache the base getInitialProps reference at module level. The previous
   helper did `await import("vinext/shims/document")` on every request to
   compare identity — unnecessary per-request work and an extra await on
   the fast path where the user has no override. Switched to a static
   import + module-scoped constant so the identity check is a synchronous
   reference compare. No-override callers now resolve with one less await.

2. Let user `getInitialProps` errors propagate. Next.js's `loadGetInitialProps`
   does not catch — a throw surfaces as a 500 to the caller. The previous
   version logged-and-swallowed the error and returned null, which
   silently erased docProps on every failing render and made user bugs
   harder to find. vinext now matches Next.js's contract.

Updated the corresponding unit test to assert the throw propagates rather
than that the helper resolves to null.

Refs #1361, #1633
2026-05-28 21:06:28 +01:00
James Anderson 809218f6c4 fix(pages-router): mark app routes as detected on prefetch (#1526) (#1653)
* fix(pages-router): mark app routes as detected on prefetch (#1526)

In a hybrid Pages + App Router app, when the Pages Router prefetches a
`<Link href>` whose target is actually an App Router route, Next.js marks
the route on the Pages Router singleton with
`router.components[urlPathname] = { __appRouter: true }` (driven by the
`_bfl` bloom filter at packages/next/src/shared/lib/router/router.ts:2525).
The Next.js deploy test `test/e2e/app-dir/app/index.test.ts` ("should
successfully detect app route during prefetch") asserts this via
`window.next.router.components["/dashboard"]`.

Vinext previously did not expose `components` and did not record App Router
prefetch targets, so the assertion never resolved.

This commit:

- adds a shared `components` map (via `Symbol.for` for module-split safety)
  on the Pages Router singleton, mirrored onto `window.next.router`,
- threads the App Router prefetch manifest into the Pages Router client
  entry so the same matcher Link uses for App Router auto-prefetch can run
  in Pages-only-entry pages,
- marks the target on `components` with `{ __appRouter: true }` from both
  `Router.prefetch` and `<Link>` Pages-mode prefetch when the target
  matches the App Router manifest.

* fix(app-route-detection): drop unused exports flagged by knip

Both `matchesAppRoute` and `PagesRouterComponentsMap` are only used
inside this module — knip rightly flagged them as unused exports.
Internalize both.
2026-05-28 21:03:25 +01:00
James Anderson 3ff06784a0 fix(app-router): forbidden()/unauthorized() escalate past intermediate layouts (#1547) (#1647)
When a deep page called `forbidden()`/`unauthorized()`/`notFound()` and the
intermediate layout segments had no matching boundary file, vinext's
page-error fast path wrapped the resolved root boundary in *all* of the
route's layouts. That left the intermediate layout's chrome ("Dynamic with
Layout") rendered next to the boundary fallback, diverging from Next.js
where the nearest ancestor boundary owns the entire fallback subtree.

`renderPageSpecialError` now resolves the deepest layout-level boundary
via `resolveAppPageParentHttpAccessBoundary` and slices the layouts to
`[0..boundaryLayoutIndex]`, so layouts beneath the boundary owner stop
rendering. When the route-level boundary file lives next to the page
(not aligned to a layout), all layouts are kept as before.

Ported the Next.js regression cases from
`test/e2e/app-dir/forbidden/basic/forbidden-basic.test.ts` and
`test/e2e/app-dir/unauthorized/basic/unauthorized-basic.test.ts`.
2026-05-28 21:00:56 +01:00
James Anderson cd62cb2ebb fix(app-router): honor experimental.staleTimes in client prefetch cache (#1490) (#1660)
* fix(app-router): honor experimental.staleTimes in client prefetch cache (#1490)

The App Router's client-side prefetch cache previously used a hard-coded
30s TTL and ignored `experimental.staleTimes` from next.config. As a
result, users could not extend (or shorten) how long prefetched route
segments were considered fresh, breaking parity with Next.js'
`test/e2e/app-dir/app-client-cache/client-cache.experimental.test.ts`.

Surface `experimental.staleTimes.{dynamic,static}` through
`ResolvedNextConfig` and inject it into the client bundle as
`process.env.__NEXT_CLIENT_ROUTER_{DYNAMIC,STATIC}_STALETIME` (matching
the Next.js variable names plumbed by `build/define-env.ts`). The
prefetch cache TTL in `shims/navigation.ts` now reads the static value
at module load time, converting seconds to ms.

Defaults mirror Next.js (`dynamic: 0`, `static: 300`). When the env var
is absent — primarily in unit tests that import the module outside the
plugin's `define` pipeline — we fall back to vinext's historical 30s
default rather than the Next.js 300s so existing tests keep passing.

Refs: .nextjs-ref/packages/next/src/client/components/router-reducer/reducers/navigate-reducer.ts
Refs: .nextjs-ref/packages/next/src/build/define-env.ts

* review: address bot feedback on staleTimes PR

- Remove invokeLoaderSideEffects scope creep (belongs to #1500 / PR #1657)
- Reject negative staleTimes at resolution time alongside Number.isFinite,
  matching the seconds < 0 guard in resolvePrefetchCacheTtl
- Drop unused __NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME define; vinext does
  not yet distinguish prefetch kinds, so the value was never consumed
2026-05-28 20:59:44 +01:00
James Anderson 90a09df893 fix(build): invoke webpack loader side effects to land process.env mutations (#1500) (#1657)
Some Next.js webpack loaders mutate `process.env.X = ...` at compile
time, expecting the value to be visible to other modules during the
same build. vinext doesn't run the webpack loader pipeline, so those
env mutations never happened and downstream code (defines,
`NEXT_PUBLIC_*`, server-side reads) saw `undefined`.

Walk the rules collected from the user's `webpack(config)` function
and invoke each referenced loader once with a dummy source. Loaders
that only mutate `process.env` get a chance to land their changes in
the shared Node process. Failures are swallowed since vinext doesn't
use the loader's transform output. Well-known framework loaders
(next-babel-loader, @next/mdx, next/dist/build/webpack/*) are skipped
to avoid pulling in webpack-runtime-dependent code at probe time.
2026-05-28 20:57:21 +01:00
James Anderson c1a6adc19a fix(routing): treat @children as transparent so explicit page wins over catchall (#1535) (#1659)
In Next.js, the `@children` directory is special: it provides the
layout's `children` prop rather than acting as a parallel slot.
`app/foo/@children/page.tsx` should therefore register a real page
route at `/foo` and take priority over a sibling `[...catchAll]`
catch-all. Previously vinext excluded all `@`-prefixed directories
from the page scan, so `@children/page.tsx` was hidden and `/` (or
`/nested`) was either served by the catch-all or failed to resolve
when no `default.tsx` existed.

Three small changes restore Next.js parity:

- Let `@children` directories through the page-scan exclusion so the
  page file at `@children/page.tsx` registers as a route.
- Strip a trailing `@children` segment in `fileToAppRoute` so the
  route is anchored at the parent directory — sibling `@slot`
  directories remain owned (not inherited) and layout/boundary
  discovery is sourced from the parent.
- Skip `@children` in `discoverParallelSlots` and
  `hasParallelSlotDirectory` so it never appears in
  `parallelSlots` (matching Next.js' types-plugin behaviour).

Ported from Next.js: test/e2e/app-dir/parallel-routes-catchall-children-slot/
https://github.com/vercel/next.js/blob/canary/test/e2e/app-dir/parallel-routes-catchall-children-slot/parallel-routes-catchall-children-slot.test.ts

References Next.js' `normalizeAppPath` and `normalize-catchall-routes`
which both treat `@children` as a non-matchable slot:
- packages/next/src/shared/lib/router/utils/app-paths.ts
- packages/next/src/build/normalize-catchall-routes.ts
- packages/next/src/build/webpack/plugins/next-types-plugin/index.ts

Fixes #1535.
2026-05-28 20:54:32 +01:00
James Anderson 1671a46c35 fix(app-router): dedupe action Set-Cookie headers by name (#1481) (#1665)
Multiple `cookies().set(name, ...)` calls on the same name inside a server
action emitted multiple Set-Cookie response headers, diverging from
Next.js's `MutableRequestCookiesAdapter`, whose underlying `ResponseCookies`
Map collapses repeated sets to the final value per name.

Apply `dedupePendingCookies` at every cookie-emitting action exit (form
action redirects, fetch action redirects, fetch action responses) so the
last write per name wins and insertion order is preserved.

Reference: packages/next/src/server/web/spec-extension/adapters/request-cookies.ts
Refs #1481.
2026-05-28 20:53:04 +01:00
James Anderson 2d9f3ffc36 fix(app-router): accept icons.other as single descriptor (#1492) (#1667)
Next.js's `metadata.icons.other` accepts either a single
`IconDescriptor` or an array of them, but `MetadataHead` iterated
it directly and threw `TypeError: metadata.icons.other is not iterable`
when given a single object. That crash bubbled up into the page
render so no `<link>` tags (favicon, shortcut, apple, custom) reached
the head at all for any page declaring `icons.other` as an object.

Normalize `metadata.icons.other` to an array before iterating, widen
its type to `OtherIconDescriptor | OtherIconDescriptor[]`, and also
forward the optional `type` attribute so descriptors like
`{ rel: "mask-icon", url, type: "image/svg+xml" }` round-trip
correctly. Ported coverage from
`test/e2e/app-dir/metadata-icons/metadata-icons.test.ts`.

Refs cloudflare/vinext#1492
2026-05-28 20:13:04 +01:00
James Anderson 33be785d43 fix(app-router): allow draftMode() reads inside cache scopes (#1489) (#1669)
Calling `await draftMode()` and reading `.isEnabled` inside a `"use cache"`
or `unstable_cache()` callback now works the same as Next.js: the
non-mutating reads succeed and reflect the `__prerender_bypass` cookie,
while only the side-effecting `enable()` / `disable()` calls throw when
invoked inside a cache scope.

Previously vinext threw eagerly on `draftMode()` itself, which caused
fixtures such as `app-static`'s `unstable-cache/dynamic` page (which
reads `(await draftMode()).isEnabled` inside the cached function) to
surface as empty/undefined values in the Next.js deploy suite.

Ported from `.nextjs-ref/packages/next/src/server/request/draft-mode.ts`
(`getDraftModeProviderForCacheScope` + `trackDynamicDraftMode`).
2026-05-28 20:12:13 +01:00
James Anderson d61c5cbafe fix(app-router): propagate cookies/headers from no-JS server actions (#1483) (#1673)
When a progressive (no-JS) server action POST runs without redirecting, the
pending `cookies().set(...)` / `draftMode().enable()` mutations made during
the action were dropped on the floor — the form-state result returned from
`handleProgressiveServerActionRequest` never read them out of the
request-scoped headers context, and the subsequent page rerender never
flushed them onto the response.

Mirror Next.js' `res.setHeader('set-cookie', ...)` flush in
`action-handler.ts` / `app-render.tsx`: capture pending cookies, the draft
cookie, and the resolved revalidation kind at the end of the non-redirect
action path, expose them on the form-state result, then append them to the
rerender response (and the `x-action-revalidated` marker) in
`app-rsc-handler`. Falls back to rebuilding the response when its headers are
immutable so cookies still ride a `redirect()` issued during the rerender.

Fixes #1483.
2026-05-28 20:11:34 +01:00
James Anderson 51a63131b5 test(pages-router): regression coverage for URL-encoded CSS paths (#1472) (#1675)
Adds focused tests verifying that the static-asset layer serves CSS
files when the browser percent-encodes special characters in the path:

* `tests/serve-static.test.ts` — three cases against `tryServeStatic`:
  the cache fast path with an encoded URL, the slow path with an
  encoded URL, and the literal-character pathname that the request
  pipeline produces after `normalizePathnameForRouteMatchStrict` runs.

* `tests/pages-css-url-encoding.test.ts` — full build-and-serve test
  for the Pages Router that imports `my@style.css` and `with space.css`
  from `pages/index.tsx`, then asserts every emitted stylesheet link
  resolves to a 200 after `encodeURI` is applied (matching browser
  behaviour).

All three tests pass against the current implementation: `tryServeStatic`
decodes percent-encoded pathnames before cache lookup, and the cache
indexes files by their literal on-disk names. These tests document the
contract and guard against future regressions.

Refs cloudflare/vinext#1472
2026-05-28 20:09:27 +01:00
James Anderson 76fe5d8b05 fix(pages-router): render custom pages/500 on SSR throw (#1676)
When getServerSideProps (or any other render-time code) threw in the
production server entry, vinext collapsed the response into a plain
"Internal Server Error" text body. Next.js instead renders the user's
custom pages/500.tsx (with pages/_error.tsx as a fallback). Match that
behaviour so frameworks that rely on custom error pages — and the
Next.js getserversideprops deploy suite — see the expected output.

The catch block in `_renderPage` now re-renders through the same entry
using `pages/500.tsx` (or the `_error` route) with status 500. A new
`__isInternalErrorRender` guard prevents infinite recursion if the error
page itself throws; data (`/_next/data/...`) requests still short-circuit
to the plain text body since they can't return HTML.

Mirrors Next.js base-server.ts `renderToResponseImpl` 500 fallback. The
dev server already renders custom 500/error pages via `renderErrorPage()`
— this aligns prod with that behaviour and adds explicit regression
coverage for both paths via a new gssp-throw fixture.

Refs #1458
2026-05-28 20:08:37 +01:00
James Anderson 98c8286fdc test(pages-router): shallow Router.push bypasses redirect for as (#1522) (#1681)
Port the Next.js "should not apply client router filter on shallow" test
(test/e2e/app-dir/app/index.test.ts) so we lock in vinext's behaviour:
`Router.push(url, as, { shallow: true })` must update history to `as`
(/redirect-1) without fetching the page HTML, even when `as` matches a
server-side `redirects` rule from next.config.js.

vinext already produces the correct behaviour — `performNavigation`
skips `runNavigateClient` when `shallow` is true, so the server-side
redirect table never runs and `window.history.pushState` lands on
`as`. The test guards against future regressions (e.g. introducing a
Next.js-style client router bloom filter without exempting shallow
updates) and serves as the parity counterpart to Next.js's own bypass
in `_bfl` in packages/next/src/shared/lib/router/router.ts.

Refs #1522.
2026-05-28 20:06:54 +01:00
James Anderson 3e7d7f8f8b fix(build): inline process.env.NEXT_DEPLOYMENT_ID for client and worker bundles (#1538) (#1683)
User code such as `new Worker(new URL('./w.ts', import.meta.url))` reads
`process.env.NEXT_DEPLOYMENT_ID` from inside the worker scope, but vinext
only defined the internal `__VINEXT_DEPLOYMENT_ID` mirror — leaving the
public Next.js identifier as `undefined` in every browser-side bundle.

Mirror Next.js' webpack DefinePlugin behavior (see
packages/next/src/build/define-env.ts) and statically inline the value
into the global Vite `define`. The same map is applied to client, SSR,
RSC and Vite worker bundles, so workers transparently see the deployment
id without needing a globalThis bridge (which can't be shared across
the main-thread / worker boundary anyway).

When no deploymentId is configured, inline `false` — the same fallback
Next.js uses, so feature checks like `if (process.env.NEXT_DEPLOYMENT_ID)`
remain dead-code eliminated.
2026-05-28 20:06:23 +01:00
Nathan Nguyen 7be428dbc3 feat(app-router): support inline CSS parity (#1595)
* feat(app-router): support inline CSS parity

App Router production builds ignored Next.js experimental.inlineCss, so HTML responses kept stylesheet links, next/font CSS lived in a second style tag, and Next-style RSC requests with RSC: 1 plus _rsc could return HTML.

The missing invariant was that inlineCss changes the production CSS delivery boundary: non-RSC HTML gets inlined style resources, RSC payloads keep CSS bodies out, and client navigations must not reintroduce duplicate stylesheet resources for CSS already present inline.

Resolve the config flag into the generated RSC entry, collect emitted CSS assets into an inline manifest for Node and Workers production, rewrite matching React stylesheet links into hoistable style tags, merge next/font CSS into the first inline style with a fallback path, and recognize Next-style RSC requests.

Regression coverage now ports the upstream app-inline-css behavior at production-browser level and adds focused tests for request normalization, stream rewriting, font merging, and fallback emission.

* feat(app-router): preserve inline CSS import ordering

Inline CSS font merging could prepend generated font rules before a stylesheet import. CSS imports must stay at the beginning of their stylesheet, so that ordering caused imported styles to be ignored when experimental.inlineCss and local font CSS were combined.

Keep import-sensitive stylesheet preambles untouched and let the existing font fallback style carry the font rules instead. Add stream-helper coverage for the import case.

* feat(app-router): harden inline CSS review edges

Inline CSS rewriting only saw complete link tags in a single decoded chunk and treated rel as an exact value. That left valid stylesheet links un-inlined when rel had multiple tokens or when streaming split the tag across chunks.

The production manifest injection also assumed the RSC worker bundle was always at dist/server/index.js, so custom rscOutDir builds missed the inline CSS manifest.

Buffer incomplete link tags across stream flushes, match stylesheet as a rel token, and inject the manifest into the configured RSC output entry. Add regressions for the streaming and custom-output cases.

* feat(app-router): match inline CSS cleanup semantics

Client navigation cleanup only pruned links whose rel was exactly stylesheet and whose precedence marker used data-precedence. That diverged from the server inline CSS rewrite, so tokenized rel values or legacy precedence links could survive after navigation as duplicate stylesheet resources.

The fix moves the cleanup into a testable helper, reuses shared HTML token-list matching for server and browser paths, accepts both precedence marker forms, and only buffers split link tags when an inline CSS manifest is present.

Regression coverage now covers browser cleanup and non-inlineCSS streaming chunk granularity.

* feat(app-router): harden inline CSS HTML rewriting

Inline CSS rewriting could prepend SSR font CSS ahead of namespace-bearing stylesheets and could treat stylesheet-like text inside script bodies as real link tags. That violates CSS ordering constraints and corrupts streamed script text when experimental.inlineCss is enabled.

The stream rewrite now treats @namespace as an unsafe preamble, skips link replacement inside raw-text and comment regions, and buffers incomplete rewrite boundaries across flushes. Regression coverage pins namespace fallback, complete script text, split script text, and unterminated script text.

* test(e2e): specify junction type for fs.symlink to support Windows

* refactor(app-router): drop write-only __PAGE__ wire marker

Every outgoing App Router payload carried `__PAGE__: true` in its wire
metadata, but nothing in the runtime ever read it. Its only consumer was
an inline-css E2E assertion checking that a dynamic navigation returned an
RSC payload rather than HTML, so the marker added permanent per-response
wire overhead with no behavioural effect.

The `__route` key is already present on every payload and proves the same
thing: the response carries page metadata. Remove the marker key, its type
field, and its re-export, and point the unit and E2E assertions at
`__route` instead.

* perf(app-router): skip inline-css manifest scan on the streaming hot path

The tick-buffered SSR transform recomputed `Object.keys(manifest).length`
on every flush through `rewriteInlineCssStylesheetLinks`, even when inline
CSS was disabled and the manifest empty. Streaming flushes are a hot path,
so this ran per chunk of every response for no benefit.

Compute the manifest-present flag once at transform creation and reuse it
to gate both the split-link boundary buffering and the link rewrite, so
non-inline-css responses skip the rewrite entirely. Also document the
shared-lastIndex constraint on the module-level rewrite regexes and the
startup/build-time population contract for `__VINEXT_INLINE_CSS__`.

* fix(app-router): forward SSR script nonce to inline-css <style> tags

Sites running `Content-Security-Policy: style-src 'nonce-…'` saw the
inlined `<style>` blocks blocked at parse time and rendered unstyled
when `experimental.inlineCss` was enabled. The `<link rel="stylesheet">`
tags the feature replaces aren't subject to inline-style CSP, but the
new inline blocks are — and React Fizz typically doesn't put a nonce on
the `<link>`, so the rewrite path had no nonce to carry over.

Thread the SSR-time `scriptNonce` through `createTickBufferedTransform`
into `rewriteInlineCssStylesheetLinks`, and prefer the link's own nonce
when present (otherwise fall back to the SSR nonce). Add unit coverage
for the SSR-only, link-only, and missing-nonce cases.

Also replace `html.toLowerCase().lastIndexOf("<link")` in
`splitTrailingIncompleteLinkTag` with a forward `g+i` regex scan so the
streaming hot path no longer allocates a lowercased copy of every flush
(can be tens of KB on large responses).

* chore(check): register experimental.inlineCss as supported

So `vp check` advertises App Router CSS inlining alongside the other
experimental flags. Notes that next/font CSS is folded into the first
inline `<style>` block.

---------

Co-authored-by: James <james@eli.cx>
2026-05-28 18:17:06 +00:00
James Anderson 9e049261e1 fix(otel): inject experimental.clientTraceMetadata into SSR head (#1644)
* fix(otel): inject experimental.clientTraceMetadata into SSR head (#1494)

When `experimental.clientTraceMetadata` is configured in next.config, read
the active OpenTelemetry context via the registered propagator and emit
`<meta name="..." content="...">` tags in the SSR HTML head for each
allow-listed key. Both App Router and Pages Router are covered (dev and
prod servers). `@opentelemetry/api` is resolved as an optional peer at
runtime, so apps without OTel get a zero-cost no-op.

Mirrors Next.js: packages/next/src/server/lib/trace/utils.ts and
packages/next/src/server/app-render/make-get-server-inserted-html.tsx.

* fix(otel): drop unused getOpenTelemetryTraceData export

knip flagged the helper as unused — it is only consumed internally by
`getClientTraceMetadataHTML`. Keep it module-private.

* fix(otel): normalize clientTraceMetadata allow-list to undefined-only

Pick one convention for the optional allow-list across the App Router
pipeline (was mixing `string[] | null` and `string[] | undefined`).
Drops the redundant `?? null` / `?? undefined` coercions and aligns
every server-side type with `ResolvedNextConfig.clientTraceMetadata`,
which is `string[] | undefined`.

Also adds a resolveNextConfig test asserting that an array passed via
experimental.clientTraceMetadata is preserved verbatim, non-string
entries are filtered, and unset / non-array values resolve to
undefined.
2026-05-28 17:44:59 +01:00
James Anderson 5bcbee60e0 fix(app-router): isolate global-not-found chunk to fix CSS cascade (#1549) (#1654)
When `app/global-not-found.tsx` is defined, route-miss 404s render that
module standalone (it ships its own `<html>`/`<body>` and replaces the
root layout). Previously the entry registered global-not-found.tsx as a
static `import * as`, which co-located its CSS with the root layout's CSS
in a single chunk. Lightningcss then dropped overlapping declarations
between the two stylesheets as dead code, so any rule global-not-found
defined that the layout also defined was silently removed — breaking the
CSS cascade for 404s.

Switching the entry to `() => import("…/global-not-found.tsx")` puts the
module in its own JS chunk and lets the SSR pipeline (and `Resources`
metadata) treat its CSS independently of the rest of the app. The
fallback renderer now accepts a `loadGlobalNotFoundModule` loader (cached
per worker) instead of an eagerly-imported module.

Also adds a regression test asserting the SSR markup for `/does-not-exist`
links only global-not-found's stylesheet — never the root layout's — so
the cascade can never resolve to the wrong color.

Ported from Next.js: test/e2e/app-dir/initial-css-order/initial-css-order.test.ts
2026-05-28 16:32:19 +01:00
James Anderson 9f3ae31f49 fix(app-router): propagate unstable_rootParams to actions and route handlers (#1452) (#1652)
`setRootParams` was only called after the post-action route match, so
server actions, progressive (form) actions, and route handlers all ran
before the unified request context's `rootParams` slice was populated.
User code calling `unstable_rootParams()` from those contexts therefore
saw `undefined` instead of the matched root layout's params.

Seed `setRootParams` from a pre-action route match against the current
cleanPathname so that:
- route handlers observe rootParams during dispatch
- server actions observe rootParams while the action runs and during
  the page rerender that follows a successful action
- `"use cache"` functions invoked from any of those contexts read
  rootParams from the unified request context

The legacy post-rewrite `setRootParams` call is preserved so the value
is refreshed if `afterFiles`/`fallback` rewrites land on a different
route (and consequently a different set of root param names).
2026-05-28 16:30:07 +01:00
James Anderson b5da92e717 fix(app-router): drop space before /> in streamed error meta tags (#1491) (#1651)
When notFound() or redirect() is called from inside a Suspense boundary
the error surfaces after the shell has already streamed, so the not-found
/ redirect intent is communicated to the client via inline <meta> tags
injected into the head section of the stream.

vinext was emitting these as `<meta name="robots" content="noindex" />`
(with a space before the self-closing slash), but Next.js serializes them
via React's HTML renderer, which produces `<meta ... content="..."/>`
without the space. The Next.js navigation tests assert on that exact
substring, so this mismatch caused ~5 deploy-suite failures.

Drop the extra space so the streamed meta tags match Next.js byte-for-byte,
and add ported regression tests against the suspense fixtures.

Ref: packages/next/src/server/app-render/make-get-server-inserted-html.tsx
Ref: test/e2e/app-dir/navigation/navigation.test.ts (SEO describe block)
2026-05-28 16:29:22 +01:00
James Anderson bdc6fe0935 fix(build): forward pageExtensions to Vite resolve.extensions (#1502) (#1649)
When the user configured `pageExtensions` with values beyond Vite's
defaults (e.g. `["platform.tsx", "tsx", "mdx"]`), extensionless imports
of files with those extensions failed to resolve and the build crashed
with `Custom deploy script failed: undefined (1)`.

Mirror Next.js / Turbopack `resolveExtensions` semantics: prepend the
configured `pageExtensions` (each prefixed with `.`) to Vite's default
extension list, preserving the user's priority so e.g. `.web.tsx`
resolves before `.tsx`.

Ported from Next.js: test/e2e/app-dir/resolve-extensions/

Refs: cloudflare/vinext#1502
2026-05-28 16:04:32 +01:00
James Anderson 15fbe66c47 test(pages-router): regression coverage for edge runtime & OG image API routes (#1338) (#1648)
Adds Pages Router fixtures and dev + production integration tests for the
two scenarios reported as failing in the Next.js Deploy Suite:

- `export const config = { runtime: 'edge' }` API route returns a Web
  Response (issue #1338 case 1 — edge API routes were observed as 500).
- `next/og` `ImageResponse` with `runtime: 'edge'` inside a Pages Router
  API route returns `image/png` (issue #1338 case 2 — OG routes were
  observed as 404).

Ports route handlers from `next.js/test/e2e/edge-pages-support/app/pages/api/hello.js`
and `next.js/test/e2e/og-api/app/pages/api/og.js`. The existing
implementation already wires both code paths correctly via
`handlePagesApiRoute` and the `vinext:og-inline-fetch-assets` plugin; this
PR locks in coverage so a Pages Router-only build cannot silently regress
either path.

Refs #1338
2026-05-28 15:58:51 +01:00
James Anderson 34c8669182 fix(config): implement compiler.define / compiler.defineServer (#1638)
* feat(config): implement compiler.define and compiler.defineServer (#1496)

Forward `compiler.define` to Vite's top-level `define` (applies to both
client and server bundles) and `compiler.defineServer` to non-client
environments only via a `configEnvironment` hook, matching Next.js
Webpack `DefinePlugin` semantics. Values are JSON-stringified at config
resolution time so they slot directly into Vite's substitution format.

Refs Next.js: packages/next/src/build/define-env.ts.

Fixes #1496

* fix(config): reject compiler.define keys that collide with built-ins

Mirrors Next.js (`packages/next/src/build/define-env.ts`) — throw when a
user-provided `compiler.define` or `compiler.defineServer` key would
silently overwrite an internal define (e.g. `process.env.NODE_ENV`,
`__NEXT_*`, `__VINEXT_*`) or when `define` and `defineServer` define the
same key. Without this, a misconfigured project would produce subtly
wrong output instead of failing fast.

Addresses /bigbonk review on #1638.
2026-05-28 15:45:55 +01:00
James Anderson f6e1525e22 fix(pages-router): throw clear error on non-serializable gSP/gSSP props (#1478) (#1642)
When `getStaticProps` or `getServerSideProps` returned props containing
non-JSON-serializable values (e.g. `Date`, `Map`, class instances), vinext
silently rendered an empty page instead of surfacing an error. This ports
Next.js's `isSerializableProps` check from `packages/next/src/lib/is-serializable-props.ts`
and invokes it from `pages-page-data.ts` and `dev-server.ts` after the
redirect/notFound short-circuits, mirroring `render.tsx` (~lines 982 and
1200). The thrown `SerializableError` is caught by the existing per-request
error boundary, which returns a 500 with a Next.js-style message naming the
offending key.
2026-05-28 15:44:13 +01:00
Nathan Nguyen 5e90f16a56 fix(app-router): preserve push autoscroll across refresh (#1602)
Calling router.push() and router.refresh() in the same transition could leave vinext on the current page instead of committing the pushed route. That diverged from Next.js and broke the default autoscroll target for the pushed page.

The refresh path dispatched a current-route RSC refresh before the nested push transition could finish scheduling, so the refresh superseded the intended navigation.

Track App Router push/replace scheduling for the current task, keep refresh cache invalidation, and skip only the overtaking current-route refresh. Add Next parity coverage for refresh, server-action refresh, focus targets, fragments, hoisted children, and metadata routes.
2026-05-28 14:20:04 +01:00
한만욱 07be579048 test(app-router): cover clean replace after search load (#1626) 2026-05-28 14:16:35 +01:00
James Anderson a0bebe0353 test(metadata): regression test for #1493 (dynamic icon hrefs with metadataBase) (#1643)
Locks in the fix from #1436: when `metadataBase` is configured (on a parent
layout) and `generateImageMetadata` produces multiple dynamic icon /
apple-icon images, the rendered `<link>` href values must stay relative,
matching Next.js behavior in
test/e2e/app-dir/metadata-dynamic-routes/index.test.ts ("should support
generate multi images with generateImageMetadata").

The existing unit-level coverage in features.test.ts verifies MetadataHead
output directly. This adds an integration test through the full pipeline
(applyFileBasedMetadata -> MetadataHead) covering route groups, dynamic
segments, and parent-layout metadataBase inheritance — the exact shape of
the failing Next.js deploy test in #1493.

Refs #1493
2026-05-28 14:15:40 +01:00
James Anderson c8b8fc3370 fix(cache): updateTag throws outside Server Action (#1485) (#1641)
Match Next.js semantics: `updateTag` from `next/cache` must throw when
called outside a Server Action context (e.g. in a Route Handler or
during render), and only the in-action invariant invokes the cache
tag invalidation.

Detect the headers access phase ("action") via the existing shim and
throw the canonical error message otherwise. Existing in-action
behavior (immediate tag expiry via the active cache handler) is
preserved.
2026-05-28 14:13:20 +01:00
James Anderson f75845ef14 fix(pages-router): emit page scripts with defer in <head> by default (#1636)
* fix(pages-router): emit page scripts with defer in <head> by default

Next.js' Pages Router emits page scripts with the `defer` attribute in
`<head>` when `experimental.disableOptimizedLoading` is false (the
default). vinext emits `<script type="module">` (which already defers
implicitly), but upstream tests assert the literal `defer` attribute
and were failing against the deploy suite.

Add `defer` to module scripts emitted by `collectAssetTags` when
`experimental.disableOptimizedLoading` is not enabled. Surface the
flag in `ResolvedNextConfig` so prod-server respects an explicit
opt-out. Browser behaviour is unchanged (module scripts already
defer), but parity tests now pass.

Fixes #1519.

* test(e2e): update hydration regex to allow defer attribute

The script tag regex in `tests/e2e/cloudflare-pages-router/hydration.spec.ts`
required `type="module"` to be immediately followed by `src="…"`, but the
optimized-loading fix inserts a `defer` attribute between them. Relax the
regex to allow any whitespace-separated attributes between `type="module"`
and `src` so future attribute additions don't break it either.
2026-05-28 14:12:15 +01:00
James Anderson 53a97e2002 fix(navigation): stabilize Pages Router useParams snapshot for SSR (#1639)
`useParams()` / `useSearchParams()` / `usePathname()` from `next/navigation`
work as cross-router compat shims under Pages Router, deriving their state
from `getPagesNavigationContext()` published by `next/router`. React's
`useSyncExternalStore` requires `getServerSnapshot` to return a stable
reference (Object.is) across calls in a single render — otherwise React
logs:

  "The result of getServerSnapshot should be cached to avoid an infinite loop"

and may re-render until the snapshots stabilize, which is wasteful and a
hydration-mismatch hazard. The SSR branch of `getPagesNavigationContext`
was returning a fresh object each call.

Cache the shape on a `WeakMap` keyed on the ALS-isolated SSR context, so
the same `{ pathname, searchParams, params }` shape (with reference-stable
`params` / `searchParams`) is returned for every hook call inside a single
request. The WeakMap key is per-request, so concurrency safety is
preserved.

Adds a Vitest unit assertion (reference equality across repeated SSR
calls) and a Playwright regression matching the Next.js deploy-suite case
(`test/e2e/app-dir/use-params/use-params.test.ts` — 'should work on pages
router'): a Pages Router dynamic page using `useParams()` inside a fixture
that also has an `app/` directory must render the matched param after
hydration.

Refs #1466
2026-05-28 14:11:36 +01:00