Skip to content
Source
Sign inSign up
TanStack/router

fix(start-server-core): preserve status code when handler throws after setResponseStatus #6785

Closeddjk01281(GitHub profile, opens in a new tab)wants to merge 4 commits intomain fromrefs/pull/6785/headopened

Summary

Fixes #5107

When a user calls setResponseStatus(401) and then throw new Error('Unauthorized') inside middleware or a request handler, the status code is lost and the response returns 500.

This is a common pattern in auth middleware (e.g., better-auth):

const session = await auth.api.getSession({ headers })

if (!session) {
  setResponseStatus(401)
  throw new Error('Unauthorized')
}

Root Cause

attachResponseHeaders() in request-response.ts only handled the fulfilled path of the promise. When a handler threw (rejected promise), the rejection bypassed attachResponseHeaders entirely and went straight to h3's toResponse(), which created a 500 response without reading event.res.status.

Note: the handleServerAction path (used by createServerFn) already handles this correctly by reading getResponse().status ?? 500 in its catch block. This fix closes the gap for the requestHandler path.

Before

setResponseStatus(401) + throw new Error() → 500
setResponseStatus(429) + throw new Response() → 200

After

setResponseStatus(401) + throw new Error() → 401
setResponseStatus(429) + throw new Response() → 429

Fix

Added a rejection handler to attachResponseHeaders(). When the handler throws after setResponseStatus() was called:

  • Thrown Error: creates a Response with the error message and the event status code
  • Thrown Response: creates a new Response preserving the original headers/body but using the event status code
  • No status set: re-throws unchanged (h3 handles normally → 500)

Test

Added unit tests for requestHandler that verify status code preservation across Error throws, Response throws, and the no-status fallback path.

