Skip to content

Commit c7e109c

Browse files
committed
fix(start-server-core): return a Response to non-RPC server function callers
A server function invoked through `serverFn.url`, for example as the action of a native HTML form, does not send the `x-tsr-serverFn` header that the RPC fetcher sends. That branch returned `res.result || res.error` directly, so a handler that returned a plain object, returned nothing, or produced an error handed a raw JS value back to the HTTP layer. `getFinalResponse` then found no response on the context and threw ERR_NO_RESPONSE, surfacing as an unhandled 500 with "It looks like you forgot to return a response from your server route handler". Only handlers that returned a `Response` worked. Every caller went through the serialization path before the middleware refactor in #5517, which added this shortcut. Restrict the shortcut to values that are already a `Response`, which includes redirects since `redirect()` returns a `Response` subclass, and let everything else fall through to `serializeResult`. RPC callers are untouched, and a handler-provided `Response` still reaches a browser without the internal `x-tss-raw` marker.
1 parent 37877da commit c7e109c

4 files changed

Lines changed: 173 additions & 4 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@tanstack/start-server-core': patch
3+
---
4+
5+
Fix a server function used as a form action failing with "It looks like you forgot to return a response from your server route handler" unless its handler returned a `Response`. A native form submission does not send the RPC header, and that path returned the handler's raw value straight to the HTTP layer. Non-RPC callers now receive a serialized `Response`, while a handler-provided `Response` or `redirect()` is still passed through untouched.

‎docs/start/framework/react/guide/server-functions.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,8 @@ Return `Response` objects binary data, or custom content types.
396396

397397
Use server functions without JavaScript by leveraging the `.url` property with HTML forms.
398398

399+
A native form submission is not an RPC call, so the response goes to the browser rather than to the client runtime. Return a `Response`, or a `redirect()`, to control what the browser does next. A redirect is the usual choice, because it sends the browser to a real page instead of leaving it on the server function URL. Any other serializable return value is sent as a JSON body, which the browser will display as-is.
400+
399401
### Middleware
400402

401403
Compose server functions with middleware for authentication, logging, and shared logic. See the [Middleware guide](./middleware.md).

