Set a default header for each fetch () request

Is it possible using the fetch API to set the default headers for each individual request?
What I want to do is set the Authorization header whenever there is a json web token in localStorage . My current solution is to set the headers using this function:

 export default function setHeaders(headers) { if(localStorage.jwt) { return { ...headers, 'Authorization': `Bearer ${localStorage.jwt}` } } else { return headers; } } 

Setting the headers in the fetch request will look like this:

 return fetch('/someurl', { method: 'post', body: JSON.stringify(data), headers: setHeaders({ 'Content-Type': 'application/json' }) }) 

But there must be a better way to do this. I am currently developing a React / Redux / Express application if that helps.

+15
source share
3 answers

You can use Axios instead of fetch, with Interceptors

 const setAuthorization = (token) => { api.interceptors.request.use((config) => { config.headers.Authorization = 'Bearer ' + token; return config; }); } 

Where Api is an axios object with a base URL

 const api= axios.create({ baseURL: 'http://exemple.com' }); 

And when you get your token, you just need to call the setAuthorization function.

Source: Axios README.md

+5
source

Someone is creating a fetch mixin for the default install to receive.

https://github.com/moll/js-fetch-defaults

+5
source

Creating a fetch wrapper may solve your problem:

 function updateOptions(options) { const update = { ...options }; if (localStorage.jwt) { update.headers = { ...update.headers, Authorization: 'Bearer ${localStorage.jwt}', }; } return update; } export default function fetcher(url, options) { return fetch(url, updateOptions(options)); } 

You also get the added benefit of being able to easily switch the request client to all the calls in your application if you decide that you like Axios or another package more. And you can do other things, for example, check if options.body object, and add the header 'Content-Type: application/json .

0
source

Source: https://habr.com/ru/post/1269318/


All Articles