Summary by CodeRabbit

  • Bug Fixes

    • Improved async response handling: when an error occurs and a status is set, the error is converted into a Response that preserves status and status text when available, merges configured response headers, and rethrows only if no status is present.
  • Tests

    • Added tests verifying status preservation and error-to-response behavior for thrown Errors, Response objects, and non-Response values.
    1. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: start-server-core

    2. No actionable comments were generated in the recent review. 🎉

      ℹ️ Recent review info

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro

      📥 Commits

      Reviewing files that changed from the base of the PR and between 82215e5cabab9b8bdfae150e151677ede01f49fd and 9825a287538ea4a164a05f3c01e3f397d1a7067a.

      📒 Files selected for processing (1)
      • packages/start-server-core/src/request-response.ts
      🚧 Files skipped from review as they are similar to previous changes (1)
      • packages/start-server-core/src/request-response.ts

      📝 Walkthrough

      Walkthrough

      attachResponseHeaders now adds rejection handling for promise-like handler results: if setResponseStatus was called, a Response is constructed using that status/statusText (preserving Response body/headers when the rejection is a Response); otherwise the original error is re-thrown.

      Changes

      Cohort / File(s)Summary
      Promise error handling
      packages/start-server-core/src/request-response.ts
      Added a rejection handler for promise-returning handlers. When a handler promise rejects and an event status exists, constructs a Response using the event's status/statusText; if the rejection is a Response, preserves its body/headers while overriding status/statusText; for other errors uses the error message as body. If no event status, rethrows the original error.
      Test coverage
      packages/start-server-core/tests/request-response.test.ts
      Added tests validating that setResponseStatus persists across thrown Error, thrown Response, and returned non-Response values; verifies default 500 when no status set; and checks request-context access errors.

      Estimated code review effort

      🎯 3 (Moderate) | ⏱️ ~20 minutes

      • TanStack/router#6161 — Modifies attachResponseHeaders and related response/status propagation behavior; strongly related to the same rejection/status handling changes.

      Poem

      🐰 I nudged a promise that once returned five-hundred, Now when it breaks, the status hops true and sound. If a Response tumbled out, I keep its headers tight, If an Error spoke, I wrap its words polite. Hooray — the server answers with the right little light. ✨

      🚥 Pre-merge checks | ✅ 4 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
      Title check✅ PassedThe title accurately describes the main fix: preserving status code when a handler throws after calling setResponseStatus, which directly addresses the core issue in #5107.
      Linked Issues check✅ PassedThe PR fully implements the requirements from #5107: adds rejection handler in attachResponseHeaders() to preserve setResponseStatus() when handlers throw Error or Response objects, with comprehensive unit tests validating the fix.
      Out of Scope Changes check✅ PassedAll changes are directly scoped to fixing #5107: modifications to attachResponseHeaders() rejection path, header merging, and comprehensive tests for the specific issue with no unrelated alterations.
      ✏️ Tip: You can configure your own custom pre-merge checks in the settings.
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Post copyable unit tests in a comment

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    3. View your CI Pipeline Execution ↗ for commit 9825a287538ea4a164a05f3c01e3f397d1a7067a

      CommandStatusDurationResult
      nx run tanstack-router-e2e-bundle-size:build --...✅ Succeeded1m 28sView ↗

      ☁️ Nx Cloud last updated this comment at 2026-02-28 06:31:09 UTC

    4. Bundle Size Benchmarks

      • Commit: de66f0e0a0d6
      • Measured at: 2026-02-28T06:30:11.509Z
      • Baseline source: history:442ada1f6432
      • Dashboard: bundle-size history
      ScenarioCurrent (gzip)Delta vs baselineRawBrotliTrend
      react-router.minimal86.58 KiB0 B (0.00%)272.45 KiB75.22 KiB▁▂▂▂▂▂▂▂▇▇█
      react-router.full89.61 KiB0 B (0.00%)282.78 KiB77.90 KiB▂▁▁▁▂▂▂▂▇▇█
      solid-router.minimal35.88 KiB0 B (0.00%)107.56 KiB32.26 KiB▁▂▂▂▅▅▅▅▇▇█
      solid-router.full40.21 KiB0 B (0.00%)120.61 KiB36.13 KiB▁▃▃▃▅▅▅▅▇▇█
      vue-router.minimal51.75 KiB0 B (0.00%)147.54 KiB46.50 KiB▁▂▂▂▅▅▅▅▇▇█
      vue-router.full56.55 KiB0 B (0.00%)163.12 KiB50.86 KiB▁▂▂▂▅▅▅▅▇▇█
      react-start.minimal99.11 KiB0 B (0.00%)311.58 KiB85.68 KiB▁▂▂▂▂▂▂▂▆▆█
      react-start.full102.49 KiB0 B (0.00%)321.36 KiB88.62 KiB▁▂▂▂▂▂▂▂▆▆█
      solid-start.minimal48.19 KiB0 B (0.00%)145.13 KiB42.67 KiB▁▃▃▃▅▅▅▅▇▇█
      solid-start.full53.67 KiB0 B (0.00%)161.05 KiB47.33 KiB▁▂▂▂▅▅▅▅▇▇█

      Trend sparkline is historical gzip bytes ending with this PR measurement; lower is better.

    5. 🧹 Nitpick comments (1)
      packages/start-server-core/tests/request-response.test.ts (1)

      9-67: Good test coverage for the core fix.

      The tests thoroughly cover the main scenarios from the linked issue. Consider adding assertions to verify:

      1. Error message preservation: When throwing an Error, verify the response body contains the error message.
      2. Response headers/body preservation: When throwing a Response after setResponseStatus, verify the original headers and body are preserved.
      3. StatusText preservation: The test on line 22 sets 'Too Many Requests' but doesn't assert it on the response.
      📝 Example: Enhanced assertions for the Error throw test
         it('should preserve status code when handler throws an Error after setResponseStatus', async () => {
           const handler = requestHandler(async (_request: Request) => {
             setResponseStatus(401)
             throw new Error('Unauthorized')
           })
      
           const request = new Request('http://localhost/test')
           const response = await handler(request, {})
      
           expect(response.status).toBe(401)
      +    expect(await response.text()).toBe('Unauthorized')
         })
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/start-server-core/tests/request-response.test.ts` around lines 9 -
      67, Add assertions to the existing tests to verify that thrown Error messages
      and thrown Response bodies/headers/statusText are preserved: in the test cases
      using requestHandler and setResponseStatus, after awaiting handler(request, {}),
      assert that the response body text contains the Error message for the
      Error-throwing case (verify response.text() includes 'Unauthorized' or
      'unexpected failure'), assert that the Response thrown after setResponseStatus
      preserves its headers and body by checking response.headers.get('...') and
      response.text() (e.g., 'Rate limited'), and assert that response.statusText
      matches the provided statusText ('Too Many Requests') for the 429 case; refer to
      the tests using requestHandler, setResponseStatus, and the individual it(...)
      blocks to locate where to add these assertions.
      🤖 Prompt for all review comments with AI agents
      Verify each finding against the current code and only fix it if needed.
      
      Nitpick comments:
      In `@packages/start-server-core/tests/request-response.test.ts`:
      - Around line 9-67: Add assertions to the existing tests to verify that thrown
      Error messages and thrown Response bodies/headers/statusText are preserved: in
      the test cases using requestHandler and setResponseStatus, after awaiting
      handler(request, {}), assert that the response body text contains the Error
      message for the Error-throwing case (verify response.text() includes
      'Unauthorized' or 'unexpected failure'), assert that the Response thrown after
      setResponseStatus preserves its headers and body by checking
      response.headers.get('...') and response.text() (e.g., 'Rate limited'), and
      assert that response.statusText matches the provided statusText ('Too Many
      Requests') for the 429 case; refer to the tests using requestHandler,
      setResponseStatus, and the individual it(...) blocks to locate where to add
      these assertions.

      ℹ️ Review info

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro

      📥 Commits

      Reviewing files that changed from the base of the PR and between de66f0e0a0d635f1efbf07d29ea84551c8470532 and 77c50ffbc704c79b200994d6c9047603744b7c14.

      📒 Files selected for processing (2)
      • packages/start-server-core/src/request-response.ts
      • packages/start-server-core/tests/request-response.test.ts
    6. ✅ Actions performed

      Review triggered.

      Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

    7. Actionable comments posted: 1

      🧹 Nitpick comments (1)
      packages/start-server-core/src/request-response.ts (1)

      117-129: Remove unsafe as T assertions by widening return type to include Response.

      The as T casts at lines 122 and 129 bypass type safety—if attachResponseHeaders were called with a generic T other than Response, the error handlers would return Response rather than T, and the assertions would hide the mismatch.

      Change the return type from MaybePromise<T> to MaybePromise<T | Response> and remove the unsafe casts. This is safe because the sole caller at line 152 passes handler()'s return value (which is Promise<Response> | Response, making T = Response), and widening to Response | Response (i.e., Response) remains compatible with h3_toResponse.

      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/start-server-core/src/request-response.ts` around lines 117 - 129,
      The function attachResponseHeaders currently returns MaybePromise<T> but uses
      unsafe "as T" casts when returning Response objects; change its signature to
      return MaybePromise<T | Response>, remove the "as T" casts in both places inside
      the error handling branches (the branch handling error instanceof Response and
      the final Response return), and update any local typing within
      attachResponseHeaders to accept returning Response directly (no assertions).
      Keep all other behavior the same; this widens the return type safely and
      eliminates the unsafe casts.
      🤖 Prompt for all review comments with AI agents
      Verify each finding against the current code and only fix it if needed.
      
      Inline comments:
      In `@packages/start-server-core/src/request-response.ts`:
      - Around line 113-129: The error-handler currently returns a new Response
      directly inside the rejected-path lambda (the arrow function handling (error) =>
      { ... }) which bypasses mergeEventResponseHeaders and can drop headers like
      Set-Cookie placed on event.res.headers; update the rejected-path to create the
      Response as before but then call mergeEventResponseHeaders(event.res.headers,
      response) (or the equivalent helper used on the fulfilled path) and return that
      merged response so any cookies or headers added to event.res.headers are
      preserved.
      
      ---
      
      Nitpick comments:
      In `@packages/start-server-core/src/request-response.ts`:
      - Around line 117-129: The function attachResponseHeaders currently returns
      MaybePromise<T> but uses unsafe "as T" casts when returning Response objects;
      change its signature to return MaybePromise<T | Response>, remove the "as T"
      casts in both places inside the error handling branches (the branch handling
      error instanceof Response and the final Response return), and update any local
      typing within attachResponseHeaders to accept returning Response directly (no
      assertions). Keep all other behavior the same; this widens the return type
      safely and eliminates the unsafe casts.

      ℹ️ Review info

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro

      📥 Commits

      Reviewing files that changed from the base of the PR and between 77c50ffbc704c79b200994d6c9047603744b7c14 and 82215e5cabab9b8bdfae150e151677ede01f49fd.

      📒 Files selected for processing (2)
      • packages/start-server-core/src/request-response.ts
      • packages/start-server-core/tests/request-response.test.ts
      🚧 Files skipped from review as they are similar to previous changes (1)
      • packages/start-server-core/tests/request-response.test.ts
      OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)
    8. djk01281(GitHub profile, opens in a new tab)replied on packages/start-server-core/src/request-response.ts lines 113 to 129

      fixed in 9825a28 .

    9. coderabbitai[bot](GitHub profile, opens in a new tab)replied on packages/start-server-core/src/request-response.ts lines 113 to 129

      @djk01281, thank you for fixing the issue! The call to mergeEventResponseHeaders will now ensure that cookies and headers set on event.res.headers are properly preserved even when the handler throws. 🎉

      ((
      ( -.-) o_(")(") Happy hopping!


      🧠 Learnings used
      Learnt from: hokkyss
      Repo: TanStack/router PR: 6394
      File: e2e/react-start/server-functions/src/routes/function-method/index.tsx:93-95
      Timestamp: 2026-01-17T08:01:35.654Z
      Learning: In TanStack Router e2e server function test files (e.g., files in `e2e/react-start/server-functions`, `e2e/solid-start/server-functions`, `e2e/vue-start/server-functions`), unhandled promise rejections in server function calls (e.g., `fn().then(setResult)` without `.catch()`) are intentional test behavior to make test failures visible in the test runner, consistent with existing patterns like in `e2e/react-start/server-functions/src/routes/factory/index.tsx`.

      If you found this review helpful, would you consider giving us a shout-out on X?

      Thank you for using CodeRabbit!

    10. we need a greater refactor of header, statuscode merging. this wont be enough

    11. Thanks, I see what you mean : )

      In the meantime, should I keep this open or close it?

Sign in to join this conversation.