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

Reading and Checking Headers

Using get(), has(), and iterating methods to inspect headers in requests and responses.

Reading and Checking Headers

You'll learn how to inspect header values in both Request and Response objects using get(), has(), and iteration methods.

Why Read Headers?

Once you've created or received a Headers object (from a Request or Response), you often need to inspect what's inside. Maybe you want to check if an API returned a specific Content-Type, verify authentication headers were set, or loop through all headers for debugging.

Core Methods

The Headers interface provides three key ways to read data:

get(name)

Returns the value of a header, or null if it doesn't exist. Case-insensitive.

const response = await fetch('https://api.example.com/data');
const contentType = response.headers.get('Content-Type');
console.log(contentType); // "application/json; charset=utf-8"

has(name)

Returns true if the header exists, false otherwise. Useful for conditional logic.

if (response.headers.has('X-RateLimit-Remaining')) {
  const remaining = response.headers.get('X-RateLimit-Remaining');
  console.log(`API calls left: ${remaining}`);
}

Iteration

Headers are iterable, so you can use for...of, forEach(), or spread them into an array.

// Loop through all headers
for (const [name, value] of response.headers) {
  console.log(`${name}: ${value}`);
}

// Or with forEach
response.headers.forEach((value, name) => {
  console.log(`${name}: ${value}`);
});

Common Pattern: Debugging Headers

Logging all headers helps diagnose issues:

console.log('Response headers:');
response.headers.forEach((value, name) => console.log(`  ${name}: ${value}`));

Key Takeaway: Use get() to retrieve specific header values, has() to check existence, and iteration methods to inspect all headers—essential for debugging and conditional response handling.