Search code examples
reactjsnode.jsnext.jsform-databun

TypeError: FormData parse error missing final boundary


Recently, I have migrated a Next.js project from node to bun. Unfortunately, I get this error while trying to parse form data:

14 | const POST = async (request)=>{
15 |     try {
16 |         console.log("request: ", await request.headers);
17 |         const formData = await request.formData();
                                    ^
TypeError: FormData parse error missing final boundary
      at processTicksAndRejections (:61:77)

From a few searches, it seems that this error occurs, when the Content-Type is erroneously overwritten while fetching. However, this doesn't happen here. This is the form component triggering the POST:

  /// ...
  return (
    <form
      action={action}
      method="post"
      className="mt-4"
      onSubmit={async (e) => {
        e.preventDefault();
        setLoading(true);
        setErrors(null);
        const formData = new FormData(e.currentTarget);
        const response = await fetch(action, {
          method: "POST",
          body: formData,
          redirect: "manual",
        });

        if (response.status === 0) {
          // redirected
          // when using `redirect: "manual"`, response status 0 is returned
          return router.refresh();
        }
        setErrors(await response.json());
        setLoading(false);
      }}
    >);

The header also properly shows the Content-Type:

request:  Headers {
  "host": "localhost:3000",
  "accept": "*/*",
  "accept-language": "en-GB,en;q=0.9",
  "accept-encoding": "gzip, deflate",
  "sec-fetch-mode": "cors",
  "content-type": "multipart/form-data; boundary=----WebKitFormBoundary2sBEsUtE1u6eArLT",
  "origin": "http://localhost:3000",
  "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15",
  "referer": "http://localhost:3000/sign-up",
  "content-length": "244",
  "connection": "keep-alive",
  "sec-fetch-dest": "empty",
  "sec-fetch-site": "same-origin",
  "x-forwarded-host": "localhost:3000",
  "x-forwarded-port": "3000",
  "x-forwarded-proto": "http",
}

The backend code is also pretty normal:

// ...
export const POST = async (request: Request) => {
  try {
    console.log('request: ', await request.headers)
    const formData = await request.formData();
    // console.log('request form data: ', JSON.stringify(request));
    const username = formData.get("username");
    const password = formData.get("password");
// ...

Appreciate the help!


Solution

  • Okay, so it turned out this is an issue in bun itself. I completely replaced bun with node and it fixed the problem. See more at https://github.com/oven-sh/bun/issues/2644.