HTTP

411 - Length Required

Getting a 411 Length Required means the server needs a Content-Length header but your request doesn't include one—the server can't determine request body size upfront and refuses to accept chunked encoding or streams without explicit length. This client-side error (4xx) happens when servers require knowing payload size before processing. Most common in upload endpoints that validate size limits, but also appears when servers don't support Transfer-Encoding: chunked or need Content-Length for security/validation checks.

#Common Causes

  • Frontend: Fetch/axios automatically sets Content-Length for string bodies, but manual requests might omit it. FormData uploads sometimes don't include Content-Length (browser handles chunked). Streaming request bodies can't provide Content-Length upfront. Client libraries strip Content-Length when using chunked encoding.
  • Backend: Server validation middleware requires Content-Length for size checking. Upload endpoint enforces size limits and needs length before accepting body. Security policy requires explicit Content-Length to prevent slowloris attacks. Legacy server implementation doesn't support chunked transfer encoding.
  • Infrastructure: Nginx proxy requires Content-Length for certain request types. Load balancer enforces Content-Length presence for uploads. WAF rules block requests without Content-Length header. API gateway validation fails without explicit length.

Solutions

  1. 1Step 1: Diagnose - Check DevTools Network tab Request Headers—verify if Content-Length is present. Look for Transfer-Encoding: chunked header (incompatible with Content-Length requirement). Check if body is being streamed (can't know length upfront).
  2. 2Step 2: Diagnose - Server logs indicate which endpoint requires Content-Length. Review API documentation for endpoint requirements. Check server configuration for chunked encoding support. Verify if size validation logic needs Content-Length.
  3. 3Step 3: Fix - Client-side: Calculate Content-Length before sending (new TextEncoder().encode(body).length for strings, file.size for files). Ensure fetch/axios includes Content-Length (usually automatic). For streams, buffer first or use endpoint that supports chunked encoding.
  4. 4Step 4: Fix - Server-side: Accept Transfer-Encoding: chunked as alternative to Content-Length. Remove Content-Length requirement if not security-critical. Use streaming body parsers that handle chunked encoding. Update validation to work with chunked transfers.
  5. 5Step 5: Fix - Infrastructure: Configure Nginx to accept chunked encoding (chunked_transfer_encoding on). Update load balancer to pass Transfer-Encoding headers. Review WAF rules for Content-Length requirements. Configure API gateway to support both Content-Length and chunked encoding.

</>Code Examples

Fetch API: Add Content-Length Header
1// Client-side: Calculate and add Content-Length header
2async function sendDataWithLength(data) {
3  // For JSON payloads
4  const jsonString = JSON.stringify(data);
5  const contentLength = new TextEncoder().encode(jsonString).length;
6  
7  const response = await fetch('/api/users', {
8  method: 'POST',
9  headers: {
10    'Content-Type': 'application/json',
11      'Content-Length': contentLength.toString(), // Explicit length
12    },
13    body: jsonString,
14  });
15  
16  if (response.status === 411) {
17    throw new Error('Server requires Content-Length header');
18  }
19  
20  return response.json();
21}
22
23// For file uploads
24async function uploadFileWithLength(file) {
25  // File size is known, use it
26  const response = await fetch('/api/upload', {
27    method: 'POST',
28    headers: {
29      'Content-Length': file.size.toString(),
30      'Content-Type': file.type,
31      'X-Filename': file.name,
32    },
33    body: file, // File object works, browser sets Content-Length
34  });
35  
36  if (!response.ok) {
37    throw new Error(`Upload failed: ${response.status}`);
38  }
39  
40  return response.json();
41}
42
43// For FormData, Content-Length is usually automatic, but can be explicit
44async function uploadFormDataWithLength(formData) {
45  // Calculate total size (approximate for FormData)
46  let totalSize = 0;
47  for (const [key, value] of formData.entries()) {
48    if (value instanceof File) {
49      totalSize += value.size;
50    } else {
51      totalSize += new TextEncoder().encode(value).length;
52    }
53  }
54  
55  const response = await fetch('/api/upload', {
56  method: 'POST',
57  headers: {
58      'Content-Length': totalSize.toString(),
59      // Don't set Content-Type, browser sets it with boundary
60    },
61    body: formData,
62  });
63  
64  return response.json();
65}
Express.js: Handle Content-Length Requirement
1// Server-side: Accept requests with or without Content-Length
2const express = require('express');
3const app = express();
4
5// Middleware to check Content-Length for specific endpoints
6const requireContentLength = (req, res, next) => {
7  const contentLength = req.headers['content-length'];
8  const transferEncoding = req.headers['transfer-encoding'];
9  
10  // Accept either Content-Length or chunked encoding
11  if (!contentLength && transferEncoding !== 'chunked') {
12    return res.status(411).json({
13      error: 'Length Required',
14      message: 'Content-Length header or Transfer-Encoding: chunked is required',
15    });
16  }
17  
18  // Validate Content-Length if provided
19  if (contentLength) {
20    const length = parseInt(contentLength, 10);
21    if (isNaN(length) || length < 0) {
22      return res.status(400).json({
23        error: 'Bad Request',
24        message: 'Invalid Content-Length header value',
25      });
26    }
27    
28    // Check size limit
29    const maxSize = 10 * 1024 * 1024; // 10MB
30    if (length > maxSize) {
31      return res.status(413).json({
32        error: 'Payload Too Large',
33        message: `Content-Length (${length}) exceeds maximum size (${maxSize})`,
34      });
35    }
36  }
37  
38  next();
39};
40
41// Apply to upload endpoint
42app.post('/api/upload', requireContentLength, (req, res) => {
43  // Process upload
44  res.json({ success: true, size: req.headers['content-length'] });
45});
46
47// Alternative: Accept chunked encoding (no Content-Length required)
48app.use(express.raw({ 
49  type: 'application/octet-stream',
50  limit: '10mb',
51  // This accepts chunked encoding
52}));
Nginx: Handle Content-Length and Chunked Encoding
1# Nginx: Configure to accept both Content-Length and chunked encoding
2server {
3    listen 80;
4    server_name api.example.com;
5    
6    location /api/upload {
7        # Accept chunked transfer encoding
8        chunked_transfer_encoding on;
9        
10        # Validate Content-Length if provided
11        client_max_body_size 10m;
12        client_body_buffer_size 1m;
13        
14        proxy_pass http://backend;
15        proxy_set_header Host $host;
16        proxy_set_header X-Real-IP $remote_addr;
17        
18        # Pass Content-Length header if present
19        proxy_set_header Content-Length $http_content_length;
20        proxy_set_header Transfer-Encoding $http_transfer_encoding;
21        
22        # Don't buffer request body for large uploads
23        proxy_request_buffering off;
24        proxy_http_version 1.1;
25    }
26    
27    # For endpoints that require Content-Length
28    location /api/strict-upload {
29        # Only accept requests with Content-Length
30        if ($http_content_length = "") {
31            return 411 "Length Required";
32        }
33        
34        proxy_pass http://backend;
35        proxy_set_header Host $host;
36        proxy_set_header Content-Length $http_content_length;
37    }
38}

Related Errors

Provider Information

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

411 - Length Required | HTTP Error Reference | Error Code Reference