-1

I want to set a customer header from browser similar to what mod plugin does on chrome, is there any way to set a header from javascript client side?

Based on a condition, I want to set a header so that all subsequent browser requests will have this header value.

I know this from server side, but wanted to know if it is possible from client side.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
kobe
  • 15,671
  • 15
  • 64
  • 91
  • All subsequent requests in what scope? For that page? – jonrsharpe Jul 24 '20 at 16:47
  • for example page has many static includes like javascripts/css/images, when browser makes subsequent requests for them, i want to do some logic based on the header value – kobe Jul 24 '20 at 16:49
  • I know its a different idea, but you could use local storage. It seems odd to want to change the header so you can use logic on it later, when local storage/cookies/sessions are used for just that. – imvain2 Jul 24 '20 at 16:51
  • What do you mean "subsequent" requests for static includes? Do you mean on some arbitrary future page load? They might not even be requested again, if the browser caches them. Have you looked into service workers, e.g. https://stackoverflow.com/a/56941460/3001761? – jonrsharpe Jul 24 '20 at 16:53
  • based on header value, I want to route few things differently on ngnix. @imv – kobe Jul 24 '20 at 16:54
  • local storage doesn't work, since those values are not avaiable on subsequent requests. – kobe Jul 24 '20 at 16:55

1 Answers1

0

A simple way to do this in vanilla JS is to augment the XMLHTTPRequest.prototype.send method.

You would do something like

const defaultSend = XMLHTTPRequest.prototype.send;
XMLHTTPRequest.prototype.send = function (data) {
  this.setRequestHeader('SOME-CUSTOM-HEADER', 'header-value');
  defaultSend.call(this, data);
};

While this works, it's like using a nuke when you need a hammer. It pollutes ALL of the following XHRs run in the context of that particular window. While you could do domain level filtering, but I find that it's not worth the trouble.

If you are using client XHR libraries like axios, they will often provide a better and more contextual way. For example, in case of axios, you could do something like

const client = axios.createClient();
client.interceptors.request.use(config => {
  config.headers['SOME-CUSTOM-HEADER'] = 'header-value';
  return config;
});
client.get('/some-url', params); // this will have the custom header that you injected

EDIT: One caveat here is that this only affects XHRs, not form submissions or asset calls.

Achrome
  • 7,773
  • 14
  • 36
  • 45
  • This is not while making an API call, just want to set the header from javascript side. So that any subseqent requests will have it. – kobe Jul 24 '20 at 17:18
  • for example how he is doing from browser https://github.com/bewisse/modheader – kobe Jul 24 '20 at 17:19