Set default header for every fetch() request Set default header for every fetch() request express express

Set default header for every fetch() request


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.


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

var Url = require("url")var assign = require("oolong").assignvar merge = require("oolong").mergevar PARSE_QUERY = falsevar 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


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