Source:  Twitter logo

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.

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.

32 users liked answer #0dislike answer #032
underblob profile pic
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

10 users liked answer #1dislike answer #110
Hugo Chevalier profile pic
Hugo Chevalier

Andri Möll created a FetchDefaults.js mixin for fetch that sets fetch defaults:

var Url = require("url")
var assign = require("oolong").assign
var merge = require("oolong").merge
var PARSE_QUERY = false
var PROTOCOL_RELATIVE = true // Enable //example.com/models to mimic browsers.

exports = module.exports = function(fetch, rootUrl, defaults) {
  if (typeof rootUrl === "string") rootUrl = parseUrl(rootUrl)
  else defaults = rootUrl, rootUrl = null
  return assign(exports.fetch.bind(null, fetch, rootUrl, defaults), fetch)
}

exports.fetch = function(fetch, rootUrl, defaults, url, opts) {
  if (rootUrl != null) url = rootUrl.resolve(url)
  if (typeof defaults === "function") defaults = defaults(url, opts)
  return fetch(url, opts == null ? defaults : merge({}, defaults, opts))
}

function parseUrl(url) {
  return Url.parse(url, PARSE_QUERY, PROTOCOL_RELATIVE)
}

Distributed under AGPL-3.0-only license

10 users liked answer #2dislike answer #210
Nantaphop profile pic
Nantaphop

A quick and unrecommended hack is to redefine the default .fetch() function:

const oldFetch = window.fetch;
window.fetch = function() {
    arguments[1].headers = { 'blahblah' : 'blabla' };
    return oldFetch.apply(window, arguments);
}

Code is untested and unfinished. If you decide to use this answer, check arguments.length, add code to preserve existing headers, etc. etc. I'm just providing the direction for further exploration.

0 users liked answer #3dislike answer #30
Alex from Jitbit profile pic
Alex from Jitbit

You can override default fetch api:

    var originalFetch = window.fetch;
    window.fetch = function (input, init) {
        if (!init) {
            init = {};
        }
        if (!init.headers) {
            init.headers = new Headers();
        }
        if (init.headers instanceof Headers) {
            init.headers.append('MyHeader', 'Value');
        } else {
            init.headers['MyHeader'] = 'Value';
        }
        return originalFetch(input, init);
    };
0 users liked answer #4dislike answer #40
iuridiniz profile pic
iuridiniz

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).