How HTTP Works
4xx · Client error
< HTTP/1.1 431 Request Header Fields Too Large

431 Request Header Fields Too Large

The server refuses to process the request because header fields are too large. Learn how to handle and prevent 431 errors in your applications.

Reviewed 8 min readintermediate2 sourcesTry itMarkdown
Cacheable
Only with explicit freshness
Retry?
No: shrink headers or cookies
Usually sent by
Web server or reverse proxy
Spec
RFC 6585 §5
Often confused with
413, 400
On this page

TL;DR: Request headers exceed server size limits (usually due to large cookies). Clear browser cookies or reduce custom headers to fix.

What is 431 Request Header Fields Too Large?

A 431 Request Header Fields Too Large status code means the server is refusing to process your request because the HTTP headers are too large. Think of it like trying to stuff a package with an address label that’s bigger than the package itself—the postal service would reject it because the overhead is unreasonable.

This error typically occurs when cookies, authentication tokens, or custom headers accumulate to exceed the server’s configured limits.

When Does This Happen?

You’ll see a 431 Request Header Fields Too Large response in these common situations:

1. Excessive Cookies

User has accumulated many cookies over time
→ Cookie header becomes massive (>8KB)
→ Server rejects request with 431

2. Large Authentication Tokens

JWT token with many claims
→ Authorization header exceeds limit
→ Request rejected

3. Too Many Custom Headers

Application adds many tracking headers
→ Total header size exceeds server limit
→ 431 response returned

4. Referrer URL Too Long

Coming from page with very long URL
→ Referer header extremely large
→ Server refuses request

5. Accumulated Session Data

Session cookies grow over time
→ Multiple large cookies sent together
→ Total size exceeds limit

Example Responses

Basic 431 Response:

HTTP/1.1 431 Request Header Fields Too Large
Content-Type: text/html
Content-Length: 247

<!DOCTYPE html>
<html>
<head><title>Request Header Too Large</title></head>
<body>
  <h1>431 Request Header Fields Too Large</h1>
  <p>The request headers exceed the server's size limit.</p>
  <p>Please clear your cookies and try again.</p>
</body>
</html>

Detailed JSON Response:

HTTP/1.1 431 Request Header Fields Too Large
Content-Type: application/json
Content-Length: 312

{
  "error": "Request Header Fields Too Large",
  "message": "The total size of request headers exceeds the server limit",
  "details": {
    "max_header_size": "8192 bytes",
    "actual_size": "12456 bytes",
    "primary_culprit": "Cookie header (9234 bytes)"
  },
  "suggestions": [
    "Clear browser cookies",
    "Remove unnecessary custom headers",
    "Contact support if issue persists"
  ]
}

With Specific Guidance:

HTTP/1.1 431 Request Header Fields Too Large
Content-Type: application/json
Retry-After: 300

{
  "error": "Request Header Fields Too Large",
  "message": "Your request headers are too large to process",
  "limit": {
    "max_total_headers": "8KB",
    "max_single_header": "4KB",
    "current_total_size": "10.2KB"
  },
  "likely_causes": [
    "Excessive cookies accumulated over time",
    "Large authentication token",
    "Too many tracking headers"
  ],
  "solutions": [
    {
      "action": "Clear cookies",
      "instructions": "Delete cookies for this domain in browser settings"
    },
    {
      "action": "Use shorter tokens",
      "instructions": "Request a new authentication token with fewer claims"
    },
    {
      "action": "Reduce custom headers",
      "instructions": "Remove unnecessary X-* headers from request"
    }
  ]
}

Real-World Example

Imagine a user who has been browsing an e-commerce site for months and accumulated many cookies:

Request with Oversized Headers:

GET /checkout HTTP/1.1
Host: shop.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)...
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Cookie: session_id=abc123; tracking_id=xyz789; preference_theme=dark; preference_language=en; preference_currency=USD; cart_item_1=product_123; cart_item_2=product_456; cart_item_3=product_789; recently_viewed_1=prod_111; recently_viewed_2=prod_222; recently_viewed_3=prod_333; recently_viewed_4=prod_444; recently_viewed_5=prod_555; analytics_session=long_token_here; ab_test_variant_homepage=B; ab_test_variant_checkout=A; ab_test_variant_product=C; consent_cookie=very_long_base64_encoded_consent_data_here; [... many more cookies totaling 10KB ...]
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJyb2xlcyI6WyJ1c2VyIiwiYWRtaW4iLCJtb2RlcmF0b3IiXSwicGVybWlzc2lvbnMiOlsicmVhZCIsIndyaXRlIiwiZGVsZXRlIl19.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
X-Custom-Tracking: [large tracking data]
X-Analytics-Session: [large analytics data]
Referer: https://shop.example.com/products/category/subcategory/item?utm_source=email&utm_medium=newsletter&utm_campaign=spring_sale_2026&session_id=abc123&tracking_id=xyz789

431 Error Response:

HTTP/1.1 431 Request Header Fields Too Large
Content-Type: application/json
Cache-Control: no-cache
Content-Length: 567

{
  "error": "Request Header Fields Too Large",
  "message": "Your request headers exceed our 8KB limit",
  "analysis": {
    "total_header_size": "10.2 KB",
    "limit": "8 KB",
    "breakdown": {
      "Cookie": "8.1 KB",
      "Authorization": "1.2 KB",
      "Referer": "0.4 KB",
      "Other": "0.5 KB"
    }
  },
  "recommendation": "Clear old cookies to resolve this issue",
  "instructions": {
    "chrome": "Settings > Privacy > Clear browsing data > Cookies",
    "firefox": "Preferences > Privacy > Clear Data > Cookies",
    "safari": "Preferences > Privacy > Manage Website Data > Remove All"
  },
  "support_url": "https://shop.example.com/help/cookie-issues"
}
CodeMeaningWhat’s Too LargeSolution
431Header fields too largeRequest headersClear cookies, reduce headers
413Payload Too LargeRequest bodyReduce body size, compress
414URI Too LongRequest URLShorten URL, use POST
507Insufficient StorageServer storageServer-side issue

Important Characteristics

Common Limits:

nginx:       each header line must fit one 8 KB buffer (large_client_header_buffers 4 8k); answers 400, not 431
Apache:      8,190 bytes per header field (LimitRequestFieldSize); answers 400
Node.js:     16 KiB for all headers together (--max-http-header-size); answers 431
AWS ALB:     16 KB per header, 64 KB total, not adjustable; answers 400
Cloudflare:  128 KB of request headers in total

Note that only some servers use 431 at all; nginx and Apache send 400. The Request Header Or Cookie Too Large guide shows how to find which layer refused and which cookie grew.

Affects Entire Request:

HTTP/1.1 431 Request Header Fields Too Large
↑
Request is rejected before processing
No partial processing occurs

Can Be Individual or Total:

  • Some servers limit individual header size
  • Some limit total header size
  • Some limit both
  • Some limit number of headers

Common Mistakes

❌ Not providing cookie clearing instructions

HTTP/1.1 431 Request Header Fields Too Large

Request Header Too Large  ← Unhelpful for users

❌ Accumulating unnecessary cookies

// Bad: Adding cookies indefinitely
app.use((req, res, next) => {
  res.cookie(`viewed_${Date.now()}`, productId)
  next()
})

❌ Sending excessive custom headers

// Bad: Too many tracking headers
fetch('/api/data', {
  headers: {
    'X-Tracking-1': data1,
    'X-Tracking-2': data2,
    'X-Tracking-3': data3
    // ... 20 more headers
  }
})

✅ Correct approach

// Good: Clean up old cookies
app.use((req, res, next) => {
  // Limit recently viewed items
  const maxItems = 5
  const viewed = req.cookies.recently_viewed || []

  if (viewed.length > maxItems) {
    res.cookie('recently_viewed', viewed.slice(0, maxItems))
  }

  next()
})

Getting 431 Request Header Fields Too Large right

Implement Cookie Rotation:

// Clean up old cookies automatically
app.use((req, res, next) => {
  const cookieSize = JSON.stringify(req.cookies).length

  if (cookieSize > 4096) {
    // 4KB warning threshold
    // Clear old tracking cookies
    const trackingCookies = Object.keys(req.cookies).filter((key) => key.startsWith('tracking_'))

    trackingCookies.forEach((cookie) => {
      res.clearCookie(cookie)
    })
  }

  next()
})

Use Short-Lived Session Storage:

// Store large data server-side, not in cookies
app.post('/api/large-data', (req, res) => {
  const dataId = generateId();

  // Store in Redis/database
  await redis.set(`data:${dataId}`, JSON.stringify(largeData), 'EX', 3600);

  // Send small reference in cookie
  res.cookie('data_ref', dataId, { maxAge: 3600000 });
  res.json({ success: true });
});

Monitor Header Sizes:

app.use((req, res, next) => {
  const headerSize = JSON.stringify(req.headers).length

  if (headerSize > 6144) {
    // 6KB warning
    console.warn(`Large headers detected: ${headerSize} bytes`)
    metrics.increment('large_headers')
  }

  if (headerSize > 8192) {
    // 8KB limit
    return res.status(431).json({
      error: 'Request Header Fields Too Large',
      size: headerSize,
      limit: 8192,
      suggestion: 'Clear cookies and try again'
    })
  }

  next()
})

Provide Clear User Guidance:

function handle431Error(req, res) {
  const headerSize = calculateHeaderSize(req)

  res.status(431).json({
    error: 'Request Header Fields Too Large',
    details: {
      current_size: `${headerSize} bytes`,
      limit: '8192 bytes',
      largest_headers: getLargestHeaders(req)
    },
    user_actions: [
      {
        step: 1,
        action: 'Clear browser cookies',
        why: 'Old cookies are accumulating',
        how: getCookieClearInstructions(req.headers['user-agent'])
      },
      {
        step: 2,
        action: 'Refresh the page',
        why: 'Retry with cleared cookies'
      }
    ],
    support: 'https://example.com/help/431-error'
  })
}

