Server functions should not assume JSON payloads #3429
Hi team! I'm writing a server function that's meant to take data as a text/plain, and set this as my content type. A toy example might look like:
const echoText = createServerFn({ method: "POST" }).handler(async () => {
const request = getWebRequest();
const text = await request.text();
return new Response(`echo: ${text}`, {
status: 200,
headers: { "Content-Type": "text/plain" },
})
});
const MyForm = () => (
<form
action={echoText.url}
method="POST"
onSubmit={(e) => {
const form = e.target as HTMLFormElement;
const url = e.target.getAttribute("action");
if (!url) {
throw new Error("no action provided");
}
fetch(url, {
method: "POST",
body: "hello world",
headers: {
Accept: "text/plain",
"Content-Type": "text/plain",
},
})
.then(console.log)
.catch(console.error);
}}
>
<h2>My Toy Form</h2>
<button type="submit">Run</button>
</form>
);
Meanwhile, this code is throwing—presumably because the server function assumes any non-FormData-like content types must be JSON:
What do you think of changing this to something like
const payloadAsString = await request.text();
if (!payloadAsString) {
return void 0;
}
const contentType = request.headers.get("Content-Type");
if (!contentType || contentType === "application/json") {
return startSerializer.parse(payloadAsString);
}
return payloadAsString;
This would support all sorts of payload types! Although I guess it could be a bit more generic, and return Blobs, to support image / video / other binary types.
Really—any solution that doesn't throw on non-JSON data is great, since I can always read request.text() out of the server fn handler anyway.
I've patched the lib in my local project, but happy to support how I can in landing something like this so we don't have to maintain our patch :)
anulman(GitHub profile, opens in a new tab) changed the title
you can return raw responses from server functions now with arbitrary content type
Sign in to join this conversation.
FWIW, this is the patch we're using: