HTTP

413 - Payload Too Large

Getting a 413 Payload Too Large means your request body exceeds the server's size limits—file upload too big, JSON payload exceeds max size, or multiple large files in one request hit the configured ceiling. This client-side error (4xx) happens when servers enforce request body size limits to prevent resource exhaustion. Most common during file uploads that exceed limits, but also appears when API clients send large JSON payloads, batch operations include too many items, or uncompressed data could be compressed.

#Common Causes

  • Frontend: Single file upload exceeds server limit (e.g., 10MB limit, 50MB file). Large JSON payloads sent without compression. Multiple files in FormData exceed combined limit. Client doesn't validate file size before upload. Uncompressed image/data that could be optimized.
  • Backend: express.json() limit set too low (default 100kb, needs increase). Body parser middleware rejects before reaching handler. Database BLOB size limits prevent large inserts. Server memory constraints limit acceptable payload size. Application code enforces business logic size limits.
  • Infrastructure: Nginx client_max_body_size too restrictive (default 1MB). Load balancer enforces payload size limits. WAF blocks large request bodies. API gateway has stricter limits than backend. Reverse proxy buffers exceed size before forwarding.

Solutions

  1. 1Step 1: Diagnose - Check DevTools Network tab—verify request body size in Request Payload section. Look for Content-Length header value. Check if file size exceeds visible limits. Review if payload could be compressed.
  2. 2Step 2: Diagnose - Server logs show exact size limit and current request size. Check Nginx error logs for "client intended to send too large body" messages. Review application logs for body parser rejections. Verify configured limits at each layer.
  3. 3Step 3: Fix - Client-side: Validate file size before upload (file.size check). Compress large JSON payloads (JSON.stringify + compression). Split large uploads into chunks (5MB chunks, reassemble server-side). Use streaming uploads for large files.
  4. 4Step 4: Fix - Server-side: Increase body parser limits (express.json({ limit: '50mb' })). Implement chunked upload endpoints for large files. Add compression middleware to accept compressed requests. Validate size early with helpful error messages.
  5. 5Step 5: Fix - Infrastructure: Increase Nginx client_max_body_size (e.g., client_max_body_size 100m;). Update load balancer payload limits. Review WAF rules for file size restrictions. Configure API gateway limits to match backend. Enable request buffering for large uploads.

</>Code Examples

