fix(start-server-core): preserve status code when handler throws after setResponseStatus #6785
main fromrefs/pull/6785/head·opened 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
View your CI Pipeline Execution ↗ for commit 9825a287538ea4a164a05f3c01e3f397d1a7067a
Command Status Duration Result nx run tanstack-router-e2e-bundle-size:build --...✅ Succeeded 1m 28s View ↗
☁️ Nx Cloud last updated this comment at
2026-02-28 06:31:09UTCBundle Size Benchmarks#
- Commit:
de66f0e0a0d6 - Measured at:
2026-02-28T06:30:11.509Z - Baseline source:
history:442ada1f6432 - Dashboard: bundle-size history
Scenario Current (gzip) Delta vs baseline Raw Brotli Trend react-router.minimal86.58 KiB 0 B (0.00%) 272.45 KiB 75.22 KiB ▁▂▂▂▂▂▂▂▇▇█ react-router.full89.61 KiB 0 B (0.00%) 282.78 KiB 77.90 KiB ▂▁▁▁▂▂▂▂▇▇█ solid-router.minimal35.88 KiB 0 B (0.00%) 107.56 KiB 32.26 KiB ▁▂▂▂▅▅▅▅▇▇█ solid-router.full40.21 KiB 0 B (0.00%) 120.61 KiB 36.13 KiB ▁▃▃▃▅▅▅▅▇▇█ vue-router.minimal51.75 KiB 0 B (0.00%) 147.54 KiB 46.50 KiB ▁▂▂▂▅▅▅▅▇▇█ vue-router.full56.55 KiB 0 B (0.00%) 163.12 KiB 50.86 KiB ▁▂▂▂▅▅▅▅▇▇█ react-start.minimal99.11 KiB 0 B (0.00%) 311.58 KiB 85.68 KiB ▁▂▂▂▂▂▂▂▆▆█ react-start.full102.49 KiB 0 B (0.00%) 321.36 KiB 88.62 KiB ▁▂▂▂▂▂▂▂▆▆█ solid-start.minimal48.19 KiB 0 B (0.00%) 145.13 KiB 42.67 KiB ▁▃▃▃▅▅▅▅▇▇█ solid-start.full53.67 KiB 0 B (0.00%) 161.05 KiB 47.33 KiB ▁▂▂▂▅▅▅▅▇▇█ Trend sparkline is historical gzip bytes ending with this PR measurement; lower is better.
- Commit:
🧹 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:
- Error message preservation: When throwing an
Error, verify the response body contains the error message. - Response headers/body preservation: When throwing a
ResponseaftersetResponseStatus, verify the original headers and body are preserved. - 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.tspackages/start-server-core/tests/request-response.test.ts
- Error message preservation: When throwing an
@coderabbitai review
✅ 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.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/start-server-core/src/request-response.ts (1)
117-129: Remove unsafeas Tassertions by widening return type to includeResponse.The
as Tcasts at lines 122 and 129 bypass type safety—ifattachResponseHeaderswere called with a genericTother thanResponse, the error handlers would returnResponserather thanT, and the assertions would hide the mismatch.Change the return type from
MaybePromise<T>toMaybePromise<T | Response>and remove the unsafe casts. This is safe because the sole caller at line 152 passeshandler()'s return value (which isPromise<Response> | Response, makingT = Response), and widening toResponse | Response(i.e.,Response) remains compatible withh3_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.tspackages/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
@@ -111,0 +109,21 @@109+ mergeEventResponseHeaders(resolved, event)110+ }111+ return resolved112+ },113+ (error) => {114+ const eventStatus = event.res.status115+ if (eventStatus) {116+ const eventStatusText = event.res.statusText117+ if (error instanceof Response) {118+ return new Response(error.body, {119+ status: eventStatus,120+ statusText: eventStatusText || error.statusText,121+ headers: error.headers,122+ }) as T123+ }124+ const message =125+ error instanceof Error ? error.message : String(error)126+ return new Response(message, {127+ status: eventStatus,128+ statusText: eventStatusText || '',129+ }) as T⚠️ Potential issue | 🟠 Major
Rejected-path responses skip
mergeEventResponseHeaders, soSet-Cookiecan be lost on non-OK throws.On Lines 117-129, the newly created
Responseis returned directly. Unlike the fulfilled path, this bypassesmergeEventResponseHeaders, so cookies written toevent.res.headersbefore the throw may not reach the client.Proposed fix
(error) => { const eventStatus = event.res.status if (eventStatus) { const eventStatusText = event.res.statusText - if (error instanceof Response) { - return new Response(error.body, { - status: eventStatus, - statusText: eventStatusText || error.statusText, - headers: error.headers, - }) as T - } - const message = - error instanceof Error ? error.message : String(error) - return new Response(message, { - status: eventStatus, - statusText: eventStatusText || '', - }) as T + const response = + error instanceof Response + ? new Response(error.body, { + status: eventStatus, + statusText: eventStatusText || error.statusText, + headers: error.headers, + }) + : new Response( + error instanceof Error ? error.message : String(error), + { + status: eventStatus, + statusText: eventStatusText || '', + }, + ) + mergeEventResponseHeaders(response, event) + return response as T } throw error },🤖 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 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.✅ Addressed in commit 9825a28
fixed in 9825a28 .
@djk01281, thank you for fixing the issue! The call tomergeEventResponseHeaderswill now ensure that cookies and headers set onevent.res.headersare 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!
djk01281(GitHub profile, opens in a new tab)replied on
packages/start-server-core/src/request-response.tslines 113 to 129fixed in 9825a28 .
coderabbitai[bot](GitHub profile, opens in a new tab)replied on
packages/start-server-core/src/request-response.tslines 113 to 129@djk01281, thank you for fixing the issue! The call tomergeEventResponseHeaderswill now ensure that cookies and headers set onevent.res.headersare 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!
we need a greater refactor of header, statuscode merging. this wont be enough
Thanks, I see what you mean : )
In the meantime, should I keep this open or close it?
Sign in to join this conversation.
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)
📝 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#
packages/start-server-core/src/request-response.tsResponse, 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.packages/start-server-core/tests/request-response.test.tssetResponseStatuspersists across thrownError, thrownResponse, and returned non-Responsevalues; verifies default 500 when no status set; and checks request-context access errors.Estimated code review effort#
🎯 3 (Moderate) | ⏱️ ~20 minutes
Possibly related PRs#
attachResponseHeadersand related response/status propagation behavior; strongly related to the same rejection/status handling changes.Poem#
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
#5107.#5107: adds rejection handler in attachResponseHeaders() to preserve setResponseStatus() when handlers throw Error or Response objects, with comprehensive unit tests validating the fix.#5107: modifications to attachResponseHeaders() rejection path, header merging, and comprehensive tests for the specific issue with no unrelated alterations.✨ Finishing Touches
🧪 Generate unit tests (beta)
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