fix: refactor middleware #5517
main fromrefs/pull/5517/head·merged by schiller-manuel(GitHub profile, opens in a new tab) fixes #5372 fixes #5266 fixes #4460 fixes #5239
Summary by CodeRabbit#
New Features
- Added a new page and navigation link for "Server Functions Middleware Unhandled Exception" E2E tests.
Bug Fixes
- Improved middleware execution and client/server error/redirect propagation for more consistent handling.
- Enhanced server response handling to support streaming and structured server-function payloads.
Chores
- Removed a legacy middleware export from the public API.
- Added a context header constant and updated client/server fetch plumbing to support the new server-function flow.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: start-client-core
Walkthrough#
Adds a new E2E route /middleware/unhandled-exception with an auth middleware that throws; refactors server/client middleware and server-function request/response handling across start-client-core and start-server-core, and updates exports/constants and client fetcher behavior.
Changes#
Cohort / File(s) Summary Route tree & registration
e2e/react-start/server-functions/src/routeTree.gen.tsImport and register MiddlewareUnhandledExceptionRoute, add torootRouteChildren, and include in FileRoutesByFullPath/FileRoutesByTo/FileRoutesById and TanStack Router augmentations.New route + navigation
e2e/react-start/server-functions/src/routes/middleware/unhandled-exception.tsx,e2e/react-start/server-functions/src/routes/index.tsxNew file route /middleware/unhandled-exceptionwithauthMiddleware(throws Unauthorized),personServerFnusing middleware chain, loader and component; index adds nav link labeled "Server Functions Middleware Unhandled Exception E2E tests".Client middleware orchestration
packages/start-client-core/src/createServerFn.ts,packages/start-client-core/src/index.tsx,packages/start-client-core/src/constants.tsMajor refactor of middleware execution to callNextMiddleware/userNextwrapper flow, await middleware results, centralize error/redirect handling; removed publicapplyMiddlewareexport; addedX_TSS_CONTEXTconstant export.Client RPC / fetcher
packages/start-client-core/src/client-rpc/serverFnFetcher.tsNew handler parameter and proxied fetch path; adds serverFn headers, supports serialized/streamed server-function responses (NDJSON / cross-JSON), and reworks JSON/redirect/not-found handling. Server request/response handling
packages/start-server-core/src/createStartHandler.ts,packages/start-server-core/src/server-functions-handler.tsAdjusted header checks (use x-tsr-createServerFn), removed middleware context propagation from execute call, added debug logging, added form-data detection, reworked payload parsing and response serialization (streaming NDJSON / cross-JSON), setX_TSS_RAW_RESPONSEfor raw Responses.Small UI text change
e2e/react-start/server-functions/src/routes/submit-post-formdata.tsxMinor copy update in displayed guidance text. Sequence Diagram(s)#
sequenceDiagram participant Client as Caller (client/serverFn) participant Runner as createServerFn.execute participant Chain as callNextMiddleware participant MW as Middleware (authMiddleware / others) participant Handler as Final Handler / ServerFn participant Fetcher as serverFnFetcher participant Server as start-server-core handler Client->>Fetcher: invoke(serverFn args, handler) Fetcher->>Server: proxied fetch with serverFn headers Server->>Runner: handleServerAction -> execute middlewares Runner->>Chain: start(index=0, ctx) Chain->>MW: execute(ctx, userNext) alt MW calls userNext MW->>Chain: userNext(mergedCtx) -> next index else MW throws MW-->>Runner: error (propagated) end opt reached handler Chain->>Handler: invoke with final ctx Handler-->>Server: result or error end Server-->>Fetcher: serialized or raw response (NDJSON/JSON/Response) Fetcher-->>Client: parsed/streamed result or redirect/errorEstimated code review effort#
🎯 5 (Critical) | ⏱️ ~120+ minutes
Areas needing extra attention:
- packages/start-client-core/src/createServerFn.ts — new middleware control-flow, userNext semantics, and removal of applyMiddleware.
- packages/start-client-core/src/client-rpc/serverFnFetcher.ts — streaming/NDJSON and proxied fetch handling.
- packages/start-server-core/src/server-functions-handler.ts — serializeResult and ctx-result unwrapping, Content-Type/X_TSS headers and Response construction.
- Integration between client fetcher and server serialized responses (headers: x-tsr-createServerFn, x-tsr-serverFn, X_TSS_RAW_RESPONSE, X_TSS_SERIALIZED).
Possibly related PRs#
- TanStack/router#5276 — Related changes affecting middleware orchestration and exports in start-client-core (server-function flow).
- TanStack/router#5513 — Overlaps in server-functions infrastructure edits touching server-functions-handler and createStartHandler.
- TanStack/router#5040 — Related modifications to server-function abstractions across client/server core packages.
Suggested reviewers#
- schiller-manuel
Poem#
🐰 I hopped through middleware, one by one, A token tossed, an Unauthorized run, I built a route for tests at dawn, Streams and headers hum along— I nibble logs and hum this song.
Pre-merge checks and finishing touches#
❌ Failed checks (1 warning)
Check name Status Explanation Resolution Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstringsto improve docstring coverage.✅ Passed checks (2 passed)
Check name Status Explanation Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled. Title Check ✅ Passed The PR title "fix: refactor middleware" is related to the primary changes in the changeset, particularly the significant middleware execution refactoring in packages/start-client-core/src/createServerFn.ts. This file underwent substantial changes including reworked client/server execution flow, expanded server-side middleware handling, middleware execution refactoring with new internal wrappers, and enhanced error handling. Supporting changes across multiple files (serverFnFetcher.ts, server-functions-handler.ts, createStartHandler.ts) appear designed to integrate and support this middleware refactoring. The title accurately captures the core intent of the PR, though it does not encompass the full scope of related server function handling changes.✨ Finishing touches
- 📝 Generate docstrings
🧪 Generate unit tests (beta)
- Create PR with unit tests
- Post copyable unit tests in a comment
- Commit unit tests in branch `fix/refactor-middleware`
Comment `@coderabbitai help` to get the list of available commands and usage tips.More templates
- tanstack-router-vue-example-basic-jsx
- tanstack-router-vue-example-basic-file-based-jsx
- tanstack-router-vue-example-basic-file-based-sfc
- 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-router-react-example-basic-authjs
- tanstack-start-example-basic-cloudflare
- tanstack-start-example-basic-react-query
- tanstack-start-example-basic-rsc
- 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
- @tanstack/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-authjs
- 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@5517@tanstack/eslint-plugin-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/eslint-plugin-router@5517@tanstack/history
npm i https://pkg.pr.new/TanStack/router/@tanstack/history@5517@tanstack/nitro-v2-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/nitro-v2-vite-plugin@5517@tanstack/react-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router@5517@tanstack/react-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@5517@tanstack/react-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-ssr-query@5517@tanstack/react-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start@5517@tanstack/react-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-client@5517@tanstack/react-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-server@5517@tanstack/router-cli
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-cli@5517@tanstack/router-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-core@5517@tanstack/router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools@5517@tanstack/router-devtools-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools-core@5517@tanstack/router-generator
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-generator@5517@tanstack/router-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-plugin@5517@tanstack/router-ssr-query-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-ssr-query-core@5517@tanstack/router-utils
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-utils@5517@tanstack/router-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-vite-plugin@5517@tanstack/solid-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router@5517@tanstack/solid-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-devtools@5517@tanstack/solid-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-ssr-query@5517@tanstack/solid-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start@5517@tanstack/solid-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-client@5517@tanstack/solid-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-server@5517@tanstack/start-client-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-client-core@5517@tanstack/start-fn-stubs
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-fn-stubs@5517@tanstack/start-plugin-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-plugin-core@5517@tanstack/start-server-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-core@5517@tanstack/start-static-server-functions
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-static-server-functions@5517@tanstack/start-storage-context
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-storage-context@5517@tanstack/valibot-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/valibot-adapter@5517@tanstack/virtual-file-routes
npm i https://pkg.pr.new/TanStack/router/@tanstack/virtual-file-routes@5517@tanstack/vue-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/vue-router@5517@tanstack/vue-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/vue-router-devtools@5517@tanstack/vue-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/vue-router-ssr-query@5517@tanstack/vue-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/vue-start@5517@tanstack/vue-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/vue-start-client@5517@tanstack/vue-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/vue-start-server@5517@tanstack/zod-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/zod-adapter@5517commit:
d27ac2aActionable comments posted: 2
🧹 Nitpick comments (3)
packages/start-client-core/src/createServerFn.ts (3)
259-263: Check for undefined explicitly and improve the error message.if (!(result as any))treats falsy values as undefined and the message doesn’t include context. Prefer a strict undefined check and include env/functionId for easier debugging.- if (!(result as any)) { - throw new Error( - 'User middleware returned undefined. You must call next() or return a result in your middlewares.', - ) - } + if (typeof result === 'undefined') { + throw new Error( + `User middleware returned undefined (env=${env}, functionId=${opts.functionId}). You must call next() or return a result.` + ) + }
182-190: Optional: avoid mutating the flattened array with shift().Using
shift()mutates shared state in the closure. An index-basedcallNextMiddleware(ctx, i)is clearer and safer if you ever need re-entrancy or debug indices.I can provide a small refactor to pass an index parameter instead of mutating the array if you want to pursue this.
146-154: Style consistency: prefer await over .then here.Elsewhere you use
await; using it here keeps style consistent and simplifies stack traces.- return executeMiddleware(resolvedMiddleware, 'server', ctx).then( - (d) => ({ - // Only send the result and sendContext back to the client - result: d.result, - error: d.error, - context: d.sendContext, - }), - ) + const d = await executeMiddleware(resolvedMiddleware, 'server', ctx) + return { + // Only send the result and sendContext back to the client + result: d.result, + error: d.error, + context: d.sendContext, + }📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 7978449cc5e33c6ecabae956d85c5587ffc2f274 and 55b636ca6e1daf3c4a48adc31a61b6d16e1290e9.
📒 Files selected for processing (5)
e2e/react-start/server-functions/src/routeTree.gen.ts(11 hunks)e2e/react-start/server-functions/src/routes/index.tsx(1 hunks)e2e/react-start/server-functions/src/routes/middleware/unhandled-exception.tsx(1 hunks)packages/start-client-core/src/createServerFn.ts(3 hunks)packages/start-client-core/src/index.tsx(0 hunks)
💤 Files with no reviewable changes (1)
- packages/start-client-core/src/index.tsx
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use TypeScript in strict mode with extensive type safety across the codebase
Files:
e2e/react-start/server-functions/src/routes/index.tsxe2e/react-start/server-functions/src/routeTree.gen.tse2e/react-start/server-functions/src/routes/middleware/unhandled-exception.tsxpackages/start-client-core/src/createServerFn.ts
**/src/routes/**
📄 CodeRabbit inference engine (AGENTS.md)
Place file-based routes under src/routes/ directories
Files:
e2e/react-start/server-functions/src/routes/index.tsxe2e/react-start/server-functions/src/routes/middleware/unhandled-exception.tsx
e2e/**
📄 CodeRabbit inference engine (AGENTS.md)
Store end-to-end tests under the e2e/ directory
Files:
e2e/react-start/server-functions/src/routes/index.tsxe2e/react-start/server-functions/src/routeTree.gen.tse2e/react-start/server-functions/src/routes/middleware/unhandled-exception.tsx
packages/{*-start,start-*}/**
📄 CodeRabbit inference engine (AGENTS.md)
Name and place Start framework packages under packages/-start/ or packages/start-/
Files:
packages/start-client-core/src/createServerFn.ts
🧬 Code graph analysis (2)
e2e/react-start/server-functions/src/routes/middleware/unhandled-exception.tsx (1)
packages/start-client-core/src/createServerFn.ts (1)
createServerFn(48-169)
packages/start-client-core/src/createServerFn.ts (2)
packages/start-client-core/src/index.tsx (4)
executeMiddleware(79-79)NextFn(71-71)ServerFnMiddlewareResult(68-68)mergeHeaders(6-6)
packages/router-core/src/ssr/client.ts (1)
mergeHeaders(1-1)
⏰ 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 (3)
e2e/react-start/server-functions/src/routes/index.tsx (1)
91-95: LGTM: adds nav to new middleware error route.e2e/react-start/server-functions/src/routes/middleware/unhandled-exception.tsx (1)
1-33: Intent check: loader will reject due to middleware throw.This looks correct for exercising the unhandled-exception path. Ensure the E2E asserts the error boundary/response instead of relying on the component render.
Can you confirm the E2E expects a rejected loader (e.g., checks for router error state) rather than querying
data-testid="regular-person"?e2e/react-start/server-functions/src/routeTree.gen.ts (1)
30-33: Generated: additions look consistent with the new route.No action; keep as-is.
Also applies to: 127-132, 180-181, 206-207, 233-234, 261-262, 287-288, 313-314, 340-341, 477-483
@@ -112,15 +111,15 @@112111 return Object.assign(113112 async (opts?: CompiledFetcherFnOptions) => {114113 // Start by executing the client-side middleware chain115- return executeMiddleware(resolvedMiddleware, 'client', {114+ const result = await executeMiddleware(resolvedMiddleware, 'client', {116115 ...extractedFn,117116 ...newOptions,118117 data: opts?.data as any,119118 headers: opts?.headers,120119 signal: opts?.signal,121120 context: {},122- }).then((d) => {123- if (d.error) throw d.error124- return d.result125121 })122+123+ if (result.error) throw result.error124+ return result.result126125 },⚠️ Potential issue | 🟠 Major
Don't drop caller-provided context in client fetcher.
The client entry sets
context: {}and ignoresopts?.context, preventing client-side middlewares from receiving user context.Apply this fix:
- const result = await executeMiddleware(resolvedMiddleware, 'client', { + const result = await executeMiddleware(resolvedMiddleware, 'client', { ...extractedFn, ...newOptions, data: opts?.data as any, headers: opts?.headers, signal: opts?.signal, - context: {}, + context: opts?.context ?? {}, }) if (result.error) throw result.error return result.result📝 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 result = await executeMiddleware(resolvedMiddleware, 'client', { ...extractedFn, ...newOptions, data: opts?.data as any, headers: opts?.headers, signal: opts?.signal, context: opts?.context ?? {}, }) if (result.error) throw result.error return result.result },🤖 Prompt for AI Agents
In packages/start-client-core/src/createServerFn.ts around lines 114 to 125, the client fetcher currently sets context: {} which drops any caller-provided opts?.context; change this to pass through the caller context (e.g. context: opts?.context ?? {}), or merge with any existing extractedFn.context if needed (e.g. context: { ...(extractedFn.context || {}), ...(opts?.context || {}) }) so client-side middlewares receive the user-supplied context instead of an empty object.✅ Addressed in commits b0d0b25 to ed54879
packages/start-client-core/src/createServerFn.ts lines 214 to 251Outdated@@ -220,6 +232,20 @@232+ headers: mergeHeaders(ctx.headers, userCtx.headers),233+ result:234+ userCtx.result !== undefined235+ ? userCtx.result236+ : userCtx instanceof Response237+ ? userCtx238+ : (ctx as any).result,239+ error: userCtx.error ?? (ctx as any).error,240+ }241+242+ try {243+ return await callNextMiddleware(nextCtx)244+ } catch (error: any) {220245 return {221- ...newCtx,246+ ...nextCtx,222247 error,223248 }224249 }250+ }225251🛠️ Refactor suggestion | 🟠 Major
Prevent multiple next() calls within a single middleware.
As written, a middleware can call
next()multiple times, advancing the chain repeatedly and producing hard-to-debug behavior. Add a simple guard.- if (middlewareFn) { - const userNext = async ( + if (middlewareFn) { + let nextCalled = false + const userNext = async ( userCtx: ServerFnMiddlewareResult | undefined = {} as any, ) => { + if (nextCalled) { + throw new Error('next() called multiple times in a middleware') + } + nextCalled = true // Return the next middleware const nextCtx = { ...ctx, ...userCtx, context: { ...ctx.context, ...userCtx.context, }, sendContext: { ...ctx.sendContext, ...(userCtx.sendContext ?? {}), }, headers: mergeHeaders(ctx.headers, userCtx.headers), result: userCtx.result !== undefined ? userCtx.result : userCtx instanceof Response ? userCtx : (ctx as any).result, error: userCtx.error ?? (ctx as any).error, } try { return await callNextMiddleware(nextCtx) } catch (error: any) { return { ...nextCtx, error, } } }📝 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.
// Execute the middleware try { if (middlewareFn) { let nextCalled = false const userNext = async ( userCtx: ServerFnMiddlewareResult | undefined = {} as any, ) => { if (nextCalled) { throw new Error('next() called multiple times in a middleware') } nextCalled = true // Return the next middleware const nextCtx = { ...ctx, ...userCtx, context: { ...ctx.context, ...userCtx.context, }, sendContext: { ...ctx.sendContext, ...(userCtx.sendContext ?? {}), }, headers: mergeHeaders(ctx.headers, userCtx.headers), result: userCtx.result !== undefined ? userCtx.result : userCtx instanceof Response ? userCtx : (ctx as any).result, error: userCtx.error ?? (ctx as any).error, } try { return await callNextMiddleware(nextCtx) } catch (error: any) { return { ...nextCtx, error, } } }🤖 Prompt for AI Agents
In packages/start-client-core/src/createServerFn.ts around lines 214 to 251, the userNext function allows a middleware to call next() multiple times; add a simple reentrancy guard inside the userNext closure (e.g., a boolean "called" flag set on first invocation) that throws or returns an error if next() is invoked again, ensuring subsequent calls are rejected; keep the rest of next's behavior (building nextCtx, calling callNextMiddleware, and catching errors) unchanged but bail early when the guard detects a repeated call.Actionable comments posted: 1
♻️ Duplicate comments (2)
packages/start-client-core/src/createServerFn.ts (2)
114-125: Still dropping caller-provided context in client fetcher.Line 120 sets
context: {}, ignoring anyopts?.contextpassed by the caller. This prevents client-side middlewares from receiving user-supplied context.Apply this fix:
const result = await executeMiddleware(resolvedMiddleware, 'client', { ...extractedFn, ...newOptions, data: opts?.data as any, headers: opts?.headers, signal: opts?.signal, - context: {}, + context: opts?.context ?? {}, })
218-252: Still missing guard against multiple next() calls.The
userNextfunction allows a middleware to callnext()multiple times, which can advance the chain repeatedly and cause unpredictable behavior.Apply this diff to add a reentrancy guard:
if (middlewareFn) { + let nextCalled = false const userNext = async ( userCtx: ServerFnMiddlewareResult | undefined = {} as any, ) => { + if (nextCalled) { + throw new Error('next() called multiple times in a middleware') + } + nextCalled = true // Return the next middleware const nextCtx = { ...ctx,📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 55b636ca6e1daf3c4a48adc31a61b6d16e1290e9 and 621a2aab54e759309a92f41ad8df86d98bd670eb.
📒 Files selected for processing (1)
packages/start-client-core/src/createServerFn.ts(3 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use TypeScript in strict mode with extensive type safety across the codebase
Files:
packages/start-client-core/src/createServerFn.ts
packages/{*-start,start-*}/**
📄 CodeRabbit inference engine (AGENTS.md)
Name and place Start framework packages under packages/-start/ or packages/start-/
Files:
packages/start-client-core/src/createServerFn.ts
🧬 Code graph analysis (1)
packages/start-client-core/src/createServerFn.ts (1)
packages/start-client-core/src/index.tsx (6)
executeMiddleware(79-79)NextFn(71-71)execValidator(77-77)MiddlewareFn(66-66)ServerFnMiddlewareResult(68-68)mergeHeaders(6-6)
⏰ 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-client-core/src/createServerFn.ts (2)
182-217: LGTM: Middleware selection and validation logic.The refactored
callNextMiddlewarecorrectly shifts through the middleware chain, validates input on the server side, and selects the appropriate middleware function based on the environment.
269-285: LGTM: Fallback handling and chain initialization.The fallback correctly continues the middleware chain when no middleware function is present, and the chain initialization properly sets up the initial context with appropriate defaults.
@@ -225,7 +252,16 @@252+ }225253226- throw error227- })228- })229- }254+ // Execute the middleware255+ const result = await middlewareFn({256+ ...ctx,257+ next: userNext as any,258+ } as any)230259231- return next(ctx)260+ if (!(result as any)) {261+ throw new Error(262+ 'User middleware returned undefined. You must call next() or return a result in your middlewares.',263+ )264+ }265+266+ return result267+ }⚠️ Potential issue | 🔴 Critical
Fix incorrect undefined check that rejects valid falsy values.
Line 260 uses
!(result as any)which rejects any falsy value (false,0,'',null). A middleware legitimately returning these values would incorrectly throw an error. The intent is to detect onlyundefined.Apply this diff:
// Execute the middleware const result = await middlewareFn({ ...ctx, next: userNext as any, } as any) -if (!(result as any)) { +if (result === undefined) { throw new Error( 'User middleware returned undefined. You must call next() or return a result in your middlewares.', ) } return result📝 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.
// Execute the middleware const result = await middlewareFn({ ...ctx, next: userNext as any, } as any) if (result === undefined) { throw new Error( 'User middleware returned undefined. You must call next() or return a result in your middlewares.', ) } return result }🤖 Prompt for AI Agents
In packages/start-client-core/src/createServerFn.ts around lines 254 to 267, the middleware undefined check uses `!(result as any)` which incorrectly rejects valid falsy returns; change the check to explicitly detect only undefined (e.g., `result === undefined` or `typeof result === 'undefined'`) so falsy but valid values like false, 0, or '' are accepted; keep the thrown Error for the undefined case and retain the surrounding logic and types.✅ Addressed in commits b0d0b25 to ed54879
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: start-server-core
Actionable comments posted: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/start-server-core/src/createStartHandler.ts (1)
92-116: Per-request global fetch override is unsafe (cross-request race/leak).Overwriting globalThis.fetch per request can affect concurrent requests (origin/requestOpts bleed), producing incorrect routing and privacy issues. At minimum, restore in a finally; preferably use an ALS-scoped wrapper or pass a handler instead of patching global.
Apply a minimal containment fix:
- globalThis.fetch = async function (input, init) { + const prevFetch = globalThis.fetch + globalThis.fetch = async function (input, init) { function resolve(url: URL, requestOptions: RequestInit | undefined) { const fetchRequest = new Request(url, requestOptions) return startRequestResolver(fetchRequest, requestOpts) } ... - } as typeof fetch + } as typeof fetch + try { + // existing logic continues... + // ... + } finally { + globalThis.fetch = prevFetch + }If you want a robust fix, wrap a single global fetch once with AsyncLocalStorage and consult per-request context to resolve same-origin URLs. I can draft that if helpful.
♻️ Duplicate comments (3)
packages/start-client-core/src/createServerFn.ts (3)
228-262: Guard against multiple next() calls in a middleware.A middleware can call next() multiple times and reenter the chain.
- const userNext = async ( + let nextCalled = false + const userNext = async ( userCtx: ServerFnMiddlewareResult | undefined = {} as any, ) => { + if (nextCalled) { + throw new Error('next() called multiple times in a middleware') + } + nextCalled = true // Return the next middleware const nextCtx = { ...ctx, ...userCtx, context: { ...ctx.context, ...userCtx.context, },
115-123: Don’t drop caller-provided context.You’re passing context: {} and ignore opts?.context; this blocks client middlewares from receiving user context.
- context: {}, + context: opts?.context ?? {},
286-290: Bug: undefined check rejects valid falsy middleware returns.!(result as any)treats 0/''/false as undefined; check strictly for undefined.- if (!(result as any)) { + if (result === undefined) { throw new Error( 'User middleware returned undefined. You must call next() or return a result in your middlewares.', ) }🧹 Nitpick comments (5)
e2e/react-start/server-functions/src/routes/submit-post-formdata.tsx (1)
36-36: Remove unnecessary empty string template literal.The
{''}at the end of the line renders nothing and appears to be a leftover from editing. Consider removing it or replacing with a colon for better readability:Apply this diff:
- It should navigate to a raw response of {''} + It should navigate to a raw response of:Or simply:
- It should navigate to a raw response of {''} + It should navigate to a raw responsepackages/start-server-core/src/createStartHandler.ts (1)
202-211: Return 406 for unsupported Accept instead of 500.Not an internal error; 406 Not Acceptable fits better.
- return json( - { error: 'Only HTML requests are supported here' }, - { status: 500 }, - ) + return json( + { error: 'Only HTML requests are supported here' }, + { status: 406 }, + )packages/start-client-core/src/client-rpc/serverFnFetcher.ts (2)
66-70: Avoid double serialization work.serializePayload() is called twice; reuse the computed value.
- const serializedPayload = await serializePayload(first) - if (serializedPayload !== undefined) { - const encodedPayload = encode({ - payload: await serializePayload(first), - }) + const serializedPayload = await serializePayload(first) + if (serializedPayload !== undefined) { + const encodedPayload = encode({ + payload: serializedPayload, + })
175-181: Avoid unconditional console.log on errors.Noise and potential sensitive data leak. Use warning in dev only.
- console.log(error) + if (process.env.NODE_ENV === 'development') { + // console.warn(error) + }packages/start-server-core/src/server-functions-handler.ts (1)
288-291: Optional: return 204 No Content for undefined results.serializeResult(undefined) currently responds with empty body and no content-type; set a 204 to clarify semantics.
- return new Response(undefined, { - status: alsResponse?.status, - statusText: alsResponse?.statusText, - }) + return new Response(null, { + status: alsResponse?.status ?? 204, + statusText: alsResponse?.statusText, + })📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between ed548799d38abe1a73c9ed3f9005833cec06fe35 and c7eddee32cba07565624c5f3b18f89e7a6af7efb.
📒 Files selected for processing (7)
e2e/react-start/server-functions/src/routes/submit-post-formdata.tsx(1 hunks)packages/start-client-core/src/client-rpc/serverFnFetcher.ts(7 hunks)packages/start-client-core/src/constants.ts(1 hunks)packages/start-client-core/src/createServerFn.ts(6 hunks)packages/start-client-core/src/index.tsx(1 hunks)packages/start-server-core/src/createStartHandler.ts(2 hunks)packages/start-server-core/src/server-functions-handler.ts(6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/start-client-core/src/index.tsx
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use TypeScript in strict mode with extensive type safety across the codebase
Files:
packages/start-server-core/src/createStartHandler.tspackages/start-client-core/src/client-rpc/serverFnFetcher.tspackages/start-client-core/src/constants.tspackages/start-client-core/src/createServerFn.tspackages/start-server-core/src/server-functions-handler.tse2e/react-start/server-functions/src/routes/submit-post-formdata.tsx
packages/{*-start,start-*}/**
📄 CodeRabbit inference engine (AGENTS.md)
Name and place Start framework packages under packages/-start/ or packages/start-/
Files:
packages/start-server-core/src/createStartHandler.tspackages/start-client-core/src/client-rpc/serverFnFetcher.tspackages/start-client-core/src/constants.tspackages/start-client-core/src/createServerFn.tspackages/start-server-core/src/server-functions-handler.ts
**/src/routes/**
📄 CodeRabbit inference engine (AGENTS.md)
Place file-based routes under src/routes/ directories
Files:
e2e/react-start/server-functions/src/routes/submit-post-formdata.tsx
e2e/**
📄 CodeRabbit inference engine (AGENTS.md)
Store end-to-end tests under the e2e/ directory
Files:
e2e/react-start/server-functions/src/routes/submit-post-formdata.tsx
🧬 Code graph analysis (4)
packages/start-client-core/src/client-rpc/serverFnFetcher.ts (1)
packages/start-client-core/src/constants.ts (1)
X_TSS_SERIALIZED(7-7)
packages/start-client-core/src/constants.ts (1)
packages/start-client-core/src/index.tsx (1)
X_TSS_CONTEXT(87-87)
packages/start-client-core/src/createServerFn.ts (1)
packages/router-core/src/index.ts (3)
redirect(370-370)parseRedirect(373-373)isRedirect(371-371)
packages/start-server-core/src/server-functions-handler.ts (3)
packages/start-client-core/src/index.tsx (3)
json(6-6)X_TSS_RAW_RESPONSE(86-86)X_TSS_SERIALIZED(85-85)
packages/start-client-core/src/constants.ts (2)
X_TSS_RAW_RESPONSE(8-8)X_TSS_SERIALIZED(7-7)
packages/start-server-core/src/request-response.ts (1)
getResponse(328-331)
🔇 Additional comments (1)
packages/start-client-core/src/constants.ts (1)
9-9: X_TSS_CONTEXT is properly integrated into the public API.The constant is correctly exported as part of the public API surface in
index.tsxalongside other similar constants (TSS_FORMDATA_CONTEXT,X_TSS_RAW_RESPONSE, etc.). While not used internally within the package, this is the expected pattern for public API constants defined in a barrel export. No action needed.packages/start-client-core/src/client-rpc/serverFnFetcher.ts lines 173 to 175@@ -178,17 +184,8 @@178184 if (response.headers.get(X_TSS_RAW_RESPONSE) === 'true') {179185 return response180186 }187+181188 const contentType = response.headers.get('content-type')182189 invariant(contentType, 'expected content-type header to be set')183190 const serializedByStart = !!response.headers.get(X_TSS_SERIALIZED)184- // If the response is not ok, throw an error185- if (!response.ok) {186- if (serializedByStart && contentType.includes('application/json')) {187- const jsonPayload = await response.json()188- const result = fromCrossJSON(jsonPayload, { plugins: serovalPlugins! })189- throw result190- }191-192- throw new Error(await response.text())193- }194191⚠️ Potential issue | 🔴 Critical
Handle no-content responses; don’t assert content-type.
Server may return undefined/204 with no content-type (e.g., serializeResult(undefined)). Current invariant throws. Treat “no content” as undefined when ok.
- invariant(contentType, 'expected content-type header to be set') + const contentType = response.headers.get('content-type') + if (!contentType) { + if (response.ok && (response.status === 204 || !response.body)) { + return undefined + } + if (!response.ok) { + throw new Error(await response.text()) + } + return response + }Also applies to: 288-294
🤖 Prompt for AI Agents
In packages/start-client-core/src/client-rpc/serverFnFetcher.ts around lines 189-191 (and similarly at 288-294), the code currently invariants that a content-type header exists which breaks for no-content responses (e.g., 204 or serializeResult(undefined)); change the logic to allow missing content-type for empty responses: first detect no-content (response.status === 204 or content-length === '0' or response.headers.get('content-type') === null and response.bodyUsed is false/response has no body), treat those cases as undefined result instead of asserting, and only assert/parse content-type when a body is actually present; preserve the existing check for the X_TSS_SERIALIZED header when present and ensure parsing flows handle both serialized and plain/no-content responses.packages/start-client-core/src/client-rpc/serverFnFetcher.ts lines 199 to 205@@ -206,13 +206,16 @@206206 },207207 })208208 }209+ // If it's a JSON response, it can be simpler209210 if (contentType.includes('application/json')) {210211 const jsonPayload = await response.json()211212 result = fromCrossJSON(jsonPayload, { plugins: serovalPlugins! })212213 }214+213215 invariant(result, 'expected result to be resolved')214216 if (result instanceof Error) {215217 throw result216218 }219+217220 return result218221 }⚠️ Potential issue | 🔴 Critical
Bug: falsy results (0, '', false) are incorrectly rejected.
invariant(result, ...) rejects valid falsy values; check only undefined.
- invariant(result, 'expected result to be resolved') + invariant(typeof result !== 'undefined', 'expected result to be resolved')📝 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.
invariant(typeof result !== 'undefined', 'expected result to be resolved') if (result instanceof Error) { throw result } return result }🤖 Prompt for AI Agents
In packages/start-client-core/src/client-rpc/serverFnFetcher.ts around lines 215 to 221, the code uses invariant(result, 'expected result to be resolved') which treats valid falsy values (0, '', false) as errors; change the check to only reject undefined (e.g., replace the invariant call with a check like if (result === undefined) { throw new Error('expected result to be resolved') } or use invariant(result !== undefined, ...)) so that falsy but valid results are preserved, keep the existing Error instance handling (if (result instanceof Error) throw result) and then return result.packages/start-client-core/src/createServerFn.ts line 19@@ -16,3 +15,4 @@1615 ValidateSerializableInput,1716 Validator,1817 } from '@tanstack/router-core'18+import type { TSS_SERVER_FUNCTION } from './constants'⚠️ Potential issue | 🔴 Critical
Invalid type-only import for value symbol.
TSS_SERVER_FUNCTION is a value, not a type. Using it as a computed key requires a value import; type-only import breaks under strict TS/isolatedModules.
-import type { TSS_SERVER_FUNCTION } from './constants' +import { TSS_SERVER_FUNCTION } from './constants'If you want a type-only reference, declare/export it as
declare const TSS_SERVER_FUNCTION: unique symbolin constants and keep a value export to use as a key. As per coding guidelines.🤖 Prompt for AI Agents
In packages/start-client-core/src/createServerFn.ts around line 18, the import uses a type-only import for TSS_SERVER_FUNCTION but that identifier is a runtime value used as a computed key; change the import to a value import (remove the leading "type") so the symbol exists at runtime. If constants currently only export a type, update packages/start-client-core/src/constants to export a runtime symbol (e.g., export const TSS_SERVER_FUNCTION = Symbol(...) or export declare const TSS_SERVER_FUNCTION: unique symbol plus a value export) so callers can import the value; ensure callers use the value import for computed property access.packages/start-server-core/src/createStartHandler.ts lines 277 to 278Outdated@@ -268,10 +268,11 @@268268 [...middlewares, requestHandlerMiddleware],269269 {270270 request,271-272271 context: requestOpts?.context || {},273272 },274273 )275274276275 const response: Response = ctx.response277276277+ console.log('response', response)278+⚠️ Potential issue | 🟠 Major
Remove noisy response logging (potential PII leakage).
console.log(response) can log bodies/headers in prod. Guard by NODE_ENV or delete.
- console.log('response', response) + if (process.env.NODE_ENV === 'development') { + // console.debug('response', response) + }📝 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.
if (process.env.NODE_ENV === 'development') { // console.debug('response', response) }🤖 Prompt for AI Agents
In packages/start-server-core/src/createStartHandler.ts around lines 277-278, the console.log('response', response) is noisy and may leak PII; remove this raw response logging or guard it so it only runs in non-production (e.g. check NODE_ENV !== 'production') and/or replace with a structured logger at a debug level that only emits safe fields (status/code, timing) rather than full headers/bodies.packages/start-server-core/src/server-functions-handler.ts lines 145 to 153Outdated@@ -137,7 +139,15 @@137139138- // Any time we get a Response back, we should just139- // return it immediately.140- if (result.result instanceof Response) {141- result.result.headers.set(X_TSS_RAW_RESPONSE, 'true')142- return result.result143- }140+ const isCtxResult =141+ isPlainObject(res) &&142+ 'context' in res &&143+ ('result' in res || 'error' in res)144+145+ console.log(146+ {147+ isServerFn,148+ isCreateServerFn,149+ isFormData,150+ isCtxResult,151+ },152+ res,153+ )⚠️ Potential issue | 🟡 Minor
Remove stray debug logging.
Avoid logging payloads/results in prod.
- console.log( - { - isServerFn, - isCreateServerFn, - isFormData, - isCtxResult, - }, - res, - ) + // Debug block removed📝 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.
// Debug block removed🤖 Prompt for AI Agents
In packages/start-server-core/src/server-functions-handler.ts around lines 145 to 153, remove the stray console.log that prints full payloads/results; replace it either by deleting the log entirely or by using a non-production gated logger (e.g. wrap with NODE_ENV !== 'production' or use a debug/logger library) so sensitive data is not printed in production. Ensure no raw payload or result is logged in the production path.packages/start-server-core/src/server-functions-handler.ts lines 156 to 164Outdated@@ -144,5 +148,17 @@148+ isCreateServerFn,149+ isFormData,150+ isCtxResult,151+ },152+ res,153+ )144154145- // If this is a non createServerFn request, we need to146- // pull out the result from the result object147- if (!isCreateServerFn) {148- result = result.result155+ function unwrapResultOrError(result: any) {156+ if (157+ isPlainObject(result) &&158+ ('result' in result || 'error' in result)159+ ) {160+ console.log('tanner')161+ return result.result || result.error162+ }163+ return result164+ }⚠️ Potential issue | 🔴 Critical
Fix unwrap logic; truthiness breaks falsy results.
result.result || result.errormisroutes 0/''/false to error. Prefer explicit presence checks.- function unwrapResultOrError(result: any) { - if ( - isPlainObject(result) && - ('result' in result || 'error' in result) - ) { - console.log('tanner') - return result.result || result.error - } - return result - } + function unwrapResultOrError(result: any) { + if (isPlainObject(result) && ('result' in result || 'error' in result)) { + return 'error' in result ? result.error : result.result + } + return result + }🤖 Prompt for AI Agents
In packages/start-server-core/src/server-functions-handler.ts around lines 156 to 164, the unwrap logic uses truthiness (result.result || result.error) which incorrectly treats valid falsy values (0, '', false) as absent; replace this with explicit presence checks: if the plain object hasOwnProperty('result') return result.result; else if it hasOwnProperty('error') return result.error; also remove the stray console.log and ensure you check property presence rather than truthiness to preserve falsy payloads.Is there anything that's blocking this PR from progressing?
Quite a few of the open issues marked under the label
needed-for-start-stableare ones involved with middleware handling.Just quickly going through this PR, it looks like it might be possible to resolve a few of them if this development completes and gets merged.
(Not trying to pressure you guys to rush anything :) just want to express that I'm sure many of us would be happy to see this PR land)
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: start-storage-context
Sign in to join this conversation.
View your CI Pipeline Execution ↗ for commit d27ac2a4a8bb4e1e39e9ccfa28876c2c857286fa
nx affected --targets=test:eslint,test:unit,tes...nx run-many --target=build --exclude=examples/*...☁️ Nx Cloud last updated this comment at
2025-12-27 00:04:41UTC