HTTP

Status Code

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.

7 min read intermediate Try in Playground

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>
```text

**Detailed JSON Response:**

```http
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"
    }
  ]
}
```http

## Real-World Example

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

**Request with Oversized Headers:**

```http
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"
}
```text

## 431 vs Other Size-Related Codes

| Code    | Meaning                 | What's Too Large | Solution                      |
| ------- | ----------------------- | ---------------- | ----------------------------- |
| **431** | Header fields too large | Request headers  | Clear cookies, reduce headers |
| **413** | Payload Too Large       | Request body     | Reduce body size, compress    |
| **414** | URI Too Long            | Request URL      | Shorten URL, use POST         |
| **507** | Insufficient Storage    | Server storage   | Server-side issue             |

## Important Characteristics

**Common Limits:**

```text
Nginx default: 8KB total headers
Apache default: 8KB per header line
Node.js default: 16KB total headers
Cloudflare: 32KB total headers
```text

**Affects Entire Request:**

```http
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
```text

**❌ Accumulating unnecessary cookies**

```javascript
// 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
  }
})
```javascript

**✅ Correct approach**

```javascript
// 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()
})

Best Practices

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()
})
```javascript

**Use Short-Lived Session Storage:**

```javascript
// 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()
})
```javascript

**Provide Clear User Guidance:**

```javascript
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()
})
```text

**Nginx Configuration:**

```nginx
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
```javascript

**Node.js HTTP Server:**

```javascript
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 || ''}`
}
```javascript

**Handle 431 Gracefully:**

```javascript
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

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. Apache defaults to 8KB, Nginx to 8KB total headers, Node.js to 16KB. Most servers allow configuration of these limits.

Keep Learning