Inertia: How to add custom headers?

Created on 8 Jul 2020  路  6Comments  路  Source: inertiajs/inertia

Hi!

I've already searched through issues and code base, but I cannot find a way to pass custom headers globally or per Inertia.visit call. I am using Inertia in React.

Thanks!
Kate

Most helpful comment

I use both default headers and interceptors and it works. JavaScript modules work as singletons, importing them return always the same export.

So unless you manually instantiate with axios.create(), any global headers or interceptors will apply to the same axios instance inertia uses.

Here is an excerpt from a project I am working on:

~~~js
import axios from 'axios';
import {publish} from '@/js/libs/bus.js';

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

axios.interceptors.request.use(
function (config) {
publish('request:started', config);

    return config;
},

function (error) {
    publish('request:ended');

    return Promise.reject(error);
},

);

// response interceptor omitted for brevity
~~~

bus is a global event bus I use in this project.

All 6 comments

Since inertia uses axios under the hood you can set global default headers for your requests:

https://github.com/axios/axios#config-defaults

For finer-grained control you could use interceptors to add headers to requests before they are sent:

https://github.com/axios/axios#interceptors

Okay thanks :) Are you sure this is working? Do you have an example? Because I have to install axios separately. I am then operating on a different instance.

I use both default headers and interceptors and it works. JavaScript modules work as singletons, importing them return always the same export.

So unless you manually instantiate with axios.create(), any global headers or interceptors will apply to the same axios instance inertia uses.

Here is an excerpt from a project I am working on:

~~~js
import axios from 'axios';
import {publish} from '@/js/libs/bus.js';

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

axios.interceptors.request.use(
function (config) {
publish('request:started', config);

    return config;
},

function (error) {
    publish('request:ended');

    return Promise.reject(error);
},

);

// response interceptor omitted for brevity
~~~

bus is a global event bus I use in this project.

@rodrigopedra Could this issue be closed now?

Let's maybe leave it open, because I'm considering removing Axios entirely from Inertia.js, and if we do that, we'd want to provide another way to do this. 馃憤

This is now possible, thanks to the work of @claudiodekker (#202).

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ambethia picture ambethia  路  5Comments

MichaelDeBoey picture MichaelDeBoey  路  4Comments

sebastiandedeyne picture sebastiandedeyne  路  6Comments

ninjaparade picture ninjaparade  路  4Comments

TimVanHerwijnen picture TimVanHerwijnen  路  5Comments