370

Does anyone know how to add or create a custom HTTP header using JavaScript or jQuery?

Kamil Kiełczewski
93.6k34 gold badges401 silver badges375 bronze badges
asked Oct 7, 2011 at 11:51
0

9 Answers 9

656

There are several solutions depending on what you need...

If you want to add a custom header (or set of headers) to an individual request then just add the headers property:

// Request with custom header
$.ajax({
 url: 'foo/bar',
 headers: { 'x-my-custom-header': 'some value' }
});

If you want to add a default header (or set of headers) to every request then use $.ajaxSetup():

$.ajaxSetup({
 headers: { 'x-my-custom-header': 'some value' }
});
// Sends your custom header
$.ajax({ url: 'foo/bar' });
// Overwrites the default header with a new header
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });

If you want to add a header (or set of headers) to every request then use the beforeSend hook with $.ajaxSetup():

$.ajaxSetup({
 beforeSend: function(xhr) {
 xhr.setRequestHeader('x-my-custom-header', 'some value');
 }
});
// Sends your custom header
$.ajax({ url: 'foo/bar' });
// Sends both custom headers
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });

Edit (more info): One thing to be aware of is that with ajaxSetup you can only define one set of default headers and you can only define one beforeSend. If you call ajaxSetup multiple times, only the last set of headers will be sent and only the last before-send callback will execute.

answered Feb 1, 2013 at 22:02
Sign up to request clarification or add additional context in comments.

15 Comments

What happens if I define a new beforeSend when doing a $.ajax?
You can only define one beforeSend callback. If you call $.ajaxSetup({ beforeSend: func... }) twice then the second callback will be the only one that fires.
Updated my answer to add more details about ajaxSetup.
Looks like it doesn't work with CORS Request (every browser). Is there a work around ?
@Si8, that looks like a cross domain issue to me. You can't make a request from one domain to another. Try looking into CORS and see if that helps.
|
57

Or, if you want to send the custom header for every future request, then you could use the following:

$.ajaxSetup({
 headers: { "CustomHeader": "myValue" }
});

This way every future ajax request will contain the custom header, unless explicitly overridden by the options of the request. You can find more info on ajaxSetup here

answered Jul 16, 2012 at 7:50

2 Comments

Where i really want to accomplish this, this doesn't seem to actually work.
Well you should make sure that the ajaxSetup is called before the actual ajax call. I don't know of any other reason why this wouldn't work :)
30

You can also do this without using jQuery. Override XMLHttpRequest's send method and add the header there:

XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(vData) {
 this.setRequestHeader('x-my-custom-header', 'some value');
 this.realSend(vData);
};
XMLHttpRequest.prototype.send = newSend;
answered May 25, 2016 at 11:04

Comments

22

Assuming JQuery ajax, you can add custom headers like -

$.ajax({
 url: url,
 beforeSend: function(xhr) {
 xhr.setRequestHeader("custom_header", "value");
 },
 success: function(data) {
 }
});
answered Oct 7, 2011 at 11:58

Comments

21

Here's an example using XHR2:

function xhrToSend(){
 // Attempt to creat the XHR2 object
 var xhr;
 try{
 xhr = new XMLHttpRequest();
 }catch (e){
 try{
 xhr = new XDomainRequest();
 } catch (e){
 try{
 xhr = new ActiveXObject('Msxml2.XMLHTTP');
 }catch (e){
 try{
 xhr = new ActiveXObject('Microsoft.XMLHTTP');
 }catch (e){
 statusField('\nYour browser is not' + 
 ' compatible with XHR2'); 
 }
 }
 }
 }
 xhr.open('POST', 'startStopResume.aspx', true);
 xhr.setRequestHeader("chunk", numberOfBLObsSent + 1);
 xhr.onreadystatechange = function (e) {
 if (xhr.readyState == 4 && xhr.status == 200) {
 receivedChunks++;
 }
 };
 xhr.send(chunk);
 numberOfBLObsSent++;
}; 

Hope that helps.

If you create your object, you can use the setRequestHeader function to assign a name, and a value before you send the request.

Misha Reyzlin
13.9k4 gold badges56 silver badges65 bronze badges
answered Oct 7, 2011 at 11:58

4 Comments

While this may have been correct in 2011, it's generally a good idea to not reinvent the wheel, and instead use an AJAX library like Zepto or jQuery.
Unless you are trying to add a header to an existing XHR2 call and don't want to start rewriting it all to use jQuery just for that... At which point, @gryzzly has the only viable answer.
@AliGajani The problem is that certain applications or libraries (like THREE.js) don't use $.ajax* functions b/c they don't depend on jQuery and instead use XHR so this is the only valid option in those cases.
@AliGajani Additionally, it's not just the network load time but the parsing time of the library. Plus, if you are not careful with what dependencies you add, you can quickly get a project with too many dependencies
19

You should avoid the usage of $.ajaxSetup() as described in the docs. Use the following instead:

$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
 jqXHR.setRequestHeader('my-custom-header', 'my-value');
});
answered Jul 12, 2015 at 19:39

Comments

6

Assuming that you mean "When using ajax" and "An HTTP Request header", then use the headers property in the object you pass to ajax()

headers(added 1.5)

Default: {}

A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

http://api.jquery.com/jQuery.ajax/

answered Oct 7, 2011 at 11:56

Comments

3

"setRequestHeader" method of XMLHttpRequest object should be used

http://help.dottoro.com/ljhcrlbv.php

answered Oct 7, 2011 at 11:59

Comments

0

Use fetch

fetch("https://...", { headers: { "myHeader1": "myValue", ... }})

fetch("https://httpbin.org/status/200", { headers: { 
 "a-first--header": "val 1", 
 "a-second-header": "val 2"
}});
//Open chrome console> network tab to see request headers

answered Apr 9, 2019 at 3:47

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.