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

2

28

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);
      }
    } 
}
Organo answered 29/7, 2021 at 10:26 Comment(0)
A
57

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
    }
}
Algorithm answered 30/7, 2021 at 12:49 Comment(6)
I set 4.5mb, still I face the issue: #75527856Ermeena
@János See https://mcmap.net/q/503597/-how-to-override-the-4mb-api-routes-body-size-limit.Algorithm
Finally I started to use AWS Lambda as an alternative, right, there is no ither trick?!Ermeena
this is not working for me. nextjs version: 13.2.4Polyurethane
@ManjunathGk The above solution is for pages API routes. The new app router introduced in Next.js 13 doesn't seem to support it. See nextjs.org/docs/app/building-your-application/routing/….Algorithm
app router now has global option for serverActions.bodySizeLimit; nextjs.org/docs/app/api-reference/next-config-js/…Galvanic
R
-1

My application is frontended by nginx so I had to change /etc/nginx/nginx.conf file to allow upload files up to 10mb.

http {
    sendfile on;
    tcp_nopush on;
    types_hash_max_size 2048;
    client_max_body_size 10M;
    ...
}
Rockabilly answered 10/2, 2024 at 12:39 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.