Creating and Setting Headers
You'll learn how to build and populate a Headers object programmatically to control HTTP request and response metadata.
What Are Headers Instances?
The Headers object is a special collection that stores HTTP header key-value pairs. Think of it like a specialized dictionary designed specifically for managing header data—it ensures proper formatting and handles case-insensitivity automatically (since HTTP headers like Content-Type and content-type are treated identically).
Creating a Headers Object
You create a new Headers instance using its constructor:
const headers = new Headers();
You can also initialize it with an object literal or another Headers instance:
const headers = new Headers({
'Content-Type': 'application/json',
'Accept': 'application/json'
});
Setting Headers Programmatically
Use the .set() method to add or update headers:
const headers = new Headers();
headers.set('Content-Type', 'text/html');
headers.set('Authorization', 'Bearer abc123');
headers.set('X-Custom-Header', 'myValue');
// Updating overwrites the previous value
headers.set('Content-Type', 'application/json'); // Now it's JSON
The .set() method accepts two string arguments: the header name and its value. If a header already exists, .set() replaces it entirely—it doesn't append.
Why Use Headers Objects?
Using Headers instances gives you structured control over metadata. You can build headers step-by-step, validate them before sending, and reuse the same Headers object across multiple fetch requests.
Key Takeaway: Create Headers instances with new Headers() and use .set(name, value) to programmatically add or update individual header key-value pairs for your HTTP requests.