Fetch API: Validate and Chunk Large Uploads
1// Client-side: Validate size and chunk large files
2const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
3const CHUNK_SIZE = 5 * 1024 * 1024; // 5MB chunks
4
5async function uploadFile(file) {
6  // Validate file size before upload
7  if (file.size > MAX_FILE_SIZE) {
8    throw new Error(`File size (${file.size} bytes) exceeds maximum (${MAX_FILE_SIZE} bytes)`);
9  }
10  
11  // For files larger than chunk size, use chunked upload
12  if (file.size > CHUNK_SIZE) {
13    return uploadLargeFile(file);
14  }
15  
16  // Small file, upload directly
17  const formData = new FormData();
18  formData.append('file', file);
19  
20  const response = await fetch('/api/upload', {
21    method: 'POST',
22    body: formData,
23  });
24  
25  if (response.status === 413) {
26    const error = await response.json();
27    throw new Error(`Upload failed: ${error.message || 'File too large'}`);
28  }
29  
30  return response.json();
31}
32
33// Chunked upload for large files
34async function uploadLargeFile(file) {
35  const chunks = Math.ceil(file.size / CHUNK_SIZE);
36  const uploadId = crypto.randomUUID();
37  
38  for (let i = 0; i < chunks; i++) {
39    const start = i * CHUNK_SIZE;
40    const end = Math.min(start + CHUNK_SIZE, file.size);
41    const chunk = file.slice(start, end);
42    
43    const formData = new FormData();
44    formData.append('chunk', chunk);
45    formData.append('uploadId', uploadId);
46    formData.append('chunkIndex', i.toString());
47    formData.append('totalChunks', chunks.toString());
48    formData.append('fileName', file.name);
49    
50    const response = await fetch('/api/upload-chunk', {
51      method: 'POST',
52      body: formData,
53    });
54    
55    if (!response.ok) {
56      throw new Error(`Chunk upload failed: ${response.status}`);
57    }
58  }
59  
60  // Finalize upload
61  const finalizeResponse = await fetch(`/api/upload-finalize/${uploadId}`, {
62    method: 'POST',
63  });
64  
65  return finalizeResponse.json();
66}
Express.js: Configure Body Size Limits
1// Server-side: Configure body size limits and handle 413
2const express = require('express');
3const multer = require('multer');
4const app = express();
5
6// Increase JSON body size limit
7app.use(express.json({ 
8  limit: '50mb', // Increase from default 100kb
9  extended: true,
10}));
11
12app.use(express.urlencoded({ 
13  limit: '50mb',
14  extended: true,
15}));
16
17// Configure multer for file uploads with size limits
18const upload = multer({
19  storage: multer.diskStorage({
20    destination: (req, file, cb) => {
21      cb(null, './uploads/');
22    },
23    filename: (req, file, cb) => {
24      cb(null, `${Date.now()}-${file.originalname}`);
25    },
26  }),
27  limits: {
28    fileSize: 10 * 1024 * 1024, // 10MB per file
29    files: 5, // Maximum 5 files
30  },
31});
32
33// Single file upload
34app.post('/api/upload', upload.single('file'), (req, res) => {
35  if (!req.file) {
36    return res.status(400).json({ error: 'No file uploaded' });
37  }
38  
39  res.json({
40    success: true,
41    filename: req.file.filename,
42    size: req.file.size,
43  });
44});
45
46// Handle 413 errors from body parser
47app.use((error, req, res, next) => {
48  if (error.type === 'entity.too.large') {
49    return res.status(413).json({
50      error: 'Payload Too Large',
51      message: `Request body size exceeds limit. Maximum size: ${error.limit}`,
52      limit: error.limit,
53    });
54  }
55  next(error);
56});
57
58// Chunked upload endpoint
59app.post('/api/upload-chunk', upload.single('chunk'), async (req, res) => {
60  const { uploadId, chunkIndex, totalChunks, fileName } = req.body;
61  
62  // Store chunk (implementation depends on storage solution)
63  await storeChunk(uploadId, parseInt(chunkIndex), req.file.buffer);
64  
65  res.json({ success: true, chunkIndex: parseInt(chunkIndex) });
66});
67
68app.post('/api/upload-finalize/:uploadId', async (req, res) => {
69  const { uploadId } = req.params;
70  
71  // Reassemble chunks into final file
72  const file = await reassembleChunks(uploadId);
73  
74  res.json({ success: true, file });
75});
Nginx: Increase Request Body Size Limits
1# Nginx: Configure client body size limits
2server {
3    listen 80;
4    server_name api.example.com;
5    
6    # Increase maximum request body size (default is 1MB)
7    client_max_body_size 100m;
8    
9    # Increase buffer sizes for large request bodies
10    client_body_buffer_size 1m;
11    client_header_buffer_size 4k;
12    large_client_header_buffers 4 16k;
13    
14    location /api/upload {
15        # Allow even larger uploads for this endpoint
16        client_max_body_size 500m;
17        
18        proxy_pass http://backend;
19        proxy_set_header Host $host;
20        proxy_set_header X-Real-IP $remote_addr;
21        
22        # Timeouts for large uploads
23        proxy_read_timeout 300s;
24        proxy_connect_timeout 60s;
25        
26        # Don't buffer request body (stream directly to backend)
27        proxy_request_buffering off;
28        proxy_http_version 1.1;
29    }
30    
31    location /api/ {
32        # Standard size limit for other endpoints
33        client_max_body_size 10m;
34        
35        proxy_pass http://backend;
36        proxy_set_header Host $host;
37        proxy_set_header X-Real-IP $remote_addr;
38    }
39}

Related Errors

Provider Information

This error code is specific to HTTP services. For more information, refer to the official HTTP documentation.

413 - Payload Too Large | HTTP Error Reference | Error Code Reference