Explain Codes LogoExplain Codes Logo

How can I add a custom HTTP header to an ajax request with javascript or jQuery?

javascript
ajax
headers
javascript-requests
Alex KataevbyAlex Kataev·Jan 24, 2025
TLDR

In jQuery, use $.ajax in conjunction with beforeSend:

$.ajax({ url: 'endpoint', beforeSend: xhr => xhr.setRequestHeader('Magic-Key', 'Opens-the-door') // Yes, that's your magic key! });

In vanilla Javascript, apply setRequestHeader on the XMLHttpRequest object:

let xhr = new XMLHttpRequest(); xhr.open('GET', 'endpoint'); xhr.setRequestHeader('Magic-Key', 'Opens-the-door'); // Same magic key here xhr.send();

Just copy and paste these chunks whenever you need to add custom headers.

Details with jQuery: Individual and Global Headers

Custom Headers on a Single Request

In jQuery, use the headers property in $.ajax to set headers for a singular request:

$.ajax({ url: 'your-endpoint', headers: { 'Custom-Header': 'custom-value' } });

Don’t we all like custom things?

Global Headers on all requests

To set headers that apply to all ajax requests, use the ajaxSetup() function, essentially setting a default header:

$.ajaxSetup({ headers: { 'Default-Header': 'default-value' } });

Because who doesn’t like global domination?

Overriding the default

If you need to override the default headers for any specific request, use the beforeSend function inside the actual $.ajax request:

$.ajax({ url: 'your-endpoint', beforeSend: function(xhr) { xhr.setRequestHeader('Another-Header', 'specific value'); } });

Who said you couldn’t change your stripes?

Please don't forget, ajaxSetup will affect all future ajax requests globally.

Classic JavaScript: Behind the Scene Actions

Create and send XMLHttpRequest

To create a request and add custom headers in vanilla Javascript:

let xhr = new XMLHttpRequest(); // Our transport missile xhr.open('POST', 'your-endpoint'); // Loading coordinates xhr.setRequestHeader('Content-Type', 'application/json'); // Custom bomb shell for special results xhr.setRequestHeader('X-Custom-Header', 'custom-value'); // Making it a bit more personal xhr.send(JSON.stringify({ key: 'value' })); // Fire!

Handling the response

Remember to process the response of your request using the onreadystatechange event:

xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { console.log('Big Bang!', xhr.responseText); // Successful hit! } else { console.error('Missed target!', xhr.status, xhr.statusText); // Missed! } } };

Error trapping

When creating XMLHttpRequest objects, always use try-catch blocks for error management:

try { let xhr = new XMLHttpRequest(); // Setup the request as per your needs } catch (error) { console.error('Fail to launch:', error); }

Browser compatibility

Be mindful of browser compatibility issues, especially for XHR2 features. Refer to resources like MDN Web Docs or the Can I Use platform for the most accurate support data across different browsers.

Lastly, Don't Forget About...

Cross-Origin Resource Sharing

Servicing headers come with CORS considerations. For your headers to work, the server must approve of their receipt or it will block your requests entirely.

POST vs GET

For sending data, a POST request is better suited - allowing for larger request bodies and respecting server-side data integrity.

Verification

Ensure header values are valid and properly formatted. Header misuse is not something you want on your console’s permanent record!

Compatibility

Inform your user on potential browser compatibility issues. A well-developed application is an informative one!

Encapsulation

When setting headers becomes a recurring task, consider encapsulating your logic within a reusable function.