Skip to content
Source
Sign inSign up
TanStack/router

Server functions should not assume JSON payloads #3429

Closedanulman(GitHub profile, opens in a new tab) opened this issue 2 comments

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:

https://github.com/TanStack/router/blob/7d7681272992af88831cb513c23a7e60bccc129d/packages/start-server-functions-handler/src/index.tsx#L165-L170

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 :)

  1. anulman(GitHub profile, opens in a new tab) changed the title

  2. anulman(GitHub profile, opens in a new tab)commented

    FWIW, this is the patch we're using:

    diff --git a/dist/esm/index.js b/dist/esm/index.js
    index 4215f5c6e557fe6a0fc71a32303e99950145634b..ebdaa4717f0b34615e7ed41c335491454abe9c6c 100644
    --- a/dist/esm/index.js
    +++ b/dist/esm/index.js
    @@ -89,8 +89,14 @@ ServerFn Request: ${serverFnId}`);
               }
               return startSerializer.parse(search.payload);
             }
    -        const jsonPayloadAsString = await request.text();
    -        return startSerializer.parse(jsonPayloadAsString);
    +        // See https://github.com/TanStack/router/issues/3429
    +        const jsonPayloadAsString = await request.clone().text();
    +        const contentType = request.headers.get("Content-Type");
    +        if (!contentType || contentType.includes("application/json")) {
    +          return startSerializer.parse(jsonPayloadAsString);
    +        }
    +
    +        return void 0;
           })();
           const result = await action(arg);
           if (result instanceof Response) {
  3. you can return raw responses from server functions now with arbitrary content type

Sign in to join this conversation.