‎packages/start-server-core/src/server-functions-handler.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -166,10 +166,17 @@ export const handleServerAction = async ({
166166
}
167167

168168
if (!isServerFn) {
169-
return unwrapped
170-
}
171-
172-
if (unwrapped instanceof Response) {
169+
// Non-RPC callers, such as a native form submission that posts to
170+
// `serverFn.url` or a direct HTTP request, get the handler's own
171+
// Response (including a redirect) untouched. Any other value still
172+
// has to be serialized: returning it raw lets a plain JS value escape
173+
// to the HTTP layer, which then fails the request with "you forgot to
174+
// return a response from your server route handler" instead of
175+
// delivering the result.
176+
if (unwrapped instanceof Response) {
177+
return unwrapped
178+
}
179+
} else if (unwrapped instanceof Response) {
173180
if (isRedirect(unwrapped)) {
174181
return unwrapped
175182
}
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
// @vitest-environment node
2+
import { beforeEach, describe, expect, test, vi } from 'vitest'
3+
4+
const action = vi.fn()
5+
6+
vi.mock('../src/getServerFnById', () => ({
7+
getServerFnById: vi.fn(async () => action),
8+
}))
9+
10+
const { handleServerAction } = await import('../src/server-functions-handler')
11+
const { requestHandler } = await import('../src/request-response')
12+
const { runWithStartContext } = await import('@tanstack/start-storage-context')
13+
14+
const SERVER_FN_ID = 'test-server-fn'
15+
16+
/**
17+
* Invoke `handleServerAction` the way the request pipeline does, and hand back
18+
* whatever it returned so the test can assert on the raw value. The pipeline
19+
* requires a Response, so returning anything else is the defect under test.
20+
*/
21+
async function invokeServerFn(options: {
22+
returns: { result?: unknown; error?: unknown }
23+
/** Set the header the RPC client sends. Native form posts do not send it. */
24+
rpc?: boolean
25+
}) {
26+
action.mockImplementation(async () => options.returns)
27+
28+
const headers: Record<string, string> = {
29+
'Content-Type': 'application/x-www-form-urlencoded',
30+
}
31+
if (options.rpc) {
32+
headers['x-tsr-serverFn'] = 'true'
33+
}
34+
35+
const request = new Request(`http://localhost/_serverFn/${SERVER_FN_ID}`, {
36+
method: 'POST',
37+
headers,
38+
body: 'name=Sean',
39+
})
40+
41+
let returned: unknown
42+
const handler = requestHandler(async () =>
43+
runWithStartContext(
44+
{
45+
getRouter: () => ({}) as any,
46+
request,
47+
startOptions: {},
48+
contextAfterGlobalMiddlewares: {},
49+
executedRequestMiddlewares: new Set(),
50+
handlerType: 'serverFn',
51+
},
52+
async () => {
53+
returned = await handleServerAction({
54+
request,
55+
context: {},
56+
serverFnId: SERVER_FN_ID,
57+
})
58+
return new Response('unused')
59+
},
60+
),
61+
)
62+
63+
await handler(request, {})
64+
return returned
65+
}
66+
67+
beforeEach(() => {
68+
action.mockReset()
69+
Object.assign(action, { method: 'POST' })
70+
})
71+
72+
describe('handleServerAction with a non-RPC caller', () => {
73+
test('serializes a plain object into a Response', async () => {
74+
const returned = await invokeServerFn({ returns: { result: { ok: true } } })
75+
76+
expect(returned).toBeInstanceOf(Response)
77+
const response = returned as Response
78+
expect(response.status).toBe(200)
79+
expect(response.headers.get('Content-Type')).toBe('application/json')
80+
await expect(response.text()).resolves.toContain('ok')
81+
})
82+
83+
test('returns a Response for a handler that returns nothing', async () => {
84+
const returned = await invokeServerFn({ returns: { result: undefined } })
85+
86+
expect(returned).toBeInstanceOf(Response)
87+
expect((returned as Response).status).toBe(200)
88+
})
89+
90+
test('returns a Response when the handler produced an error', async () => {
91+
const returned = await invokeServerFn({
92+
returns: { result: undefined, error: new Error('boom') },
93+
})
94+
95+
expect(returned).toBeInstanceOf(Response)
96+
})
97+
98+
test('passes a handler-provided Response through untouched', async () => {
99+
const returned = await invokeServerFn({
100+
returns: {
101+
result: new Response('done', {
102+
status: 201,
103+
headers: { 'Content-Type': 'text/plain' },
104+
}),
105+
},
106+
})
107+
108+
expect(returned).toBeInstanceOf(Response)
109+
const response = returned as Response
110+
expect(response.status).toBe(201)
111+
expect(response.headers.get('Content-Type')).toBe('text/plain')
112+
// A non-RPC caller is a browser or an external client, so the internal
113+
// raw-response marker must not be added.
114+
expect(response.headers.get('x-tss-raw')).toBeNull()
115+
await expect(response.text()).resolves.toBe('done')
116+
})
117+
118+
test('passes a redirect Response through untouched', async () => {
119+
const { redirect } = await import('@tanstack/router-core')
120+
const returned = await invokeServerFn({
121+
returns: { result: redirect({ href: '/after-submit', statusCode: 302 }) },
122+
})
123+
124+
expect(returned).toBeInstanceOf(Response)
125+
const response = returned as Response
126+
expect(response.status).toBe(302)
127+
expect(response.headers.get('Location')).toBe('/after-submit')
128+
})
129+
})
130+
131+
describe('handleServerAction with the RPC client', () => {
132+
test('still serializes a plain object', async () => {
133+
const returned = await invokeServerFn({
134+
returns: { result: { ok: true } },
135+
rpc: true,
136+
})
137+
138+
expect(returned).toBeInstanceOf(Response)
139+
const response = returned as Response
140+
expect(response.headers.get('Content-Type')).toBe('application/json')
141+
expect(response.headers.get('x-tss-serialized')).toBe('true')
142+
})
143+
144+
test('still marks a raw Response for the client to unwrap', async () => {
145+
const returned = await invokeServerFn({
146+
returns: { result: new Response('done', { status: 201 }) },
147+
rpc: true,
148+
})
149+
150+
expect(returned).toBeInstanceOf(Response)
151+
const response = returned as Response
152+
expect(response.status).toBe(201)
153+
expect(response.headers.get('x-tss-raw')).toBe('true')
154+
})
155+
})

0 commit comments

Comments
 (0)