Setting and Managing Request Headers
You'll learn: how to add, read, modify, and remove HTTP headers when making Fetch API requests using the Headers interface.
When making API requests, you often need to send extra information about the request itself—like what data format you accept, authentication tokens, or custom metadata. HTTP headers are the way to communicate this information. The Headers interface gives you a clean, consistent way to manage these headers.
Think of headers like the envelope and stamps on a letter. The letter itself is your request body, but the envelope carries important instructions: where it's going, who sent it, and how it should be handled.
Creating and Setting Headers
You can create a Headers object and add headers in several ways:
// Create an empty Headers object
const headers = new Headers();
// Set a header (replaces if exists)
headers.set('Content-Type', 'application/json');
headers.set('Authorization', 'Bearer abc123');
// Append adds without replacing (useful for multiple values)
headers.append('Accept', 'application/json');
Using Headers in Fetch Requests
const headers = new Headers();
headers.set('Content-Type', 'application/json');
headers.set('X-Custom-Header', 'my-value');
fetch('https://api.example.com/data', {
method: 'POST',
headers: headers,
body: JSON.stringify({ name: 'Alice' })
});
Reading and Deleting Headers
// Get a header value
const contentType = headers.get('Content-Type'); // 'application/json'
// Check if header exists
const hasAuth = headers.has('Authorization'); // true
// Remove a header
headers.delete('X-Custom-Header');
Key Takeaway: The Headers interface provides set(), append(), get(), has(), and delete() methods to manage request headers cleanly and pass them to Fetch API calls for complete control over HTTP communication.