Search code examples
djangocookiesheaderfetch

Browser not saving cookies but Set-Cookie headers present


I am using React frontend and Django backend and have been struggling for days with authentication. I have boiled down the issue I am having to the browser not setting the cookies it receives from the backend.

When in inspect, I can verify that the Set-Cookie headers are present in the response. They are not appearing in storage though... (the cookies are a csrf token and session id). Other functionalities dependant on these cookies like logout fail. However, when using the Django rest framework interfaces (connecting to the backend urls, e.g., localhost:8000/users/login/), I can perform the login and over there, the cookies appear in storage.

I have tried both fetch and axios, I have included credentials: 'include' and withCredentials: true respectively.

As a final note, when using fetch, I grab the response

fetch(url, { ... })
.then(res => console.log(res.headers.get('Set-Cookie')))

When this prints null, when looping over all present headers I only see two (like application json).

For reference some screenshots.

storage

These are all the cookies present, I am expecting to see csrftoken and session.

The next image shows the headers, there are two Set-Cookie headers with both sessionid and csrftoken.

headers

And finally the cookies from the response

cookies

I have enabled the cors settings in Django, I played around with all pf the SAMESITE and HTTPONLY settings for cookies, I also tried different cors settings, nothing works.


Solution

  • For the browser to accept cookies with samesite=none, then they must also have the secure attribute set and you must use HTTPS.

    Like

    Set-Cookie:SessionCookie=xxxxxxxxxx; SameSite=None; Secure;
    

    To complement this answer, I wrote a blog post that goes into more detail about this topic:Debugging cookie problems