'How can I retain the cookies in the response?

const setContext = require('apollo-link-context');
const axios = require('axios')

const req = async () => {

    const dotenv = require("dotenv")
    dotenv.config()

    const res = await axios.post(process.env.URL, {
        email: process.env.EMAIL,
        password: process.env.PASSWORD}, {
            headers: {
                'content-type' : 'application/x-www-form-urlencoded'
            }
        }, {withCredentials: true}
    );
    console.log(res.headers['set-cookie']);
}

req();

Does anyone know how to retain the cookies in the response? There are two specific cookies in the response I want to save in a variable so I can use for another request.

I have tried reading documentation and using other libraries for requests, but nothing works.



Solution 1:[1]

You don't have to save the cookies in the header explicitly in order to use them in your subsequent requests. They are automatically stored in the browser sent along with the subsequent requests. For that to happen however you need to set the {withCredentials: true} on your subsequent request and the server must have the response headers with the property ' ACCESS-CONTROL-ALLOW-CREDENTIALS': true. Now Depending on your backend. server, you can find cookie parsing libraries like js-cookie. which will allow you to easily read and store the cookies in a variable. But if for some specific reason you want to set it as a header in your subsequent request explicitly you can do so using the code below. However, keep in mind that you cannot read/write/edit httpOnly flagged cookies from the browser

    const cookie = require("js-cookie");
    (async()=>{
        const res = await axios.post(process.env.URL, {
        email: process.env.EMAIL,
        password: process.env.PASSWORD}, {
            headers: {
                'content-type' : 'application/x-www-form-urlencoded'
            }
        }, {withCredentials: true}
    );
    //assuming the server sets the cookie in its response headers during your 1st request
    let mycookieValue = cookie.get("my-cookie-key");
    axios.get(second-request-url,{headers:{mycookieValue}});})();

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