Handling cookies with axios

Recently, while developing a website , I ran across an issue while making post request using axios. The general format for making the request is:

axios.post(url, data, config)
.then(function(response) {
<your_code>
})
.catch(function(error) {
<your_code>
});

The problem I was facing was that the cookie wasn’t reaching the backend. After much pondering and deliberation, I found out that the cookie was absent in the request headers. While googling, I came across several solutions. Some of which were:

  • To stringify the data before sending. I tried both JSON.stringify and queryString.stringify, but it did not work :(
JSON.stringify()
queryString.stringify()
  • Setting {withCredentials: true} while making request. While searching, I came across a solution which stated to set withCredentials:true, while making a request. It should be noted that we should set withCredentials: true in config as a different key: value pair. For eg:
config = { headers: {'Content-Type' : 'application/json'},
withCredentials: true
}

But even this method failed.

  • After even more research, I observed that setting Cookie as header and passing the cookie in it was a method suggested.
Cookie: name=value; name2=value2; name3=value3;

But still no luck. I got an error on console. After researching, I found out that we cannot set Cookie as header according to new W3C rules, owing to security reasons.

At this point, I was planning to move to tokens instead of cookies. But then after a whole ton of trial and error, I finally decoded the way!!

Setting Authorization as header and passing the cookie value in it, in this form:

headers: {Authorization: `Bearer ${cookie_value}`}

After this just make sure your backend allows the header Authorization and voila cookie passed!!!

This process of configuring the right way was extremely time taxing and complicated but with a whole ton of trial and error, I am really happy to have solved the issue.

So, I decided to write an article on it and share my experience, providing the correct way to do it, so that in the future, developers don’t have to spend time configuring the solution to this problem. Hope it helps someone :)