X-XSRF-TOKEN header automatic generation in [email protected]

459 views Asked by At

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?

1

There are 1 answers

0
devgioele On

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.

axios.defaults.baseURL = BACKEND_URL

const XSRF_TOKEN_HEADER_NAME = 'X-XSRF-TOKEN'
const XSRF_TOKEN_COOKIE_NAME = 'XSRF-TOKEN'

axios.defaults.xsrfHeaderName = XSRF_TOKEN_HEADER_NAME
axios.defaults.xsrfCookieName = XSRF_TOKEN_COOKIE_NAME

// Attach XSRF token to requests using the base url
axios.interceptors.request.use((config) => {
  if (!config.url?.startsWith('http')) {
    const token = getCookie(XSRF_TOKEN_COOKIE_NAME)
    if (token) {
      config.headers[XSRF_TOKEN_HEADER_NAME] = token
    }
  }
  return config
})

How to read cookies in a correct and performant way is another topic.