Back to Guides

Request Size Limits & Timeouts

Unbounded request sizes and long-running operations can exhaust server resources. Configure proper limits to maintain stability.

Body Size Limits

Next.js allows configuring body size limits per route:

// app/api/upload/route.ts
export const config = {
  api: {
    bodyParser: {
      sizeLimit: "4mb",
    },
  },
};

// For App Router, use route segment config
export const maxDuration = 60; // seconds
export const dynamic = "force-dynamic";

Validating Upload Size

export async function POST(request: Request) {
  const contentLength = request.headers.get("content-length");
  const MAX_SIZE = 4 * 1024 * 1024; // 4MB

  if (contentLength && parseInt(contentLength) > MAX_SIZE) {
    return Response.json(
      { error: "File too large" },
      { status: 413 }
    );
  }

  // Process upload...
}

Timeout Configuration

Configure function timeouts based on expected operation duration:

// For Vercel deployments
export const maxDuration = 30; // 30 seconds max

// For long-running tasks, use background jobs
// instead of blocking API routes

Best Practices

  • Set reasonable size limits for all upload endpoints
  • Use streaming for large file uploads
  • Implement client-side size validation as first line of defense
  • Configure appropriate timeouts for each endpoint type
  • Use background jobs for operations over 30 seconds
Pro Portal - VibeCheck | VibeCheck