React: Fix issue with Session changing after every request

Are you using React and Axios?

Are you having a mysterious issue with session id changing on every new request, thus causing users to be disconnected upon page refresh?

Yeah, that happened to me too. It’s because you’re not sending the cookies and authentication headers with your request. To include those, simply add the following line in any file where you’ve imported Axios:

axios.defaults.withCredentials = true;

Alternatively, you can specify whether an Axios request should send the request withCredentials:

axios("http://example.com/something", {
    method: "POST",
    data: { message: "hi lol" },
    withCredentials: true
});

If you don’t send the cookie which contains the session id, the server won’t know if there’s already an existing session, and may potentially generate a new session for you every time a request is sent.


Update

Many years later, I realize that this was really just a misunderstanding about what determines when to send a cookie (or even authorization headers) along with a request. When a request is cross-site, cookies are not sent to that external website by default, which is in fact a very important security feature, since it protects you from having your session hijacked. All in all, this doesn’t just apply to Axios - it applies to all HTTP clients that.

The only way to make a HTTP request in JavaScript is by using XMLHttpRequest, which has a withCredentials boolean that decides whether the cookies should be sent with the request, and because withCredentials is false by default when the request is cross-origin while true by default when the request is from the same origin, then it’s very possible what some people will never encounter this issue.

When I first encountered that issue, I was extremely confused - it worked locally (the front-end and the back-end were both running locally), but not in production. Looking back at it, the issue was that running the front-end and back-end locally meant that they were on the same origin, whereas in production, both the front-end and back-end were on different origins, which made withCredentials default to true locally, but to false in production.

While building a website with a simple architecture, this isn’t an issue because both the front-end and the back-end are interwoven. The same cannot be said when your architecture is made up of multiple back-ends and front-ends.

I’m just rambling on at this point, I just wanted a valid reason to not get rid of this article.