The Next.js API Route Body Exceeds Limit Error happens when a request’s body is too large for the server to process, causing the Next.js server to reject it.

Here are the common causes and how to fix them:

  1. Default Body Limit: Next.js, by default, limits the request body size to 1MB to prevent denial-of-service attacks. This is often too small for file uploads or large JSON payloads.

    • Diagnosis: This error doesn’t usually leave a specific log on the client or server side beyond the error message itself. You’d infer this is the cause if you’re sending data larger than 1MB.
    • Fix: Increase the body parser limit in your next.config.js file.
      // next.config.js
      module.exports = {
        api: {
          bodyParser: {
            sizeLimit: '4mb', // Set your desired limit, e.g., '4mb', '10mb', '50mb'
          },
        },
      };
      
    • Why it works: This configuration tells the underlying body parser (usually body-parser or its equivalent in the Node.js server) to accept larger bodies before it throws an error.
  2. Large File Uploads Without Streaming: If you’re uploading large files and buffering the entire file into memory before processing, you’re likely hitting memory limits or the body size limit.

    • Diagnosis: Monitor your server’s memory usage during uploads. If it spikes significantly and then the request fails, it’s a strong indicator.
    • Fix: Use a library like formidable or multer (if using Express middleware) to stream file uploads directly to disk or cloud storage without buffering the whole file in memory.
      // pages/api/upload.js
      import { IncomingForm } from 'formidable';
      import fs from 'fs';
      import path from 'path';
      
      export const config = {
        api: {
          bodyParser: false, // Disable Next.js's default body parser
        },
      };
      
      export default async (req, res) => {
        if (req.method === 'POST') {
          const form = new IncomingForm({
            uploadDir: './uploads', // Ensure this directory exists
            keepExtensions: true,
            maxFileSize: 10 * 1024 * 1024, // 10MB max file size
          });
      
          form.parse(req, async (err, fields, files) => {
            if (err) {
              console.error(err);
              return res.status(500).json({ error: 'File upload failed' });
            }
            // Process files here, e.g., move to final destination, upload to S3
            const file = files.myFile; // 'myFile' is the name attribute in your form input
            if (file) {
              const newPath = path.join('./processed_uploads', path.basename(file.filepath));
              fs.rename(file.filepath, newPath, (renameErr) => {
                if (renameErr) {
                  console.error(renameErr);
                  return res.status(500).json({ error: 'Failed to move file' });
                }
                res.status(200).json({ message: 'File uploaded successfully', filePath: newPath });
              });
            } else {
              res.status(400).json({ error: 'No file uploaded' });
            }
          });
        } else {
          res.setHeader('Allow', ['POST']);
          res.status(405).end(`Method ${req.method} Not Allowed`);
        }
      };
      
    • Why it works: By disabling Next.js’s default body parser (bodyParser: false) and using a streaming parser like formidable, the entire file content is never held in memory at once. It’s processed in chunks, significantly reducing memory overhead and allowing for larger files.
  3. JSON Payload Exceeding Limit: While sizeLimit in next.config.js handles this, it’s worth noting that large JSON payloads are a primary reason for this error.

    • Diagnosis: If you’re sending a single large JSON object (e.g., an array of thousands of items, or deeply nested objects) and sizeLimit is already set reasonably high, this could be the cause.
    • Fix: Ensure sizeLimit in next.config.js is sufficient for your JSON data. If the data is truly massive, consider alternative approaches like paginated requests or sending data in smaller chunks.
      // next.config.js
      module.exports = {
        api: {
          bodyParser: {
            sizeLimit: '10mb', // Adjust as needed
          },
        },
      };
      
    • Why it works: This directly increases the threshold at which the server-side JSON parser will refuse to process the request body.
  4. Third-Party Middleware Interference: If you’re using custom server logic or middleware that also attempts to parse the request body, it might do so before Next.js or with its own stricter limits.

    • Diagnosis: Review any custom server setup (server.js) or middleware you’ve applied. Look for app.use(express.json()) or similar body-parsing middleware that might be configured with a lower limit.
    • Fix: Ensure any custom body-parsing middleware is configured with a limit that accommodates your needs, or disable it if Next.js’s built-in parser (configured via next.config.js) is sufficient.
      // Example in a custom server (server.js)
      // If using Express middleware, configure its limit:
      server.use(express.json({ limit: '10mb' }));
      server.use(express.urlencoded({ limit: '10mb', extended: true }));
      
    • Why it works: This ensures that any middleware intercepting the request also allows for the expected body size, preventing it from rejecting the request before Next.js even gets to it.
  5. Vercel/Platform Limits: If you’re deploying on Vercel or another platform, they might have their own request body size limits that are independent of your Next.js configuration.

    • Diagnosis: Check the deployment platform’s documentation for request body size limits. Vercel, for instance, has a default limit of 5MB for Serverless Functions, which can be increased to 50MB by upgrading your plan.
    • Fix: If you’re on Vercel, increase the sizeLimit in next.config.js to be within Vercel’s allowed limits (e.g., up to 50MB on a Pro plan). For larger payloads, consider using a service like AWS S3 for direct uploads, bypassing the function’s request body entirely.
      // next.config.js (for Vercel deployment)
      module.exports = {
        api: {
          bodyParser: {
            sizeLimit: '45mb', // Example for Vercel Pro plan, up to 50MB
          },
        },
      };
      
    • Why it works: This aligns your application’s configuration with the infrastructure’s constraints, allowing larger requests to pass through the platform’s network edge and reach your Next.js API route.
  6. Incorrect bodyParser Configuration: Sometimes, the bodyParser option in next.config.js can be misconfigured, leading to unexpected behavior.

    • Diagnosis: Double-check the syntax and expected values for sizeLimit. It expects a string with a unit (e.g., '1mb', '50kb'). Using just a number or incorrect units will cause it to fail.
    • Fix: Ensure sizeLimit is a string with valid units.
      // next.config.js
      module.exports = {
        api: {
          bodyParser: {
            sizeLimit: '8mb', // Correct format
            // sizeLimit: 8000000, // Incorrect format, will not work
          },
        },
      };
      
    • Why it works: Correctly formatted configuration ensures that Next.js’s build process and runtime correctly interpret the desired body size limit.

After fixing these, the next error you might encounter is a 504 Gateway Timeout if your API route takes too long to process the now-accepted larger request body, especially on platforms with execution time limits for serverless functions.

Want structured learning?

Take the full Nextjs course →