fix: memory leaks #5896
main fromrefs/pull/5896/head·merged by schiller-manuel(GitHub profile, opens in a new tab) Summary by CodeRabbit#
Chores
- Reworked server start/request flow with a centralized middleware pipeline, request-scoped start options, and guaranteed router cleanup.
Bug Fixes
- Stricter redirect validation and consistent serialized redirect responses.
- Accept header validation for HTML requests.
- Ensure injected-HTML listeners and stream cancellations/timeouts are cleaned up and errors return proper responses.
- Route loaders now use router origin for API requests.
Refactor
- On-demand server manifest loading and improved SSR state dehydration.
New Features
- Added the /users path to prerendering configuration.
Tests
- Removed prerendering tests/assertions for the users (and related deferred) routes.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: start-server-core
Caution
Review failed#
The pull request is closed.
Walkthrough#
Reworks the server start flow to build a per-request router via getRouter, merge startOptions with serialization adapters (including ServerFunctionSerializationAdapter), run a middleware pipeline that prioritizes server functions, perform SSR dehydration and header assembly, validate/serialize redirects (x-tsr-redirect), centralize error handling, and reset router on completion.
Changes#
Cohort / File(s) Change Summary Start handler core
packages/start-server-core/src/createStartHandler.tsReplace global fetch patching and inline router setup with request-scoped getRouter and requestStartOptions (merging startOptions and serialization adapters). Introduce runWithStartContext-based middleware pipeline, server-function-first handling, Accept header validation for HTML, on-demand start manifest loading, SSR dehydration and header assembly, x-tsr-redirect support and redirect validation, centralized error handling, and final router reset in finally. SSR stream cancellation
packages/router-core/src/ssr/transformStreamWithRouter.tsAllow passthrough stream to accept an optional onCancel hook, add cancel handling to the ReadableStream to mark destroyed and invoke onCancel, defer assignment and teardown of injected-HTML listener (stopListeningToInjectedHtml), wire final passthrough cancellation to stop listening and clear timeouts, and ensure cleanup runs in finally. E2E route loaders (use router origin for API calls)
e2e/react-start/basic/src/routes/users.$userId.tsx,e2e/react-start/basic/src/routes/users.tsx,e2e/solid-start/basic/src/routes/users.$userId.tsx,e2e/solid-start/basic/src/routes/users.tsxImport and use getRouterInstance/getRouter to obtain router and use router.options.originas baseURL for Axios/API requests instead of relative URLs; minor await/order adjustments.E2E Vite configs (prerender filter)
e2e/react-start/basic/vite.config.ts,e2e/solid-start/basic/vite.config.tsAdd /usersto prerender filter entries and remove an inline comment; no runtime behavior change beyond filter update.E2E prerendering tests
e2e/react-start/basic/tests/prerendering.spec.ts,e2e/solid-start/basic/tests/prerendering.spec.tsRemove assertions and test blocks that expected prerendered output for users (and deferred) pages; reduce coverage of those prerender checks. Sequence Diagram(s)#
sequenceDiagram participant Client participant Handler as createStartHandler participant ReqOpts as requestStartOptions participant Router participant Context as runWithStartContext participant Middleware as Middleware Pipeline participant ServerFn as Server Functions participant RouterExec as executeRouter participant SSR as SSR Dehydrate Client->>Handler: incoming HTTP request Handler->>ReqOpts: compute requestStartOptions (merge adapters) Handler->>Router: getRouter(ReqOpts) Router-->>Handler: configured router rect rgb(245,250,255) Handler->>Context: runWithStartContext(request) Context->>Middleware: execute middleware chain Middleware->>ServerFn: attempt server-function handling first alt server-fn handled ServerFn-->>Middleware: Response else Middleware->>RouterExec: executeRouter -> route resolution RouterExec-->>Middleware: route result / redirect / error end end alt Response ready Middleware->>SSR: dehydrate SSR state + collect headers SSR-->>Handler: final body + headers Handler-->>Client: final response else Redirect / Error Middleware-->>Handler: redirect/error response Handler-->>Client: redirect/error end Note over Handler,Router: finally -> reset router / cleanupsequenceDiagram participant Stream as PassthroughStream participant Listener as InjectedHTMLListener Stream->>Listener: subscribe (deferred assignment) Client->>Stream: consume alt Consumer cancels or times out Stream--xListener: onCancel -> stopListeningToInjectedHtml() end Listener-->>Stream: stop/cleanup invokedEstimated code review effort#
🎯 4 (Complex) | ⏱️ ~45 minutes
- Areas to focus on:
- router lifecycle and final cleanup (resetting router state)
- merging/deduplication of serialization adapters into requestStartOptions
- middleware ordering and server-function-first behavior
- redirect serialization,
x-tsr-redirectheader handling, and redirect validation - SSR dehydration, header collection, and response assembly
- stream cancellation and injected-HTML listener teardown in transformStreamWithRouter
Possibly related PRs#
- TanStack/router#5268 — related to marking server function fetchers as serializable and serializer types; intersects server-function serialization wiring.
- TanStack/router#5314 — modifies how serialization adapters are handled and registered in start/router flow.
- TanStack/router#5321 — changes merging/application of serializationAdapters between start options and router.options.
Suggested reviewers#
- chorobin
- tannerlinsley
Poem#
🐇 I hopped through start and stream with care, I stitched adapters, trimmed the snare, When callers cancel, listeners sleep, Redirects checked before they leap, Router reset — I bound my lair.
Pre-merge checks and finishing touches#
❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstringsto improve docstring coverage.Title check ❓ Inconclusive The PR title "fix: memory leaks" is vague and generic; it does not clearly specify which memory leaks are being fixed or what the primary change is. Consider a more specific title such as "fix: memory leaks in stream handling and router cleanup" to better convey the nature of the changes across the codebase. ✅ Passed checks (1 passed)
Check name Status Explanation Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
📜 Recent review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 01557d4efb2a23039492dfcea787cddcc7ccb3de and 08391ddbc1bbd8536dde41f39d50c34b54a8da1d.
📒 Files selected for processing (2)
e2e/react-start/basic/tests/prerendering.spec.ts(0 hunks)e2e/solid-start/basic/tests/prerendering.spec.ts(0 hunks)
Comment `@coderabbitai help` to get the list of available commands and usage tips.- Areas to focus on:
More templates
- tanstack-router-react-example-authenticated-routes
- tanstack-router-react-example-authenticated-routes-firebase
- tanstack-router-react-example-basic
- tanstack-router-react-example-basic-default-search-params
- tanstack-router-react-example-basic-devtools-panel
- tanstack-router-react-example-basic-file-based
- tanstack-router-react-example-basic-non-nested-devtools
- tanstack-router-react-example-react-query
- tanstack-router-react-example-basic-react-query-file-based
- tanstack-router-react-example-basic-ssr-file-based
- tanstack-router-react-example-basic-ssr-streaming-file-based
- tanstack-router-react-example-basic-virtual-file-based
- tanstack-router-react-example-basic-virtual-inside-file-based
- tanstack-router-react-example-deferred-data
- tanstack-router-i18n-paraglide
- tanstack-router-react-example-kitchen-sink
- tanstack-router-react-example-kitchen-sink-file-based
- tanstack-router-react-example-kitchen-sink-react-query
- tanstack-router-react-example-kitchen-sink-react-query-file-based
- tanstack-router-react-example-large-file-based
- tanstack-router-react-example-location-masking
- tanstack-router-react-example-navigation-blocking
- tanstack-router-react-example-quickstart
- tanstack-router-react-example-quickstart-esbuild-file-based
- tanstack-router-react-example-quickstart-file-based
- tanstack-router-react-example-quickstart-rspack-file-based
- tanstack-router-react-example-quickstart-webpack-file-based
- router-monorepo-react-query
- router-mono-simple
- router-mono-simple-lazy
- tanstack-router-react-example-scroll-restoration
- tanstack-search-validator-adapters
- tanstack-start-example-bare
- tanstack-start-example-basic
- tanstack-start-example-basic-auth
- tanstack-start-example-basic-cloudflare
- tanstack-start-example-basic-react-query
- tanstack-start-example-basic-static
- tanstack-start-bun-hosting
- tanstack-start-example-clerk-basic
- tanstack-start-example-convex-trellaux
- tanstack-start-example-counter
- tanstack-start-i18n-paraglide
- tanstack-start-example-large
- tanstack-start-example-material-ui
- tanstack-start-streaming-data-from-server-functions
- tanstack-start-example-supabase-basic
- tanstack-start-tailwind-v4
- tanstack-start-example-trellaux
- tanstack-start-example-workos
- tanstack-router-react-example-view-transitions
- tanstack-router-react-example-with-framer-motion
- tanstack-router-react-example-with-trpc
- tanstack-router-react-example-with-trpc-react-query
- tanstack-router-solid-example-authenticated-routes
- tanstack-router-solid-example-authenticated-routes-firebase
- tanstack-router-solid-example-basic
- tanstack-router-solid-example-basic-default-search-params
- tanstack-router-solid-example-basic-devtools-panel
- tanstack-router-solid-example-basic-file-based
- tanstack-router-solid-example-basic-non-nested-devtools
- tanstack-router-solid-example-basic-solid-query
- tanstack-router-solid-example-basic-solid-query-file-based
- tanstack-router-solid-example-basic-ssr-file-based
- tanstack-router-solid-example-basic-ssr-streaming-file-based
- tanstack-router-solid-example-basic-virtual-file-based
- tanstack-router-solid-example-basic-virtual-inside-file-based
- tanstack-router-solid-example-deferred-data
- tanstack-router-solid-i18n-paraglide
- tanstack-router-solid-example-kitchen-sink
- tanstack-router-solid-example-kitchen-sink-file-based
- tanstack-router-solid-example-kitchen-sink-solid-query
- tanstack-router-solid-example-kitchen-sink-solid-query-file-based
- tanstack-router-solid-example-large-file-based
- tanstack-router-solid-example-location-masking
- tanstack-router-solid-example-navigation-blocking
- tanstack-router-solid-example-quickstart
- tanstack-router-solid-example-quickstart-esbuild-file-based
- tanstack-router-solid-example-quickstart-file-based
- tanstack-router-solid-example-quickstart-rspack-file-based
- tanstack-router-solid-example-quickstart-webpack-file-based
- router-solid-mono-simple
- router-solid-mono-simple-lazy
- router-solid-monorepo-solid-query
- tanstack-router-solid-example-scroll-restoration
- tanstack-solid-router-search-validator-adapters
- tanstack-solid-start-example-basic
- tanstack-solid-start-example-basic-auth
- tanstack-solid-start-example-basic-cloudflare
- tanstack-solid-start-example-basic-netlify
- tanstack-solid-start-example-basic-nitro
- tanstack-start-example-basic-solid-query
- tanstack-solid-start-example-basic-static
- tanstack-solid-start-bun-hosting
- tanstack-solid-start-example-convex-better-auth
- tanstack-solid-start-example-counter
- tanstack-solid-start-i18n-paraglide
- tanstack-solid-start-example-large
- tanstack-solid-start-streaming-data-from-server-functions
- tanstack-solid-start-example-supabase-basic
- tanstack-solid-start-tailwind-v4
- tanstack-router-solid-example-view-transitions
- tanstack-router-solid-example-with-framer-motion
- tanstack-router-solid-example-with-trpc
@tanstack/arktype-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/arktype-adapter@5896@tanstack/directive-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/directive-functions-plugin@5896@tanstack/eslint-plugin-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/eslint-plugin-router@5896@tanstack/history
npm i https://pkg.pr.new/TanStack/router/@tanstack/history@5896@tanstack/nitro-v2-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/nitro-v2-vite-plugin@5896@tanstack/react-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router@5896@tanstack/react-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@5896@tanstack/react-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-ssr-query@5896@tanstack/react-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start@5896@tanstack/react-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-client@5896@tanstack/react-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-server@5896@tanstack/router-cli
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-cli@5896@tanstack/router-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-core@5896@tanstack/router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools@5896@tanstack/router-devtools-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools-core@5896@tanstack/router-generator
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-generator@5896@tanstack/router-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-plugin@5896@tanstack/router-ssr-query-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-ssr-query-core@5896@tanstack/router-utils
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-utils@5896@tanstack/router-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-vite-plugin@5896@tanstack/server-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/server-functions-plugin@5896@tanstack/solid-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router@5896@tanstack/solid-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-devtools@5896@tanstack/solid-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-ssr-query@5896@tanstack/solid-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start@5896@tanstack/solid-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-client@5896@tanstack/solid-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-server@5896@tanstack/start-client-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-client-core@5896@tanstack/start-plugin-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-plugin-core@5896@tanstack/start-server-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-core@5896@tanstack/start-static-server-functions
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-static-server-functions@5896@tanstack/start-storage-context
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-storage-context@5896@tanstack/valibot-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/valibot-adapter@5896@tanstack/virtual-file-routes
npm i https://pkg.pr.new/TanStack/router/@tanstack/virtual-file-routes@5896@tanstack/zod-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/zod-adapter@5896commit:
01557d4Actionable comments posted: 2
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 5ca33d7c4000478b5129aadf59edea90c100838f and d7735af93370bdf70ed22c66614ce578d62d94d9.
📒 Files selected for processing (1)
packages/start-server-core/src/createStartHandler.ts(2 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-11-02T16:16:24.898Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5732 File: packages/start-client-core/src/client/hydrateStart.ts:6-9 Timestamp: 2025-11-02T16:16:24.898Z Learning: In packages/start-client-core/src/client/hydrateStart.ts, the `import/no-duplicates` ESLint disable is necessary for imports from `#tanstack-router-entry` and `#tanstack-start-entry` because both aliases resolve to the same placeholder file (`fake-start-entry.js`) in package.json during static analysis, even though they resolve to different files at runtime.Applied to files:
packages/start-server-core/src/createStartHandler.ts
📚 Learning: 2025-10-01T18:30:26.591Z
Learnt from: schiller-manuel Repo: TanStack/router PR: 5330 File: packages/router-core/src/router.ts:2231-2245 Timestamp: 2025-10-01T18:30:26.591Z Learning: In `packages/router-core/src/router.ts`, the `resolveRedirect` method intentionally strips the router's origin from redirect URLs when they match (e.g., `https://foo.com/bar` → `/bar` for same-origin redirects) while preserving the full URL for cross-origin redirects. This logic should not be removed or simplified to use `location.publicHref` directly.Applied to files:
packages/start-server-core/src/createStartHandler.ts
🧬 Code graph analysis (1)
packages/start-server-core/src/createStartHandler.ts (5)
packages/router-core/src/ssr/ssr-server.ts (2)
getOrigin(227-239)attachRouterServerSsrUtils(100-225)
packages/start-client-core/src/client/ServerFunctionSerializationAdapter.ts (1)
ServerFunctionSerializationAdapter(5-16)
packages/start-storage-context/src/async-local-storage.ts (1)
runWithStartContext(15-20)
packages/start-server-core/src/router-manifest.ts (1)
getStartManifest(10-63)
packages/start-client-core/src/createServerFn.ts (2)
flattenMiddlewares(582-606)executeMiddleware(172-241)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Test
🔇 Additional comments (1)
packages/start-server-core/src/createStartHandler.ts (1)
83-125: Router lifecycle, SSR wiring, and redirect handling look solid.The refactored flow—lazy
getRouterinitialisation with memory history, per-requestrunWithStartContext, SSR setup viaattachRouterServerSsrUtils+dehydrate, and centralised redirect handling (including manualx-tsr-redirectresponses androuter.resolveRedirect) is coherent and addresses the previous global/patchy setup. Thefinallyblock that clearsrouter.serverSsrand drops the localrouterreference is an appropriate cleanup step for avoiding per-request SSR state retention.Also applies to: 137-234, 251-314
packages/start-server-core/src/createStartHandler.ts lines 127 to 135Outdated@@ -208,8 +122,14 @@208- status: 500,209- },210- )211- }122+ basepath: ROUTER_BASEPATH,123+ })124+ return router125+ }212126213- // if the startRoutesManifest is not loaded yet, load it once214- if (startRoutesManifest === null) {215- startRoutesManifest = await getStartManifest()127+ const startOptions: AnyStartInstanceOptions =128+ (await (await getEntries()).startEntry.startInstance?.getOptions()) ||129+ ({} as AnyStartInstanceOptions)130+ startOptions.serializationAdapters =131+ startOptions.serializationAdapters || []132+ // insert start specific default serialization adapters133+ startOptions.serializationAdapters.push(134+ ServerFunctionSerializationAdapter,135+ )⚠️ Potential issue | 🔴 Critical
Avoid per-request growth of
serializationAdapters(risk of memory leak).startOptions.serializationAdapters.push(ServerFunctionSerializationAdapter)mutates the options object on every request. IfstartInstance.getOptions()returns a shared object (which is likely), this will append the same adapter indefinitely, growing the array and causing duplicated work.Guard the push with a dedupe check so the adapter is only added once per options object:
- startOptions.serializationAdapters = - startOptions.serializationAdapters || [] - // insert start specific default serialization adapters - startOptions.serializationAdapters.push( - ServerFunctionSerializationAdapter, - ) + startOptions.serializationAdapters = + startOptions.serializationAdapters || [] + // insert start specific default serialization adapter once + if ( + !startOptions.serializationAdapters.includes( + ServerFunctionSerializationAdapter, + ) + ) { + startOptions.serializationAdapters.push( + ServerFunctionSerializationAdapter, + ) + }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const startOptions: AnyStartInstanceOptions = (await (await getEntries()).startEntry.startInstance?.getOptions()) || ({} as AnyStartInstanceOptions) startOptions.serializationAdapters = startOptions.serializationAdapters || [] // insert start specific default serialization adapter once if ( !startOptions.serializationAdapters.includes( ServerFunctionSerializationAdapter, ) ) { startOptions.serializationAdapters.push( ServerFunctionSerializationAdapter, ) }🤖 Prompt for AI Agents
In packages/start-server-core/src/createStartHandler.ts around lines 127 to 135, the code mutates startOptions.serializationAdapters on every request which can grow a shared array and leak memory; instead avoid mutating a potentially shared options object by either deduplicating before pushing or by replacing the array with a new one that includes the adapter only once: check if startOptions.serializationAdapters already contains ServerFunctionSerializationAdapter (by identity) and only add it if missing, or assign startOptions.serializationAdapters = [...(startOptions.serializationAdapters || []), ServerFunctionSerializationAdapter] only when not present so you never append duplicates to a shared array.@@ -253,2 +228,20 @@253- return err228+ throw err254229 }230+ },231+ )232+ return response233+ },234+ )235+236+ const flattenedMiddlewares = startOptions.requestMiddleware237+ ? flattenMiddlewares(startOptions.requestMiddleware)238+ : []239+ const middlewares = flattenedMiddlewares.map((d) => d.options.server)240+ const ctx = await executeMiddleware(241+ [...middlewares, requestHandlerMiddleware],242+ {243+ request,244+245+ context: requestOpts?.context || {},246+ },247+ )⚠️ Potential issue | 🔴 Critical
Server middleware mapping can prematurely terminate the pipeline when
.options.serveris missing.Both the request-level and route-level middleware pipelines map through
d.options.serverwithout filtering:- Lines 236‑239:
flattenMiddlewares(startOptions.requestMiddleware).map((d) => d.options.server) - Lines 345‑347 and 373‑376: similar pattern for route
server.middleware.
Since
executeMiddlewaretreats a falsymiddlewareas “end of chain” (if (!middleware) return ctx), any entry whereoptions.serverisundefinedwill stop processing and prevent later middlewares (includingrequestHandlerMiddlewareand the finalexecuteRouterhandler) from running. This is a correctness issue if any middleware is client‑only or conditionally defines a server handler.Filter out undefined server handlers before passing them to
executeMiddleware:- const flattenedMiddlewares = startOptions.requestMiddleware - ? flattenMiddlewares(startOptions.requestMiddleware) - : [] - const middlewares = flattenedMiddlewares.map((d) => d.options.server) + const flattenedMiddlewares = startOptions.requestMiddleware + ? flattenMiddlewares(startOptions.requestMiddleware) + : [] + const middlewares = flattenedMiddlewares + .map((d) => d.options.server) + .filter(Boolean)And similarly in
handleServerRoutes:- const middlewares = flattenMiddlewares( - matchedRoutes.flatMap((r) => r.options.server?.middleware).filter(Boolean), - ).map((d) => d.options.server) + const middlewares = flattenMiddlewares( + matchedRoutes.flatMap((r) => r.options.server?.middleware).filter(Boolean), + ) + .map((d) => d.options.server) + .filter(Boolean)This keeps the middleware chain intact even when some middlewares are client‑only or only define one side.
Also applies to: 345-347, 373-376
🤖 Prompt for AI Agents
In packages/start-server-core/src/createStartHandler.ts around lines 236-247 (and also at the similar sites around 345-347 and 373-376), the code maps middleware entries directly to d.options.server which can produce undefined entries and prematurely terminate executeMiddleware; update each middleware mapping to first map to d.options.server then filter out falsy/undefined handlers while preserving order (e.g., create an array of server handlers by mapping then filtering Boolean) before passing to executeMiddleware so client-only or undefined server handlers do not stop the chain.✅ Confirmed as addressed by @schiller-manuel
request middlewares only have .server() handler
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Search for middleware type definitions to understand the structure rg -n -A5 -B5 "type.*Middleware|interface.*Middleware" --type=ts # Also search for how middlewares are defined/created rg -n -C3 "requestMiddleware|defineMiddleware" --type=ts -g '!node_modules' -g '!dist' -g '!build'Length of output: 97719
@schiller-manuel Thank you for the clarification! You're absolutely right—request middlewares created with
createMiddleware({ type: 'request' })always have a.server()handler by design, sooptions.serverwill always be defined for those. I appreciate the correction.
🧬 Code Graph Analysis Results
File: packages/start-server-core/src/createStartHandler.ts
- Summary: The code constructs the middleware chain for a request by:
- Flattening any global request middlewares defined in startOptions.requestMiddleware.
- Mapping these flattened middlewares to their server-side handlers via d.options.server.
- Building a combined middleware stack that also includes requestHandlerMiddleware (which handles the actual request logic).
- Executing the chain with executeMiddleware, passing in the current Request and context.
- This demonstrates that, for request middlewares, only the .server() handlers are used when building the middleware chain.
- Summary: The code constructs the middleware chain for a request by:
File: packages/start-server-core/src/request-response.ts
- Summary: The requestHandler helper wraps a user-provided RequestHandler to:
- Create an H3Event from the incoming Request.
- Run the handler within a start-context-scoped environment (via runWithStartContext).
- Convert the result into a Response via h3_toResponse, ensuring proper integration with the H3 lifecycle.
- This clarifies how request handlers ultimately produce HTTP responses.
- Summary: The requestHandler helper wraps a user-provided RequestHandler to:
Actionable comments posted: 1
♻️ Duplicate comments (3)
packages/start-server-core/src/createStartHandler.ts (3)
348-350: Critical: Route middleware chain can terminate prematurely when.options.serveris missing.Similar to the request middleware issue, this maps
d.options.serverwithout filtering, which can produce undefined entries that prematurely stop middleware execution.Apply this diff:
const middlewares = flattenMiddlewares( matchedRoutes.flatMap((r) => r.options.server?.middleware).filter(Boolean), - ).map((d) => d.options.server) + ) + .map((d) => d.options.server) + .filter(Boolean)
376-378: Critical: Handler middleware chain can terminate prematurely when.options.serveris missing.This middleware mapping also lacks filtering for undefined
serverhandlers, creating the same chain termination risk.Apply this diff:
if (middleware && middleware.length) { middlewares.push( - ...flattenMiddlewares(middleware).map((d) => d.options.server), + ...flattenMiddlewares(middleware) + .map((d) => d.options.server) + .filter(Boolean), ) }
240-243: Critical: Middleware chain can terminate prematurely when.options.serveris missing.The middleware pipeline maps through
d.options.serverwithout filtering out undefined entries. SinceexecuteMiddleware(line 444) treats a falsymiddlewareas "end of chain" (if (!middleware) return ctx), any entry whereoptions.serverisundefinedwill stop the pipeline and preventrequestHandlerMiddlewarefrom running.Apply this diff:
const flattenedMiddlewares = startOptions.requestMiddleware ? flattenMiddlewares(startOptions.requestMiddleware) : [] - const middlewares = flattenedMiddlewares.map((d) => d.options.server) + const middlewares = flattenedMiddlewares + .map((d) => d.options.server) + .filter(Boolean)🧹 Nitpick comments (1)
packages/start-server-core/src/createStartHandler.ts (1)
257-268: Consider extracting duplicate manual redirect handling.The manual redirect response logic (lines 257-267 and 298-307) is duplicated. While the control flow is correct (handling already-resolved vs newly-resolved redirects), extracting this to a helper function would improve maintainability.
Example helper:
function createManualRedirectResponse(response: any) { return json( { ...response.options, isSerializedRedirect: true, }, { headers: response.headers, }, ) }Then replace both blocks with:
if (request.headers.get('x-tsr-redirect') === 'manual') { return createManualRedirectResponse(response) }Also applies to: 298-308
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between d7735af93370bdf70ed22c66614ce578d62d94d9 and a6494bd41bc14441fb23e0935596c9fd45ad1b89.
📒 Files selected for processing (1)
packages/start-server-core/src/createStartHandler.ts(2 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-01T18:30:26.591Z
Learnt from: schiller-manuel Repo: TanStack/router PR: 5330 File: packages/router-core/src/router.ts:2231-2245 Timestamp: 2025-10-01T18:30:26.591Z Learning: In `packages/router-core/src/router.ts`, the `resolveRedirect` method intentionally strips the router's origin from redirect URLs when they match (e.g., `https://foo.com/bar` → `/bar` for same-origin redirects) while preserving the full URL for cross-origin redirects. This logic should not be removed or simplified to use `location.publicHref` directly.Applied to files:
packages/start-server-core/src/createStartHandler.ts
🧬 Code graph analysis (1)
packages/start-server-core/src/createStartHandler.ts (6)
packages/router-core/src/ssr/ssr-server.ts (2)
getOrigin(227-239)attachRouterServerSsrUtils(100-225)
packages/start-client-core/src/client/ServerFunctionSerializationAdapter.ts (1)
ServerFunctionSerializationAdapter(5-16)
packages/start-server-core/src/index.tsx (2)
HEADERS(16-16)attachRouterServerSsrUtils(4-4)
packages/start-storage-context/src/async-local-storage.ts (1)
runWithStartContext(15-20)
packages/start-server-core/src/router-manifest.ts (1)
getStartManifest(10-63)
packages/start-client-core/src/createServerFn.ts (2)
flattenMiddlewares(582-606)executeMiddleware(172-241)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Test
- GitHub Check: Preview
🔇 Additional comments (2)
packages/start-server-core/src/createStartHandler.ts (2)
94-102: Excellent fix for the serializationAdapters memory leak!Creating a new array with the spread operator instead of mutating the shared
startOptions.serializationAdaptersproperly addresses the memory leak concern from the previous review.
314-318: Good practice: router cleanup in finally block.Ensuring
routeris set tonullin the finally block helps prevent memory leaks by allowing garbage collection after each request completes or errors.packages/start-server-core/src/createStartHandler.ts lines 179 to 186@@ -225,4 +169,18 @@169+170+ const supportedMimeTypes = ['*/*', 'text/html']171+ const isRouterAcceptSupported = supportedMimeTypes.some(172+ (mimeType) =>173+ splitRequestAcceptHeader.some((acceptedMimeType) =>174+ acceptedMimeType.trim().startsWith(mimeType),175+ ),176+ )225177226- // If there was a redirect, skip rendering the page at all227- if (router.state.redirect) {228- return router.state.redirect178+ if (!isRouterAcceptSupported) {179+ return json(180+ {181+ error: 'Only HTML requests are supported here',182+ },183+ {184+ status: 500,185+ },186+ )⚠️ Potential issue | 🟡 Minor
Use HTTP 406 instead of 500 for Accept header mismatch.
A 500 status indicates a server error, but rejecting an unsupported media type is a client request issue. HTTP 406 (Not Acceptable) is the standard status code when the server cannot satisfy the
Acceptheader.Apply this diff:
return json( { error: 'Only HTML requests are supported here', }, { - status: 500, + status: 406, }, )📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
return json( { error: 'Only HTML requests are supported here', }, { status: 406, }, )🤖 Prompt for AI Agents
In packages/start-server-core/src/createStartHandler.ts around lines 179 to 186, the response for requests that don't accept HTML currently returns HTTP 500; change the response status to 406 (Not Acceptable) to reflect that the client's Accept header cannot be satisfied. Update the json response call to use status: 406 and keep the error payload the same so the client receives the correct semantic HTTP status for an unsupported media type.github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: router-core
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between a6494bd41bc14441fb23e0935596c9fd45ad1b89 and 7b2bbfa205fd610fa08ed1705711d2fd08582f2b.
📒 Files selected for processing (1)
packages/router-core/src/ssr/transformStreamWithRouter.ts(4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Preview
- GitHub Check: Test
🔇 Additional comments (3)
packages/router-core/src/ssr/transformStreamWithRouter.ts (3)
38-48: LGTM! Clean cancellation propagation.The
onCancelparameter andcancel()handler provide a proper hook for cleanup when the stream is canceled, marking the passthrough as destroyed and propagating the cancellation signal.
141-143: LGTM! Proper subscription cleanup.Capturing the unsubscribe function in
stopListeningToInjectedHtmlenables proper cleanup of the event listener, preventing memory leaks from lingering subscriptions.
178-178: LGTM! Ensures cleanup on promise settlement.The
.finally()block ensures the subscription is cleaned up when the injected HTML promise settles, complementing the cancellation cleanup on line 106.Note: This means cleanup can occur via two paths (cancellation or promise settlement), but the optional chaining and typical unsubscribe idempotency make this safe.
@@ -96,4 +100,8 @@96100 timeoutMs?: number97101 },98102 ) {99- const finalPassThrough = createPassthrough()103+ let stopListeningToInjectedHtml: (() => void) | undefined = undefined104+105+ const finalPassThrough = createPassthrough(() => {106+ stopListeningToInjectedHtml?.()107+ })⚠️ Potential issue | 🟡 Minor
Consider clearing timeout on stream cancellation.
The
onCancelcallback properly unsubscribes from injected HTML events, but if the stream is canceled after the timeout is set (line 245), the timeout handle won't be cleared, potentially leaving a lingering timer.Additionally, note that
stopListeningToInjectedHtmlwill be called both here (on cancel) and in the.finally()block (line 178), resulting in double cleanup. While most unsubscribe functions are idempotent, this complexity could be error-prone.Consider this refactor to clear the timeout on cancel:
+ let timeoutHandle: NodeJS.Timeout | undefined let stopListeningToInjectedHtml: (() => void) | undefined = undefined const finalPassThrough = createPassthrough(() => { + if (timeoutHandle) { + clearTimeout(timeoutHandle) + } stopListeningToInjectedHtml?.() })And then move the
timeoutHandledeclaration from line 116 to here (removing it from line 116).Committable suggestion skipped: line range outside the PR's diff.
✅ Addressed in commits 5504347 to 7cfa14e
schiller-manuel(GitHub profile, opens in a new tab)replied on
packages/start-server-core/src/createStartHandler.tslines 240 to 251request middlewares only have .server() handler
coderabbitai[bot](GitHub profile, opens in a new tab)replied on
packages/start-server-core/src/createStartHandler.tslines 240 to 251🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Search for middleware type definitions to understand the structure rg -n -A5 -B5 "type.*Middleware|interface.*Middleware" --type=ts # Also search for how middlewares are defined/created rg -n -C3 "requestMiddleware|defineMiddleware" --type=ts -g '!node_modules' -g '!dist' -g '!build'Length of output: 97719
@schiller-manuel Thank you for the clarification! You're absolutely right—request middlewares created with
createMiddleware({ type: 'request' })always have a.server()handler by design, sooptions.serverwill always be defined for those. I appreciate the correction.
🧬 Code Graph Analysis Results
File: packages/start-server-core/src/createStartHandler.ts
- Summary: The code constructs the middleware chain for a request by:
- Flattening any global request middlewares defined in startOptions.requestMiddleware.
- Mapping these flattened middlewares to their server-side handlers via d.options.server.
- Building a combined middleware stack that also includes requestHandlerMiddleware (which handles the actual request logic).
- Executing the chain with executeMiddleware, passing in the current Request and context.
- This demonstrates that, for request middlewares, only the .server() handlers are used when building the middleware chain.
- Summary: The code constructs the middleware chain for a request by:
File: packages/start-server-core/src/request-response.ts
- Summary: The requestHandler helper wraps a user-provided RequestHandler to:
- Create an H3Event from the incoming Request.
- Run the handler within a start-context-scoped environment (via runWithStartContext).
- Convert the result into a Response via h3_toResponse, ensuring proper integration with the H3 lifecycle.
- This clarifies how request handlers ultimately produce HTTP responses.
- Summary: The requestHandler helper wraps a user-provided RequestHandler to:
Sign in to join this conversation.
🤖 Nx Cloud AI Fix Eligible#
To disable these notifications, a workspace admin can disable them [in workspace settings.](https://cloud.nx.app/orgs/6412ca9d1c251d000efa21ba/workspaces/6442f7de8226a6291646a813/settings#selfHealingCISettings?utm_source=pull-request&utm_medium=comment)View your CI Pipeline Execution ↗ for commit 08391ddbc1bbd8536dde41f39d50c34b54a8da1d
nx affected --targets=test:eslint,test:unit,tes...nx run-many --target=build --exclude=examples/*...☁️ Nx Cloud last updated this comment at
2025-11-19 00:27:10UTC