Setting Request Headers with Fetch
You'll learn how to configure custom HTTP headers in your fetch requests using the Headers object and initialization options.
What Are Custom Headers For?
When making API requests, you often need to send additional information beyond the URL and method—like authentication tokens, content type specifications, or API keys. HTTP headers carry this metadata, and the Fetch API gives you precise control over them.
Two Ways to Set Headers
Using the init Object
The simplest approach is passing a headers property directly in the fetch options:
fetch('https://api.example.com/users', {
method: 'GET',
headers: {
'Authorization': 'Bearer abc123token',
'Accept': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data));
Using the Headers Object
For more complex scenarios, create a Headers instance:
const myHeaders = new Headers();
myHeaders.append('Authorization', 'Bearer abc123token');
myHeaders.append('Accept', 'application/json');
fetch('https://api.example.com/users', {
method: 'GET',
headers: myHeaders
})
.then(response => response.json())
.then(data => console.log(data));
Think of It Like Addressing an Envelope
Setting headers is like filling out the envelope's metadata—recipient, return address, priority stamp—before mailing your letter (the request body). The postal service (HTTP) uses this information to handle your package correctly.
Common Headers You'll Set
- Authorization: Bearer tokens or API keys
- Content-Type: Tells the server what format you're sending (e.g.,
application/json) - Accept: Tells the server what format you want back
Key Takeaway: Custom headers in fetch are set via the headers property in the init options object, either as a plain object or a Headers instance, allowing you to send authentication, content type, and other metadata with your requests.