Implementation Examples

Express.js Middleware:

const MAX_HEADER_SIZE = 8 * 1024 // 8KB

app.use((req, res, next) => {
  const headerSize = Buffer.byteLength(JSON.stringify(req.headers))

  if (headerSize > MAX_HEADER_SIZE) {
    return res.status(431).json({
      error: 'Request Header Fields Too Large',
      message: `Headers size ${headerSize} exceeds limit ${MAX_HEADER_SIZE}`,
      solution: 'Clear cookies or reduce custom headers'
    })
  }

  next()
})

Nginx Configuration:

http {
    # Increase header buffer size if needed
    large_client_header_buffers 4 16k;

    # Or return 431 for oversized headers
    client_header_buffer_size 8k;
}

Apache Configuration:

# Set maximum header size
LimitRequestFieldSize 8190

# Set maximum number of headers
LimitRequestFields 100

Node.js HTTP Server:

const http = require('http')

const server = http.createServer(
  {
    maxHeaderSize: 8192 // 8KB limit
  },
  (req, res) => {
    // Handle request
  }
)

server.on('clientError', (err, socket) => {
  if (err.code === 'HPE_HEADER_OVERFLOW') {
    socket.write('HTTP/1.1 431 Request Header Fields Too Large\r\n')
    socket.write('Content-Type: application/json\r\n\r\n')
    socket.write(
      JSON.stringify({
        error: 'Request Header Fields Too Large',
        message: 'Headers exceed 8KB limit',
        solution: 'Clear cookies and retry'
      })
    )
    socket.end()
  }
})

Client-Side Prevention

Monitor Cookie Size:

function setCookieSafely(name, value, options) {
  // Check total cookie size
  const currentCookieSize = document.cookie.length
  const newCookieSize = `${name}=${value}`.length

  if (currentCookieSize + newCookieSize > 4096) {
    console.warn('Cookie size approaching limit, clearing old cookies')

    // Clear old tracking cookies
    document.cookie.split(';').forEach((cookie) => {
      const name = cookie.split('=')[0].trim()
      if (name.startsWith('old_') || name.startsWith('temp_')) {
        document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT`
      }
    })
  }

  // Set the new cookie
  document.cookie = `${name}=${value}; ${options || ''}`
}

Handle 431 Gracefully:

async function apiCall(url, options = {}) {
  try {
    const response = await fetch(url, options)

    if (response.status === 431) {
      // Clear cookies and retry
      console.warn('Headers too large, clearing cookies...')

      // Clear all cookies
      document.cookie.split(';').forEach((cookie) => {
        const name = cookie.split('=')[0].trim()
        document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`
      })

      // Retry request
      return fetch(url, options)
    }

    return response
  } catch (error) {
    console.error('API call failed:', error)
    throw error
  }
}

Try It Yourself

Visit our request builder and see 431 in action:

  1. Set method to GET
  2. Set path to /api/test
  3. Add many custom headers or large cookie values
  4. Click Send request
  5. Observe 431 response when headers exceed limit

Try it with curl

Send a very large Cookie header. Node’s HTTP server rejects oversized headers with 431; nginx usually answers 400 with its own “Request Header Or Cookie Too Large” page instead, so the status you get depends on the server.

curl -i https://api.example.com/ \
  -H "Cookie: session=$(head -c 20000 /dev/zero | tr '\0' 'a')"

Example output (illustrative, not captured from a real server):

HTTP/1.1 431 Request Header Fields Too Large
Connection: close

Shrink the head -c count until the request passes to find the limit. A real browser hits this when cookies pile up on a domain.

Frequently asked questions

What does 431 Request Header Fields Too Large mean?

A 431 error means the request headers exceed the server limit. This often happens when cookies grow too large or too many custom headers are sent.

How do I fix a 431 error?

Clear your browser cookies for the site, reduce the number of custom headers, or ask the server administrator to increase header size limits.

What causes headers to become too large?

Common causes include accumulated cookies, large JWT tokens in Authorization headers, excessive custom headers, or tracking cookies from third-party scripts.

What is the header size limit?

Limits vary by server. Node.js allows 16 KiB for all headers together; nginx needs each header line to fit an 8 KB buffer; Apache allows 8,190 bytes per field; Cloudflare allows 128 KB in total. nginx and Apache answer 400 rather than 431. Most self-hosted servers let you raise these limits.

Sources

  1. MDN Web Docs: 431 Request Header Fields Too Largedeveloper.mozilla.org
  2. RFC 6585: 431 Request Header Fields Too Largerfc-editor.org

Keep going

Browse /search