-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.

6
  • All subsequent requests in what scope? For that page? Commented Jul 24, 2020 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 Commented Jul 24, 2020 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. Commented Jul 24, 2020 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. stackoverflow.com/a/56941460/3001761? Commented Jul 24, 2020 at 16:53
  • based on header value, I want to route few things differently on ngnix. @imv Commented Jul 24, 2020 at 16:54

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
for example how he is doing from browser github.com/bewisse/modheader

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.