In this blog post we will see how to use and manipulate headers in the javascript Fetch Api, including setting headers, reading, with some examples.
The javascript Fetch Api allows us to make Ajax Http calls to webservices and web api’s. If you work with it before the Fetch Api is a promise based Api which return a promise so you can get the response using then(), catch() syntax or async await which is different from the callback based Api provided in the XMLHttpRequest.Â
The Fetch Api is much easier than the XMLHttpRequest and provide us some methods for sending requests and retrieving responses and setting headers.
Consider this example:
async function getArticles() { try { const response = await fetch('https://jsonplaceholder.org/posts'); const result = await response.json(); console.log(result); } catch(error) { console.error("Error:", error); } }
In this simple example we are fetching dummy data from jsonplaceholder.org Api using the fetch method. I am using async await to capture the response which returned as a promise and then using the response.json() method to get the actual data.
Let’s see how to send and manipulate headers using the Fetch Api.
The fetch method in this example is taking the endpoint url you want to retrieve data from. To send headers along with the fetch, you need to pass another argument which is an options object. The options object allows to customize the behavior of fetch like setting the http method, request body, headers, etc like so:
await fetch(url, { method: "POST", mode: "cors", // no-cors, *cors, same-origin cache: "no-cache", credentials: "same-origin", headers: { "Content-Type": "application/json", }, body: JSON.stringify(data), // body data type must match "Content-Type" header });
The key we are interested in is the headers. The headers can be set as an object like shown above or by creating an object of the Headers interface provided in the Fetch Api.
So let’s update the previous example to send some headers:
const response = await fetch('https://jsonplaceholder.org/posts', { headers: { "Content-Type": "application/json", "Accept": "application/json", "Accept-Language": "ar", "X-Num-Items": "20" } });
In this code i included some headers to be sent in the request like Content-Type, Accept, Accept-Language and a custom header which is “X-Num-Items”. As you might know any headers sent can modify the request or you can retrieve the headers server side and implement a custom logic.
Note that there some forbidden headers that cannot be sent along with the request, such headers that start with “Sec-” or “Proxy-“. You check the full list of forbidden headers in MDN docs.
Creating Headers Using the Headers interface
Like passing the headers as an object, you can create it using the Headers interface. The Headers interface contains several methods to set, append, remove and retrieve headers.
const appHeaders = new Headers()
Some Header methods:
- headers.set(): Set a new value into an existing header object or add the value if it doesn’t exist.
- headers.append(): Append new header inside of header object or add the value if it doesn’t exist. If you are setting an empty header object then use headers.set() and header.append() after that.
- headers.delete(): Delete a header from header object.
- headers.has(): Detect whether header object contains a value using header key.
- headers.get(): Return header value using header key.
- headers.entries(): Returns an iterable containing all key/value pairs contained in this object
So in the above example let’s use the Headers interface:
const appHeaders = new Headers(); appHeaders.set('Content-Type', "application/json"); appHeaders.append('Accept', "application/json"); appHeaders.append('Accept-Language', "ar"); appHeaders.append('X-Num-Items', "20"); const response = await fetch('https://jsonplaceholder.org/posts', { headers: appHeaders });
Now the headers working just like before, and you can use the above methods to manipulate headers object.
Checking for header value:
console.log(appHeaders.has('X-Num-Items')); // true console.log(appHeaders.has('X-Not-Exist')); // false
Retrieving header value
console.log(appHeaders.get('Accept-Language')); // ar console.log(appHeaders.get('Not-Exist')); // null
Retrieving headers entries
console.log(appHeaders.entries()); // output Headers Iterator {}[[Prototype]]: Headers Iterator
Iterating over headers
There are many ways to iterate headers object, the first by using for..of :
for(const p of appHeaders) { console.log(p); } //output (2)Â ['accept', 'application/json'] (2)Â ['accept-language', 'ar'] ...
Also the Headers interface contains a forEach() method which allow to execute a callback for every item:
appHeaders.forEach((val, key) => { console.log(`${key} ==> ${val}`); });
Removing header values:
appHeaders.delete('X-Num-Items'); console.log(appHeaders.has('X-Num-Items')); // false
Response Headers
We saw above how to send headers along with the request. However you can also retrieve the response headers.
The fetch Response object contains a readonly headers property which contains all the headers from the response.
for(const p of response.headers) { console.log(p); }
we can use the same Header methods described above with the response headers like get(), has():
console.log(response.headers.get('content-type'));
You can not use methods like set() or append() as response headers is read-only.