request.formData() on NextJs 13 RouterHandler throws error

Problematic endpoint: https://sensational-truffle-8607b2.netlify.app/api/bugs
Method: POST

Snippet of code:

import FormData from 'form-data';

export async function POST(request) {
  let data = await request.formData() // This line throws an error
  
  // Do something with data
}

Building the form data itself works fine, but parsing the form data on NextJs 13’s RouteHandler is the problematic one. It works fine when i use other deployment and hosting services but fails to work on netlify.

Hi @Mozzarella99, welcome and thanks for the post.
Are you trying to parse a form data which contains an image or file?

Thanks.

Hi yes that’s my intention. But even without the file, it is not working.

Hi @Mozzarella99, thanks for the feedback. Kindly share a snippet of the form submit handler from your form or the error message that is thrown?

If possible can you share your repository as well for me help with the debugging.

Thanks.

You can submit a post request to this URL here: https://brilliant-lollipop-876008.netlify.app/api/hello
Any content for the form is fine.

This is the repository: GitHub - HubertHalim/test-bug

Hi @Mozzarella99, thanks for sharing the extra information. The reason why response.formData is throwing an error is because Next.js 13 App Router is still in beta.
There are 2 ways to resolve the issue.

1 Use request.body to parse the form data

export async function GET(request) {
  return new Response('Hello, Next.js!')
}

export async function POST(request) {

  try {
    let data = await request.body;
  } catch (e) {
    console.log(e)
    return new Response("fail")
  }

  return new Response("success")

2 Use the experimental-edge configuration and send your form data as multipart/form-data OR application/x-www-form-urlencoded

// Make sure you send your form data as multipart/form-data 
// OR application/x-www-form-urlencoded from the front-end.

export const config = { runtime: 'experimental-edge' }

export async function GET(request) {
  return new Response('Hello, Next.js!')
}

export async function POST(request) {

  try {
    let data = await request.formData();
  } catch (e) {
    console.log(e)
    return new Response("fail")
  }

  return new Response("success")
}

Make the changes and then redeploy again to see if it works.

Let me know the outcome.

Thanks.

2 Likes

@clarnx i tried your request.body parse way and when i log the data it give me this

ReadableStream { locked: false, state: 'readable', supportsBYOB: false }

can you help me in how can i get the data from that ReadableStream

Hi @dungkhoaito1, welcome.

Instead of request.body try const body = await request.json()

Thanks.

2 Likes

thank you so much, it works for now !

1 Like

glad you found your solution!

let data = await request.formData();

thx, this worked mate :slight_smile:.

1 Like

Welcome to the community! I’m glad you found the solution helpful. (:

1 Like