Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default header for every fetch() request

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

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

Setting the headers in a fetch request would then look like this:

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

But there has to be a better way to do this. I'm currently developing a React/Redux/Express app if that is of any help.

like image 361
eRodY Avatar asked Jun 29 '17 08:06

eRodY


People also ask

How do I set the default header in Fetch?

create({ baseURL: 'http://exemple.com' }); And when you get your token, u just have to call the function setAuthorization. Pierre C. You can use axios to set your authorization headers and then use normal fetch request and the headers will be set for the fetch request as well.

How do you set header in fetch react?

To use an authorization header with fetch in React Native, we set the headers option when we call fetch . fetch(url, { method: "post", headers: new Headers({ Authorization: "Basic " + btoa("username:password"), "Content-Type": "application/x-www-form-urlencoded", }), body: "foo=1&bar=2", });

How do I send authorization header in Fetch?

You can pass HTTP headers to the fetch() request as the second parameter. For example, to pass the Bearer Token Authorization Header, call fetch() with the {headers: {Authentication: 'Bearer Token'}} parameter. The example below shows how to send multiple headers to the server, including a custom HTTP header.


2 Answers

Creating a fetch wrapper could 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 switch your request client easily for all the calls in your application if you decide you like Axios or other package better. And you can do other things like check if options.body is an object and add the 'Content-Type: application/json header.

like image 58
underblob Avatar answered Sep 21 '22 04:09

underblob


You could 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, u just have to call the function setAuthorization.

Source: Axios README.md

like image 35
Hugo Chevalier Avatar answered Sep 22 '22 04:09

Hugo Chevalier