Repository navigation
fix(app-router): enforce dynamicParams = false for route handlers - #4125
james-elicx merged 20 commits into
Conversation
|
/bigbonk review for issues. Review head SHA 340d365. You have an 8-minute time limit. |
@vinext/cloudflare
create-vinext-app
@vinext/types
vinext
@cloudflare/workers-response-store
commit: |
|
Performance benchmarksCompared 0 improved · 0 regressed · 7 within ±1.5%
View detailed results and traces 🟢 improvement · 🔴 regression · ⚫ change below 1.5% · paired base/head |
| } | ||
| } | ||
|
|
||
| const unlistedParamsResponse = await rejectUnlistedParams(); |
There was a problem hiding this comment.
The static-param gate runs after the ISR read, so an existing entry for an unlisted path still returns 200. This is reachable when a persisted data-cache entry was written before dynamicParams = false (or before this fix) because appIsrRouteKey() contains only the pathname/route suffix, not the build ID; Next checks fallback === false && !isPrerendered before its response cache lookup. Please validate before accepting a cache hit, or otherwise prove the cached path belongs to the current generated-param set.
There was a problem hiding this comment.
Declining this one. Route-cache keys include the build ID (appIsrCacheKey prefixes app:v2:${buildId}), so an entry stored for params that a later deploy removes isn't read by that deploy. That only fails with a pinned generateBuildId plus a cache that persists across deploys. Pages and image metadata routes behave the same way, and docs/reference/differences.mdx documents it as a design decision. Calling generateStaticParams on every hit would undo the runtime-generator tradeoff documented there. In 34bce3b the docs sentence now names route handlers too, and the PR's known limitations list it.
| route, | ||
| searchParams: resolvedSearchParams, | ||
| }); | ||
| return withRouteMissCacheControl(routeHandlerResponse); |
There was a problem hiding this comment.
This now treats a header authored by an ordinary Route Handler as trusted framework state. A handler can return x-vinext-route-miss: 1; this branch then relabels the request /404 and forces no-store. In split mode, completed-response admission occurs inside the response stage before this outer call, so a cacheable forged response can also be stored with the marker and replayed. Strip this reserved header from user Route Handler responses before cache admission, while preserving the marker added by markRouteMissResponse().
There was a problem hiding this comment.
Fixed in 34bce3b. stripAppRouteHandlerRouteMissMarker() drops the marker from the handler's own response right after assertSupportedAppRouteHandlerResponse. It runs on both the live path (app-route-handler-execution.ts) and background regeneration (app-route-handler-cache.ts), so the marker can't reach the request stage or the route cache. Immutable headers, such as on a proxied fetch() response, are rebuilt. markRouteMissResponse() adds its marker later, so it's unaffected. Tests cover mutable and immutable live responses and a regenerated write, and fail without the fix.
| params: {}, | ||
| }); | ||
| setRootParams({}); | ||
| return renderUnmatchedRoute(); |
There was a problem hiding this comment.
Resetting navigation/root params is not enough to make this equivalent to an unmatched route. Before this callback, the outer handler installed route soft tags and dispatchAppRouteHandler() installed the rejected handler’s fetchCache, revalidate, and force-dynamic defaults. Any fetch or use cache call made while rendering the root not-found therefore inherits the rejected Route Handler’s cache policy/tags; a real unmatched URL reaches renderUnmatchedRoute() without those settings. Reset the fetch-cache state for the fallback in both direct and response-stage paths.
There was a problem hiding this comment.
Fixed in 34bce3b. rejectUnlistedParams clears the fetch soft tags, cache mode, revalidate and force-dynamic default before rendering the 404. It's in dispatch, so this covers both the direct and the response-stage paths. A test records the request context inside renderNotFound for a fetchCache: "force-cache", revalidate: 60 handler, and it fails without the reset.
|
Review: 3 findings. Posted 3 actionable inline comments. |
c19e547 to
34bce3b
Compare
|
/bigbonk review for issues. Review head SHA 34bce3b. You have an 8-minute time limit. |
| const handlerResult = tracedResult.handlerResult; | ||
| let { dynamicUsedInHandler, response } = handlerResult; | ||
| assertSupportedAppRouteHandlerResponse(response); | ||
| response = stripAppRouteHandlerRouteMissMarker(response); |
There was a problem hiding this comment.
The marker is stripped before response completion, but this codebase explicitly permits stream producers to mutate headers while the body is consumed (see the snapshot at lines 451-454). A handler can return a stream whose pull() re-adds x-vinext-route-miss; completeAppRouteHandlerResponse() then rebuilds from the post-EOF headers, so the forged marker still reaches the ISR write/shared-cache admission and the outer trusted-marker branch. I verified the same Web Response sequence locally: delete before arrayBuffer(), re-add from pull(), and the completed response contains the marker. Strip again from the completed response immediately before policy/cache handling, and do the same after completion in background regeneration; please add a late-stream mutation test.
There was a problem hiding this comment.
Fixed in ee463fc. The strip now runs on the completed response, right after completion and before the policy snapshot, ISR write and cacheability admission. It also runs on completed.response before the background-regeneration cache write. The tests use a lazy stream (highWaterMark: 0) whose pull() re-adds the marker, on both the live and regeneration paths. They fail with the earlier pre-completion strip.
|
Review: 1 findings. Posted 1 actionable inline comment. |
34bce3b to
ee463fc
Compare
|
/bigbonk review for issues. Review head SHA ee463fc. You have an 8-minute time limit. |
| // Response.redirect() and similar responses have immutable headers. | ||
| const headers = new Headers(response.headers); | ||
| headers.delete(VINEXT_ROUTE_MISS_HEADER); | ||
| return new Response(response.body, { |
There was a problem hiding this comment.
Rebuilding an immutable proxied response with this plain init drops Workerd-only response state. This repository's request-tracing.ts explicitly uses new Response(response.body, response as ResponseInit) because Workerd copies cf, webSocket, and encodeBody; losing the latter can double-encode a body, and losing webSocket breaks an upgrade response whenever the upstream happened to return this reserved header. Rebuild from response as ResponseInit, then delete the marker from the new mutable headers.
There was a problem hiding this comment.
Fixed in 27782a6. The immutable-header fallback now rebuilds with new Response(response.body, response as ResponseInit), as updateResponseHeader in request-tracing.ts does, so Workerd keeps cf, webSocket and encodeBody. It then deletes the marker from the new headers. The rebuild also keeps the fully-buffered body metadata and the Link-header provenance. A unit test checks that the original response is the init and the marker is gone. It fails with the plain-init rebuild.
|
Since last review: 1 resolved, 0 still open, 1 new. Posted 1 actionable inline comment. |
ee463fc to
27782a6
Compare
|
/bigbonk review for issues. Review head SHA 27782a6. You have an 8-minute time limit. |
| if (!hasGenerateStaticParams) { | ||
| return handler.dynamic === "force-static" || handler.dynamic === "error"; | ||
| } | ||
| return !hasNonStaticAppRouteHandlerMethods(handler); |
There was a problem hiding this comment.
This exemption is only valid when at least one generated path actually prerenders and the mixed-method route bails out. When generateStaticParams() returns [], Next still emits the dynamic route with fallback: false (its build has no generated path on which a non-static method can trigger a bailout), so every parameter returns 404. Here hasNonStaticAppRouteHandlerMethods() makes vinext run the handler for every parameter instead, contradicting the PR’s stated empty-generator parity. Please distinguish an empty generated set before applying the mixed-method exemption and add a production test for dynamicParams = false, generateStaticParams: () => [], and POST.
There was a problem hiding this comment.
Fixed in f7c3136. I confirmed it with a local next@16.2.7 next build --webpack / next start. With dynamicParams = false and generateStaticParams: () => [], POST, PUT and OPTIONS exports all build as ● with fallback: false and 404 every param. With one generated path, a POST export builds as ƒ and serves. force-dynamic and revalidate = 0 serve even with []. The policy (resolveAppRouteHandlerStaticParamsEnforcement) now returns enforce-when-none-generated for production mixed-method routes, and dispatch runs the generator to decide. A production-mode dispatch test covers [] + POST (404, handler not run) and a generated path + POST (served). It fails without the fix. The PR's verification table has both cases.
|
Since last review: 1 resolved, 0 still open, 1 new. Posted 1 actionable inline comment. |
27782a6 to
f7c3136
Compare
|
/bigbonk review for issues. Review head SHA f7c3136. You have an 8-minute time limit. |
| const enforcement = resolveAppRouteHandlerStaticParamsEnforcement(handler, isProduction); | ||
| if (enforcement === "skip") return null; | ||
| if (enforcement === "enforce-when-none-generated") { | ||
| const generated = await ( |
There was a problem hiding this comment.
When this first call returns [], execution falls through to validateAppPageDynamicParams(), which invokes the same generateStaticParams function again. That duplicates user data-fetching/side effects on every mixed-method miss, and a stateful generator can return [] first and rows second, causing vinext to admit a path even though Next’s single build-time result produced fallback: false. Please reuse the generated result for validation, or directly render the miss once this call has established that the result is empty; add a call-count assertion to the new test.
There was a problem hiding this comment.
Fixed in d0f0e4a. Once the single generateStaticParams call for a mixed-method route returns no rows, dispatch renders the miss directly and doesn't call validateAppPageDynamicParams. The generator now runs exactly once per request on both branches. The test asserts one call for the empty generator (404) and one for the generated one (served). It fails on the previous head.
|
Since last review: 1 resolved, 0 still open, 1 new. Posted 1 actionable inline comment. |
f7c3136 to
d0f0e4a
Compare
|
/bigbonk review for issues. Review head SHA d0f0e4a. You have an 8-minute time limit. |
| const headers = new Headers(response.headers); | ||
| applyCdnResponseHeaders(headers, { cacheControl: NEVER_CACHE_CONTROL }); | ||
| headers.set(VINEXT_ROUTE_MISS_HEADER, "1"); | ||
| return preserveFullyBufferedBodyMetadata( |
There was a problem hiding this comment.
markRouteMissResponse() reconstructs the response but does not copy the renderer-owned Link provenance attached to response.headers. A rendered root not-found can carry CSS/preload links; after this wrapper, finalizeAppRscResponse() sees hasPostConfigLinkHeaders() as false, so a matching next.config Link header replaces those renderer links instead of being prepended. This affects both page and route-handler misses now that they share this helper. Please call copyLinkHeaderProvenance(response.headers, headers) before constructing the marked response, as the other response wrappers do.
There was a problem hiding this comment.
Fixed in 9165cc7. The wrapper code came from #4122, so I fixed it at the bottom of the stack in 3f99cdf and rebased. markRouteMissResponse() now copies Link provenance onto the marked response's headers. The provenance is a WeakMap keyed by the Headers object, so it's copied onto the final response, not the intermediate init. The request stage's immutable-headers fallback in withRouteMissCacheControl copies it too. Tests: the page miss keeps renderer Link provenance, and an end-to-end handler test on an immutable not-found expects config Link to be prepended before the not-found's own. Both fail without the fix.
|
Review: 1 findings. Posted 1 actionable inline comment. Targeted tests pass: 493 tests. |
d0f0e4a to
9165cc7
Compare
A route handler exporting dynamicParams = false with generateStaticParams ran for any param value. Next.js rejects unlisted params while routing and serves the unmatched-URL 404, so route handlers now do the same, using the routing-level not-found that dynamicParams page misses already use. Both misses share one marker, so the request stage reasserts the never-cache policy, shared-cache admission never stores the 404, and the request is traced as /404 rather than the rejected route.
… its own Like Next.js, a route handler's generateStaticParams sees no root params from the request, and its fetches add no tags or dynamic-fetch observations to the request the handler then serves. A stored route response also drops the framework's route-miss marker.
… dynamicParams miss
…st APIs or dynamic usage
…er's generateStaticParams
…rk unit and keep draft cookies on the miss
…n guard and request cache separate from the request
… work before checking its params
…erateStaticParams registers late
…tch memoization outside an on-demand revalidation
…taticParams A cached function a route handler's generateStaticParams calls reads draft mode as disabled, still fails to store what it computed after a caught connection() error, and "use cache: private" is rejected outside a request, as in Next.js. The generator no longer reads the request's private cache.
9d38011 to
a6a18de
Compare
|
/bigbonk review for issues Please review exact head |
There was a problem hiding this comment.
✅ Approved — No findings. The cache-scope changes since the last review (disabled draft mode in a cached function, connection() checking the cache scope first, and rejecting "use cache: private" in generateStaticParams) are correct and each has a regression test.
The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.
✅ All checks passed
🔒 Security: ✅ LGTM
The generator can't read the request's private cache, and its request APIs stay blocked. The route-miss marker still can't be forged by a handler's response.
📖 AGENTS.md: ✅ LGTM
Runtime logic stays in server/* and shims/*. The generated entry only adds thin wiring.
📋 Code Quality: ✅ LGTM
The cache-scope rules for a route handler's generateStaticParams are consistent across draftMode(), connection() and the private cache boundary.
⚡ Performance: ✅ LGTM
No new hot-path cost. The added checks are a cheap work-unit lookup.
📝 Documentation: ✅ LGTM
No documentation issues.
Reviewed commit: a6a18ded
|
LGTM! |
38 upstream commits. Conflicts resolved file by file, keeping the official code wherever upstream solved the same problem, and layering ours on top only where it adds behavior: - app-page-dispatch: upstream's routing-level dynamicParams miss (cloudflare#4122, cloudflare#4125, cloudflare#4634) replaces our boundary render, and its draft-mode skip supersedes ours (cloudflare#3547). Our parameter matching admission still gates the check. - action-owner-manifest: upstream's sourcemap-preserving rewrite (cloudflare#4679) replaces our MagicString fix; the file now equals upstream. - app-rsc-handler: upstream moved the unmatched-route render into a helper; our percent-escaping of the cache path match (670fa02) is re-applied there. - link / app-router-navigation: upstream's Cache Components-only dynamic shell (cloudflare#4660) combined with our static shell prefetch stages. - fetch-cache / cache / cache-runtime: upstream's cacheRead token (cloudflare#4642) threaded through our resume data cache reads. - deploy: our --mode support next to upstream's version annotations (cloudflare#4689). - prerender: upstream's forked prerender server (cloudflare#4687, cloudflare#4695) with our fallback-shell error handling; tests use `_prodServer: { port }`. - use-cache-callable: keeps the removal of the layout/template default exclusion from the Cache Components resume stack. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Summary
A route handler (
route.ts) that exportsdynamicParams = falsetogether withgenerateStaticParamsran for any param value. Pages and generated metadata images in the same segment already returned 404 for unlisted params, but a sibling route handler answered 200 with whatever it returned for the unlisted slug.Next.js gates these handlers on its prerender manifest (
build/templates/app-route.ts:fallback === false && !isPrerendered→NoFallbackError), so an unlisted param gets the unmatched-URL 404.This is stacked on #4122, which gives
dynamicParams = falsepage misses Next's routing-level not-found. The route handler 404 now goes through the same path. It supersedes #4123, which fixed the same gap independently. Its policy, tests and fixtures are ported here and use #4122's shared mechanism, with the gaps listed below closed.Fix
shouldEnforceAppRouteHandlerStaticParams()(app-route-handler-policy.ts) ports the cases where Next.js lists a route handler withfallback: false. Only the handler's own exports count, because layouts don't apply to route handlers.dynamicParams = falseandgenerateStaticParams.dynamic = "force-dynamic",revalidate = 0, or exporting POST/PUT/DELETE/PATCH/OPTIONS. Those methods only bail out while a generated path prerenders. So whengenerateStaticParamsreturns[], Next still lists the route withfallback: falseand 404s every param. vinext runs the generator for these routes to tell the two cases apart. WithoutgenerateStaticParams, onlyforce-static/errorroutes are listed, and they 404 every param.runtime = "edge"together withgenerateStaticParamsat build time.dispatchAppRouteHandler()checks params with the sharedvalidateAppPageDynamicParams()./x/public%2520postis admitted only when"public%20post"is listed.generateStaticParams. It still runs before the 400, auto-OPTIONS and 405 responses, as in Next.js.isAppRouteHandlerParamsMiss(), and routing decides draft mode as the dispatch does (the live headers context, then the request). An admitted match passesskipStaticParamsValidation, so the generator runs once.fetchCache(norevalidateor force-dynamic default), in a scope of its own.headers(),cookies(),connection()anddraftMode()(reading it included) reject there, as Next'sgenerate-static-paramswork unit makes them throw, so a generator can't list a param from the request. It runs in that work unit, soio()resolves andrevalidateTag()/revalidatePath()throw, as in Next, also from a"use cache"function the generator calls.cacheForRequest()values aren't shared between the generator and the request, and the generator memoizes its own fetches whichever branch runs it. Like Next's build store, it reads cached data even when the request is an on-demand revalidation, and its fetches carry the route handler's own implicit tags rather than the request pathname's. A cached function the generator calls keeps Next's cache-scope rules: it reads draft mode as disabled, a caughtconnection()error still fails it, and"use cache: private"is rejected outside a request. The generator never reads the request's private cache. Like Next'sAfterRunner, the generator'safter()work finishes before its params are checked, and a failed task fails the generation. Dynamic usage (ano-storefetch) stays out of the request, so a fallback rewrite's target isn't marked dynamic by the rejected handler's generator. It sees no root params from the request, because a route's own generator has no parent params, and its fetches add no tags, revalidate or dynamic-fetch observations to the request the handler then serves. For the "returns[]" case, a row counts only when it fills every pathname param and has no empty required segment, as in Next's static paths. A listed param named__proto__is admitted.draftMode().disable().renderNotFoundcallback for it. The handler's fetch defaults and soft tags (fetchCache,revalidate,dynamic) are cleared before it renders, as they are for an unmatched URL. Because the response is the not-found page, next.config headers meet it with page rules rather than the Route Handler collision rules from fix(app-router): resolve next.config header collisions with Route Handler headers like Next.js #4528, both directly and through the response stage. A redirect thrown while it renders (say, by the root layout) still counts as an application response, so it gets config headers like the same redirect on an unmatched URL.x-vinext-route-missheader that a handler's own response carries (for example a proxiedfetch()) is dropped after the response completes, so a header the body's producer adds while streaming is dropped too. It never reaches the request stage or the route cache, and a stored route response drops it when read.markRouteMissResponse()(route-miss-response.ts) now marks both page and route handler misses with fix(app-router): render dynamicParams misses as a routing-level not-found #4122'sx-vinext-route-missmarker. The request stage strips the marker, reasserts never-cache after config and middleware headers, and relabels the request trace as/404. Compared with fix(app-router): enforce dynamicParams = false for route handlers #4123, this:next.configCDN policy such asCloudflare-CDN-Cache-Control: public, …let response-stage admission store fix(app-router): enforce dynamicParams = false for route handlers #4123's route handler 404./404. The request had already recorded the matched route and the first value wins, so fix(app-router): enforce dynamicParams = false for route handlers #4123'ssetFrameworkRequestRoute("/404")calls did nothing. fix(app-router): render dynamicParams misses as a routing-level not-found #4122'sreplaceFrameworkRequestRoute()relabels it.Verified against real Next.js 16.2.7 (in #4123:
next build --webpack/next start, andnext dev)dynamicParams=false+ gSPOPTIONSdynamic="force-dynamic",revalidate=0, or exportsPOSTPOST/PUT/OPTIONS, gSP returns[](checked locally withnext build --webpack/next start)force-dynamicorrevalidate=0, gSP returns[](same check)rewrites().fallback(checked with this PR's fixture shape)dynamic="force-static"/"error"[[...slug]]with gSP[{slug:["a"]}], request/Tests
tests/fixtures/app-basic/app/metadata-static-params/[slug]/data/route.tsmirrors the route-handler half of Next.js' own fixture for this case, including the encoded rows its sibling page and image use.dynamic-data/route.tsis the force-dynamic variant.tests/e2e/app-router/isr.spec.ts"route handlers honor dynamicParams=false" covers listed/encoded/unlisted params, OPTIONS, the not-found body and cache-control, force-dynamic being served, and draft mode skipping the check. Against fix(app-router): render dynamicParams misses as a routing-level not-found #4122's source alone, it fails (unlisted param → 200).segment-cache-dynamic-params.spec.tsadds adynamic-params-fallback/[slug]/data/route.tshandler with a fallback rewrite. A listed param reaches the handler, an unlisted one reaches the rewrite target (this fails before the fix with a 404), and in draft mode the handler answers the unlisted param. Runs in dev and production.tests/app-router-metadata-routes.test.ts.app-route-handler-policyandapp-route-handler-dispatch: decoded comparison, the optional catch-all, a cache hit skippinggenerateStaticParams, dev without gSP, edge runtime. The 404 also stays out of a split stage's shared cache under a public config CDN policy; this test fails without the storage veto. The 404 renders without the handler's fetch state, and a handler-set marker is dropped from live responses (mutable headers, immutable headers, and one the body's producer adds while streaming) and from regenerated ones. The generator runs without the request's root params and fetch state, with the handler'sfetchCachebefore an auto-OPTIONS response, memoizes a mixed-method generator's repeated fetch, reads its cached fetch during an on-demand revalidation, tags fetches with the route's implicit tags, keeps the cache-scope rules above, and ignores rows that list no concrete path. Each of these fails without its fix.app-rsc-handler: the route handler 404's never-cache policy, render context, single application of config headers and/404trace, both direct and through the response stage.Known limitations
request.headers,request.urlor search params, callingcookies()/headers(), or ano-storefetch. Next production serves those params, because its build-time prerender bails out and drops the manifest entry. vinext can't know this before running the handler.docs/reference/differences.mdx), a route-cache hit is served without the check unless the app has fallback rewrites, in which case routing runs the generator for every request, hits included. Cache keys include the build ID, so this only matters with a pinnedgenerateBuildIdand a cache that persists across deploys. The docs sentence now names route handlers too.dynamicParams = falseroute that rejects the param, Next resumes routing with the later fallback rewrites. vinext renders that route's 404. Like fix(app-router): render dynamicParams misses as a routing-level not-found #4122's other-dynamic-routes limitation, this needs routing to resume after a miss, which is left for a follow-up.generateStaticParamsstill runs with the request's root params and request APIs, and, outside fix(app-router): render dynamicParams misses as a routing-level not-found #4122's fallback-rewrite routing check, its fetch state. That predates this stack and is left for a follow-up.generateStaticParams: returning[]404s every param in vinext dev and prod. Next prod also 404s, but Next dev serves.