Request Headers
You'll learn how to read and set HTTP headers on a Request object using the request.headers property.
What Are Request Headers?
Think of headers as the metadata envelope around your HTTP request — they tell the server important information like what kind of data you're sending, what language you prefer, or who you are (authentication tokens). Every Request object has a headers property that contains a Headers object, letting you read and manipulate these key-value pairs.
Reading Request Headers
When you create a Request, you can access its headers through the headers property:
const request = new Request('https://api.example.com/data', {
headers: {
'Content-Type': 'application/json'
}
});
// Read a specific header
const contentType = request.headers.get('Content-Type');
console.log(contentType); // "application/json"
// Check if a header exists
console.log(request.headers.has('Authorization')); // false
Setting Headers
You can set headers when creating the Request or modify them on an existing Headers object:
const request = new Request('https://api.example.com/data', {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123'
}
});
The Headers object provides methods like get(), has(), set(), append(), and delete() to work with individual headers.
Why This Matters
Headers control how the server interprets your request — wrong headers can cause requests to fail or return unexpected results. The request.headers property gives you programmatic control over this crucial metadata.
Key Takeaway: The request.headers property returns a Headers object that lets you read and set HTTP headers, controlling how your request is processed by the server.