Setting Request Headers
What you'll learn: How to attach custom headers like Authorization or Content-Type to your fetch requests to control server behavior and authentication.
Why Headers Matter
Think of HTTP headers as the envelope information on a letter—they tell the server important metadata about your request before it even looks at the body. Headers can specify the data format you're sending, provide authentication tokens, or instruct the server how to handle caching.
Adding Headers to Fetch
The fetch() function accepts a second parameter—an options object—where you can specify a headers property. You can pass headers as a plain object:
fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'Authorization': 'Bearer your-token-here',
'Content-Type': 'application/json'
}
});
Common Headers You'll Use
Authorization: Sends credentials or tokens to prove your identity to the server.
Content-Type: Tells the server what format your request body is in (like application/json when sending JSON data).
Accept: Tells the server what response formats you can handle.
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer abc123'
},
body: JSON.stringify({ name: 'Alice' })
});
Why This Matters
Many APIs require authentication headers on every request. Without the proper Content-Type, servers might reject your JSON data. Headers give you fine-grained control over how your requests are interpreted and processed.
Key Takeaway: Request headers are set via the headers property in fetch's options object, allowing you to add authentication, specify content types, and control server behavior on a per-request basis.