'React doesn't set cookies but Postman does?

I have a spring boot backend that allows a user to login.

When I use postman to send a json payload to login in a user it returns the correct response with a cookie for a JSESSION.

Postman details with response and cookie

When I send the payload in react (axios) I don't see the cookie for the JSESSION anywhere but the response is still okay ?

const API_URL = "http://localhost:8080/api/auth/";


login(uniqueId: string, password: string) {
    return axios.post(API_URL + "login", JSON.stringify({
            "uniqueId": uniqueId,
            "password": password
        }), 
        {
            headers: {
                'Content-Type': 'application/json',
                'withCredentials': 'true'
            }
        })
        .then(response => {
            console.log(response);
            return response;
        }).catch(error => {
            return error.response
    });
}

Chrome tab with response and no cookie



Solution 1:[1]

'withCredentials': 'true' shoud be outside of headers (Request Config documentstion)

In your case it would be:

const API_URL = "http://localhost:8080/api/auth/";


login(uniqueId: string, password: string) {
    return axios.post(API_URL + "login", JSON.stringify({
            "uniqueId": uniqueId,
            "password": password
        }), 
        {
            withCredentials: true,
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            console.log(response);
            return response;
        }).catch(error => {
            return error.response
    });
}

another solution is create instance axios with parametr withCredentials: true (creating axios instance).

const BASE_URL = "http://localhost:8080/api/";
const api = axios.create({
baseURL: BASE_URL,
withCredentials: true,
headers: {'Content-Type': 'application/json'}
});

and then you can do:

 return api.post("/auth/login", JSON.stringify({
            "uniqueId": uniqueId,
            "password": password
        })) .then(response => {
            console.log(response);
            return response;
        }).catch(error => {
            return error.response
    });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrey Balabanov