1

I cannot receive the request body on the NextJS server from my NextJS client.

Client:

import { NextPage } from 'next';
import { v4 } from 'uuid';

const submit = async (event: any) => {
 event.preventDefault();
 const postID = v4();
 const inputElem = document.getElementById('imgfile') as HTMLInputElement;

 // @ts-ignore
 const file = inputElem!.files[0];
 let blob = file.slice(0, file.size, 'image/jpeg');
 let newFile = new File([blob], `${postID}_image.jpeg`, {
   type: 'image/jpeg',
 });
 let formData = new FormData();
 formData.append('imgfile', newFile);

 const response = await fetch('/api/hello', {
   method: 'POST',
   headers: {
     'Content-Type': 'multipart/form-data',
   },
   body: formData,
 });
};

const SubmitPicture: NextPage = () => {
 return (
   <div>
     <h2>Google Storage API Test</h2>
     <input type="file" name="imgfile" accept="image/jpeg" id="imgfile" />
     <button onClick={submit}>Submit</button>
   </div>
 );
};

export default SubmitPicture;

Server :

import nextConnect from 'next-connect';
export default nextConnect().post(async (req: any, res: any) => {
  res.status(200).json('Everything is ok');
  
});

The problem is that server just ignores the requests with the formData body. If I would send a request without body to the same place, it would return status 200 to me.

I have spent half of the day on it and a bit desperate.

  • Does this help answer your question: [next.js file upload via api routes / formidable - not working](https://stackoverflow.com/questions/60020241/next-js-file-upload-via-api-routes-formidable-not-working). You need to disable Next.js built-in body parser on the API route. – juliomalves May 25 '22 at 17:17

1 Answers1

0

form-data is not a regular POST request with a body. You need to use a middleware like formidable to parse it.


Follow these steps to accept multipart/form-data in NextJS Server

Install formidable

npm i formidable

Install next-connect

This is a middleware library for NextJS

npm i next-connect

Implement the NextJS API Handler

import formidable from 'formidable';
import nextConnect from 'next-connect';

const form = formidable({ multiples: true }); // uploaded files will be an array

// Middleware
async function parseMultipartForm(req, res, next) {
  if (req.headers['content-type'] && req.headers['content-type'].indexOf('multipart/form-data') !== -1) {
    form.parse(req, (err, fields, files) => {
      if (!err) {
        req.body = fields;
        req.files = files;
      }
      next();
    });
  } else {
    next();
  }
}

// Disable NextJS body parsing
export const config = {
  api: {
    bodyParser: false,
  },
};

// Handler
const handler = nextConnect({})
  .use(parseMultipartForm)
  .post((req, res) => {
    // req.files will be an array of files
    // Do something with the files
  });

export default handler;

Client-side is the same

 let formData = new FormData();
 formData.append('imgfile', newFile);

 const response = await fetch('/api/hello', {
   method: 'POST',
   body: formData,
 });
Brian
  • 1,056
  • 9
  • 15
  • what is your next version? next12 allows only root middleware and i tried on root middleware. but got error ``` Critical dependency: the request of a dependency is an expression error - Error: The edge runtime does not support Node.js 'events' module. ``` – Sacru2red Jan 18 '23 at 07:20
  • I'm using Next13 – Brian Jan 18 '23 at 14:34