axios icon indicating copy to clipboard operation
axios copied to clipboard

Inconsistent Cookie Behavior with Axios withCredentials in Vue.js

Open firefiber opened this issue 2 years ago • 2 comments

Discussed in https://github.com/axios/axios/discussions/6158

Originally posted by firefiber December 30, 2023

I'm working on a Vue.js frontend and have encountered an odd behavior regarding cookie transmission using Axios. I've set up a custom Axios instance with default configurations and an interceptor to append the CSRF token in headers. The setup is as follows:

// Custom Axios instance
const customAxios = axios.create({
    baseURL: config.BASE,
    withCredentials: true // Global setting
});

// Axios interceptor to add CSRF token
customAxios.interceptors.request.use(function (config) {
    // Interesting things happen
    // ...
    return config;
});

I use this custom instance across various API endpoint functions, like this:

export const userTrainingData = async () => {
    return await customAxios.get(config.BASE_USER_TRAINING, { withCredentials: true });
};

Now, I've observed the following behavior:


Global withCredentials: When withCredentials is true in the Axios instance, and I don't specify it in the endpoint function, all cookies (sessionid and csrftoken) are sent as expected.


Local withCredentials: When I remove the global withCredentials and only specify it in the individual endpoint function, only the csrftoken cookie is sent, but the sessionid cookie is missing. This occurs consistently across different browsers. I've also tested with setting withCredentials inside the interceptor itself, instead of within the create method, which results in the same behaviour (sessionid not sent, csrftoken cookie sent, along with the csrf header).


Headers are all correct (I've checked in the dev tools, access control, path, all the required ones), and the rest of the application behaves as expected. CORS/CSRF settings are all correct. It's not an issue with the cookies being sent back, or being set properly by the browser. It's just this specific discrepancy based on where withCredentials is defined that's weird.


Could anyone explain why this might be happening? Is this expected behavior with Axios, or might there be something I'm overlooking with cookie settings or Axios configuration? Any insights or similar experiences would be greatly appreciated!

Thank you!

firefiber avatar Dec 31 '23 15:12 firefiber

Use other than withcredential

seyoi avatar Jun 13 '24 08:06 seyoi

Digging into my own CSRF issues, maybe the withXSRFToken config is relevant to you?

withXSRFToken: added withXSRFToken option as a workaround to achieve the old withCredentials behavior;

https://github.com/axios/axios/releases/tag/v1.6.2

ptim avatar Jul 18 '24 03:07 ptim