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

Viewed 6852

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);
      }
    } 
}
1 Answers

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: '4mb' // 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.

Related