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

The Headers Object

Understanding the Headers interface for managing HTTP headers in fetch requests and responses.

The Headers Object

You'll learn: How to work with the Headers interface to read, set, and manage HTTP headers in your fetch requests and responses.

What is the Headers Object?

The Headers object is a specialized container for HTTP headers in the Fetch API. Think of it like a dictionary specifically designed for managing key-value pairs of HTTP headers—with built-in logic to handle header names case-insensitively and follow HTTP conventions.

Unlike plain objects, Headers provides methods to safely manipulate headers without worrying about duplicates, case sensitivity, or improper formatting.

Creating and Using Headers

You create a Headers instance using its constructor:

const headers = new Headers();

// Add headers one at a time
headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Bearer token123');

// Or initialize with an object
const headers2 = new Headers({
  'Content-Type': 'text/html',
  'Accept': 'application/json'
});

Key Methods

  • append(name, value) – Adds a header (allows duplicates for certain headers)
  • set(name, value) – Sets a header, replacing any existing value
  • get(name) – Retrieves a header value (returns null if not found)
  • has(name) – Checks if a header exists
  • delete(name) – Removes a header
headers.set('Content-Type', 'application/json');
console.log(headers.get('content-type')); // "application/json" (case-insensitive!)
console.log(headers.has('Authorization')); // true
headers.delete('Authorization');

Why Use Headers Objects?

Headers objects automatically normalize header names (case-insensitive), prevent common mistakes, and integrate seamlessly with Request and Response objects you've already learned about.

Key Takeaway: The Headers object provides a safe, structured way to manage HTTP headers with built-in case-insensitivity and methods that prevent common header-handling errors.