Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read FormData in NextJS

I'd like to read fetch's body. Here's what I send:

fetch('/api/foo', {
  method: 'POST',
  body: new FormData(formRef.current),
});

enter image description here

And now I only need to parse the body. But I don't know how. I can't use FormData on the server side, because it says ReferenceError: FormData is not defined. And I can't also use forEach like on the client.

What should I do?

export default function sendMail(req: NextApiRequest, res: NextApiResponse): void {
    // console.log(req.body instanceof FormData);
    // req.body.forEach(console.log);
    console.log(req.body['name']);
    res.status(200).json({});
}
like image 786
Ivan Adanenko Avatar asked May 10 '26 09:05

Ivan Adanenko


2 Answers

You could use formidable.

npm install formidable

Then in your code use

import { NextApiRequest, NextApiResponse } from 'next'
import { Formidable } from "formidable";

//set bodyparser
export const config = {
  api: {
    bodyParser: false
  }
}

export default async (req: NextApiRequest, res: NextApiResponse) => {
  const data = await new Promise((resolve, reject) => {
    const form = new Formidable();

    form.parse(req, (err, fields, files) => {
      if (err) reject({ err })
      resolve({ err, fields, files })
    }) 
  })

  //return the data back or just do whatever you want with it
  res.status(200).json({
    status: 'ok',
    data
  })
}
like image 117
rottitime Avatar answered May 12 '26 22:05

rottitime


If you are using route-handlers of NextJS, you can do the following :

export async function POST(request: NextRequest) {
  const formData = await request.formData();
  const email = formData.get('email');
  const password = formData.get('password');
  return NextResponse.json({
    message: 'Logged in successfully'
  });
}
like image 42
Midhun Darvin Avatar answered May 12 '26 21:05

Midhun Darvin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!