Course contentsShow
← JavaScript
Lesson 2283 of 2,72347. Networking PrimitivesFree lesson

Headers Immutability and Guards

How headers are protected by guards (request, response, none) and immutability patterns.

Headers Immutability and Guards

What you'll learn: How the Headers object protects itself from unwanted modifications using immutability patterns and guard mechanisms.

The Three Guard Types

When you work with Headers in the Fetch API, they aren't all created equal. Each Headers object has an internal "guard" that controls what operations are allowed:

  • none: Fully mutable; you can add, modify, or delete any header. This is the default for headers you create yourself with new Headers().
  • request: Headers attached to a Request object. Certain headers (like Host) are forbidden because the browser controls them for security.
  • response: Headers attached to a Response object. You cannot modify these at all after they're received from a server—they're read-only to preserve the integrity of what the server actually sent.

Why Guards Matter

Think of guards like security levels in a building. The lobby (none) lets anyone modify anything. The office floor (request) restricts dangerous actions. The vault (response) is view-only.

// Guard: none (fully mutable)
const myHeaders = new Headers();
myHeaders.set('X-Custom', 'value'); // ✓ works

// Guard: request (restricted)
const req = new Request('/api', {
  headers: { 'X-Custom': 'value' }
});
// req.headers has 'request' guard
// Trying to set forbidden headers silently fails

// Guard: response (immutable)
const res = await fetch('/api');
// res.headers has 'response' guard
res.headers.set('X-Hack', 'value'); // ✗ throws TypeError

Guards prevent you from accidentally breaking HTTP rules or tampering with server responses after the fact.

Key Takeaway: Headers use guard levels (none, request, response) to enforce immutability and security constraints, preventing unauthorized modifications to request/response metadata.