For some reason my browser (I've tried several) is not setting cookies even though a valid set-cookie response is being returned by the server when the GET call is made via Ajax using the fetch api to make the request
If I make the identical GET call via just putting the URL in the browser, the (identical) set-cookie response headers are respected by the browser and the cookies are saved.
I've inspected the request and response headers via LiveHeaders and the Chrome network inspector and there is no difference.
EDIT: To clarify, this is NOT a problem with ajax sending cookies to the server. It is a problem where the cookies are not saved by the browser at all when a response comes back with valid set-cookies headers (which according to documentation should be respected whether ajax or not).
Yes, you can set cookie in the AJAX request in the server-side code just as you'd do for a normal request since the server cannot differentiate between a normal request or an AJAX request.
The Set-Cookie header is sent by the server in response to an HTTP request, which is used to create a cookie on the user's system. The Cookie header is included by the client application with an HTTP request sent to a server, if there is a cookie that has a matching domain and path.
The Set-Cookie HTTP response header is used to send a cookie from the server to the user agent, so that the user agent can send it back to the server later. To send multiple cookies, multiple Set-Cookie headers should be sent in the same response.
Set-Cookie is a forbidden response header name. You cannot read it using browser-side JavaScript. If you need to pass that information to your JavaScript, then you need to have the server use some other mechanism (such as a different header or part of the response body).
After much head banging, I solved this issue by setting the 'credentials' property of the request to 'include'. I was under the impression that this only controlled the sending of cookies to the server on fetch requests, but apparently, at least in the implementation I am using, if not set it also means that cookies will not be saved if they are sent back from the server.
From the spec at https://fetch.spec.whatwg.org/
A request has an associated credentials mode, which is "omit", "same-origin", or "include". Unless stated otherwise, it is "omit".
Request's credentials mode controls the flow of credentials during a fetch. When request's mode is "navigate", its credentials mode is assumed to be "include" and fetch does not currently account for other values. If HTML changes here, this standard will need corresponding changes.
Credentials are HTTP cookies, TLS client certificates, and authentication entries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With