Automatically Adding Default Headers to ALL Fetch (AJAX) Requests

Below is an unobtrusive way to ensure AJAX headers are set with every fetch() request, which compliments our post regarding fetch() wrappers.

const originalFetch = fetch
fetch = ((url, options) => {
	if (!options) options = {}
	Object.assign(options, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
	const promise = originalFetch(url, options).catch(error => { console.error(error) })
	return promise
})

Now every fetch() request includes the X-Requested-With: XMLHttpRequest header.

We ultimately ended up with the following alternative to avoid replacing other existing headers.

if (!options) options = {}
if (!options.headers) options.headers = {}
options.headers['X-Requested-With'] = 'XMLHttpRequest'

Fairly handy when you depend on something like CodeIgniter’s isAJAX() method.

Leave a Reply

Your email address will not be published. Required fields are marked *