I get frustrated populating the X-XSRF-TOKEN header based on the value of the XSRF-TOKEN cookie, and then send the request to a trusted host.
That issue comes with the breaking change in axios library 1.5.1=>1.6.0, where the automatic population was reduced to the same origin host.
Now I added the custom logic when creating the axios instance
import axios from 'axios';
const instance = axios.create();
const hosts = ['https://example.com', 'https://api.example.com'];
instance.interceptors.request.use((config) => {
if (hosts.some(host => config.url.startsWith(host))) {
const token = getCookie('XSRF-TOKEN');
if (token) {
config.headers['X-XSRF-TOKEN'] = token;
}
}
return config;
});
Now waiting for 1.6.1, where such logic may be implemented.
Do you know a better solution?
If you make all requests using a base url, you can make sure the XSRF token is attached to requests using the base url only. Relative paths are going to use the base url, while absolute paths are not.
How to read cookies in a correct and performant way is another topic.