Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multer doesn't return req.body and req.file using next-connect

I'm using nextjs and I want to upload a file so I used next-connect in order to use multer

import nc from "next-connect";
import multer from "multer";

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

const upload = multer({ dest: `${__dirname}../../public` });

const handler = nc()
  .use(upload.single('image'))
  .post(async (req, res)=>{
    console.log(req.body); // undefined
    console.log(req.file); // undefined
    res.status(200).send("yo");
  })


export default handler;

this is the client side code :

function handleOnSubmit(e){
        e.preventDefault();

        const data = {};

        var formData = new FormData(e.target);
        for (const [name,value] of formData) {
            data[name] = value;
        }
        data.type = data.type[0].toUpperCase();
        data.name = data.name[0].toUpperCase();

        axios({
            method: "POST",
            url:"/api/manager",
            data,
            config: {
                headers: {
                    'content-type': 'multipart/form-data'
                }
            }
        })
        .then(res=>{
            console.log(res);
        })
        .catch(err=>{
            throw err
        });
    }
...
return(
   ...
   <Form onSubmit={(e)=>handleOnSubmit(e)}>
   ...
   </Form>
)

I searched and everything I found was related to nodejs and expressjs but nothing on next.js. I have no idea about how to proceed.

like image 300
Eye Patch Avatar asked Sep 01 '25 16:09

Eye Patch


1 Answers

for those who are still looking for a solution on how to use multer as middleware with nextJs, here is an example of an API route, using multer has middleware. The route is calling a getSignedUrl function to upload file to bucket.

running nextJs v12 and multer 1.4.3

import multer from "multer";
import { NextApiRequest, NextApiResponse } from "next";
import { getSignedUrl } from "../../lib/uploadingToBucket";

function runMiddleware(
  req: NextApiRequest & { [key: string]: any },
  res: NextApiResponse,
  fn: (...args: any[]) => void
): Promise<any> {
  return new Promise((resolve, reject) => {
    fn(req, res, (result: any) => {
      if (result instanceof Error) {
        return reject(result);
      }

      return resolve(result);
    });
  });
}

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

const handler = async (
  req: NextApiRequest & { [key: string]: any },
  res: NextApiResponse
): Promise<void> => {
  //const multerStorage = multer.memoryStorage();
  const multerUpload = multer({ dest: "uploads/" });

  await runMiddleware(req, res, multerUpload.single("file"));
  const file = req.file;
  const others = req.body;
  const signedUrl = await getSignedUrl(others.bucketName, file.filename);
   res.status(200).json({ getSignedUrl: signedUrl });
};

export default handler;
like image 136
Jerome Avatar answered Sep 06 '25 15:09

Jerome