In order to set a default header on your fetch request you have two choices:
1st choice: create a fetch wrapper
The best solution, while it may look like a simple task at forst glance, it can get quite tricky. You might use a library instead, I wrote this one.
2nd choice: create a helper to merge the default headers with the new ones.
Always keep in mind this one thing: your auth header has to be dynamic, you should read it everytime you make a fetch request. In order to stay safe, read it in a function call
const withDefaults = (headers) => {
// for the Auth header make sure to read the value dynamically inside this function
// if you were to read it outside the value would never change
// the following also works with cookies
const authHeader = localStorage.getItem('auth-header')
// transform the headers from the params in an Header instance
// this formats the keys in a consistent way
// eg both 'content-Type' and 'Content-type' are transformed to 'Content-Type'
const headersInstance = new Headers(headers)
// add the Authorization header if the headersInstance do not have it
if(!headersInstance.has('Authorization')){
headersInstance.set('Authorization', authHeader)
}
return headersInstance
}
Usage
fetch('url here', {
headers: withDefaults({ 'content-type': 'application/json' }),
// ...other options
method: 'POST',
body: { hello: 'world'}
})
Make it reusable
Our solution is not really reusable, the default headers are hard coded into our function
To solve that issue we can use a factory function
const createWithDefaults = (getDefaultHeaders) => {
return (headers) => {
const headersInstance = new Headers(headers)
new Headers(getDefaultHeaders()).forEach((val, key) => {
if(!headersInstance.has(key)) {
headersInstance.set(key, val)
}
})
return headersInstance
}
}
Notice that getDefaultHeaders
is a function, this makes sure the default headers stay dynamic: they are evaluated inside if withDefaults
usage
const withDefaults = createWithDefaults(() => ({
Authorization: localStorage.getItem('auth-header'),
// other default headers
}))
// then do the same as before
fetch('url here', {
headers: withDefaults({ 'content-type': 'application/json' }),
// ...other options
method: 'POST',
body: { hello: 'world'}
})
This way we never need to change the internals of the functions. We only need to change the arg passed to createWithDefaults