question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Parsing multipart form data not working with Next.js

See original GitHub issue

Support plan

  • Which support plan is this issue covered by? (Community, Sponsor, Enterprise): Community
  • Currently blocking your project/work? (yes/no): yes
  • Affecting a production system? (yes/no): no

Context

  • Node.js version: v16.13.1
  • Release Line of Formidable (Legacy, Current, Next): Current
  • Formidable exact version: 2.0.1
  • Environment (node, browser, native, OS): node
  • Used with (popular names of modules): Next.js

What are you trying to achieve or the steps to reproduce?

I am trying to handle the following multipart form data submission:

--part-delimiter
Content-Disposition: form-data; name="santa-claus"
Content-Type: application/json
{
    "collector": "Santa Claus",
    "collectedAt": "2022-02-17T17:17:55.764Z",
    "latitude":90,
    "longitude":0
}
--part-delimiter
Content-Disposition: form-data; name="mrs-claus"
Content-Type: application/json
{
    "collector": "Mrs Claus",
    "collectedAt": "2022-03-17T17:17:55.764Z",
    "latitude":90,
    "longitude":1
}
--part-delimiter--

The request is being sent with Postman and includes the header Content-Type: multipart/related; boundary=part-delimiter.

I am using this code to handle the request:

export default async function (req: NextApiRequest, res: NextApiResponse) {
  switch (req.method) {
    case 'POST':
      const form = formidable({});
      form.parse(req, (error, fields, files) => {
        if (error) {
          console.error(error);
          res.status(500).end();
          return;
        }
        console.log({ fields, files });
        res.status(200).end();
      });
    break;
  }
}

(NextApiRequest extends IncomingMessage, so the types are compatible)

What was the result you got?

The callback passed to form.parse is never called.

I’ve tried setting breakpoints to see what is going wrong, but I’m unable to figure it out. It appears that the data is being processed because this.write(buffer) is called (and the catch below doesn’t catch any errors). However, while initMultipart is called and a callback is registered to handle processing data (these lines are running), the callback is never called (i.e. a breakpoint set at the first line of the callback is never hit).

Eventually, when Formidable finishes processing the stream and gets to the check if (!this.ended || this._flushing || this.error), this.ended is undefined and thus the function returns and the parser is never informed that the parsing is done. (I tried removing the !this.ended check to see if maybe that just wasn’t set by the parser. This does lead the callback passed to form.parse to be called, but fields and files are then empty objects.)

What result did you expect?

I expected it to handle parsing the form and call the callback provided to form.parse, or at least throw an error.

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

4reactions
kylecombescommented, Jul 12, 2022

Well, I figured it out: Turns out the problem was Next.js automatically parsing the request body stream. The fix is simply to add the following to the end of my Next.js API route file:

export const config = {
  api: {
    bodyParser: false,
  },
};

I realized it had to be Next.js when I tried using the example code from the repo and it stopped working as soon as I involved Next.js. I feel like an idiot because this auto-parsing has been a problem for me in the past so I was aware of this behavior. But it’s fixed now!

0reactions
Freundschaftcommented, Jul 13, 2022

ok cool, i was just wondering if there was some built in parser already, but thanks 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

How could I use A Multipart-Form In Next.js using API Routes ...
I am facing the same problem, and I am already using the form-data package, it still doesn't work, it works if I use...
Read more >
POST multipart/form-data to Serverless Next.js API (running ...
You can use the multiparty package to parse multipart/form-data. The key is to also export a config object turning the bodyParser off.
Read more >
How To Use A Multipart-Form In Next.js Using API Routes
Currently in Next.js using /api routes there's no way to parse a multipart-form. What we can do is create a middleware to do...
Read more >
Processing third party form data in Next.js using Webhooks
How to receive JSON formatted multipart form data in a Next.js serverless function from a form service webhook, such as Jotform.
Read more >
Building Forms with Next.js
Learn how to create forms with Next.js, from the form HTML element to advanced concepts with React.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found