Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Body exceeded 1mb limit error in Next.js API route

If I use FormData on Next.js to upload image to server I always get this error.

I tried a lot but I didn't fix this.

My code:

const changeValue = (e) => {
if (e.target.name === "avatar") {
      const file = e.target.files[0];
      const formData = new FormData();
      formData.append("image", file, file.name);
      try {
        const config = {
          Headers: {
            "Content-Type": "multipart/form-data",
          },
        };
        axios
          .post("/api/upload", formData, config)
          .then((res) => {
            setAvatar(res.data);
            setAvatarPreview(res.data);
          })
          .catch((err) => {
            console.log(err.message);
          });
      } catch (err) {
        console.log(err);
      }
    } 
}
like image 716
Rawand122 Avatar asked Sep 06 '25 03:09

Rawand122


1 Answers

API routes in page router

The default size limit for the body parser is 1mb in API routes. You can modify this value through the custom config object exported from the API route.

// /pages/api/upload.js

export const config = {
    api: {
        bodyParser: {
            sizeLimit: '2mb' // Set desired value here
        }
    }
}

Note that there's a limit imposed on the API routes body size, see How to override the 4mb API Routes body size limit? for details.


Server Actions in app router

The same default size limit of 1mb is applied to Server Actions. You can modify this value using the serverActions.bodySizeLimit option in next.config.js.

// next.config.js

module.exports = {
    serverActions: {
        bodySizeLimit: '2mb' // Set desired value here
    }
}
like image 53
juliomalves Avatar answered Sep 07 '25 22:09

juliomalves