Skip to content

Mixing FormData with other JSON fields breaks File fields #4133

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
carderne opened this issue May 10, 2025 · 1 comment
Open

Mixing FormData with other JSON fields breaks File fields #4133

carderne opened this issue May 10, 2025 · 1 comment

Comments

@carderne
Copy link

Which project does this relate to?

Start

Describe the bug

Files in FormData get mangled if the FormData is sent along with anything else.

This works:

const uploadFileFn = createServerFn({ method: "POST" })
  .validator((formData) => {
    const fileName = formData.get("file").name;

But this doesn't:

const uploadFileFn = createServerFn({ method: "POST" })
  .validator(({ id, formData }) => {
    const name = formData.get("file").name;

But accessing non-file FormData entries is fine:

const uploadFileFn = createServerFn({ method: "POST" })
  .validator(({ id, formData }) => {
    const name = formData.get("name");

Your Example Website or App

https://gist.github.com/carderne/8ff24cc001e2b7ca07983715f68139a0

Steps to Reproduce the Bug or Issue

Full reproduction component:

import { createServerFn } from "@tanstack/react-start";

const uploadFileFn = createServerFn({ method: "POST" })
  .validator(({ formData }: { id: string; formData: FormData }) => {
    const name = (formData.get("doc") as File).name;
    // name is undefined
    return name;
  })
  .handler(async () => {});

export function TanstackUploadFileBroken() {
  return (
    <form
      onSubmit={async (e) => {
        e.preventDefault();
        const formData = new FormData(e.currentTarget);
        await uploadFileFn({ data: { id: "", formData } });
      }}
    >
      <input type="file" name="doc" accept="*" />
      <button>Submit</button>
    </form>
  );
}

Expected behavior

I expected it to work the same for Files as for other Form fields.

Screenshots or Videos

No response

Platform

@tanstack/react-router: 1.120.3
@tanstack/react-start: 1.120.3

Additional context

No response

@akawahuynh
Copy link

@carderne

you can't pass a formData to a plain JavaScript object, while the fetch API doesn't accept such an object for the body, or you split it into 2 createServerFn(): fordatacreateServerFn() and idcreateServerFn()

or:

const formData = new FormData(e.currentTarget);
formData.append("id", "123");
await uploadFileFn({ data: formData });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants