To allow receiving & sending cookies by a CORS request successfully, do the following.
Back-end (server):
Set the HTTP header Access-Control-Allow-Credentials
value to true
.
Also, make sure the HTTP headers Access-Control-Allow-Origin
and Access-Control-Allow-Headers
are set and not with a wildcard *
.
Recommended Cookie settings per Chrome and Firefox update in 2021: SameSite=None
and Secure
. See MDN documentation
For more info on setting CORS in express js read the docs here
Front-end (client): Set the XMLHttpRequest.withCredentials
flag to true
, this can be achieved in different ways depending on the request-response library used:
jQuery 1.5.1 xhrFields: {withCredentials: true}
ES6 fetch() credentials: 'include'
axios: withCredentials: true
Avoid having to use CORS in combination with cookies. You can achieve this with a proxy.
If you for whatever reason don't avoid it. The solution is above.
It turned out that Chrome won't set the cookie if the domain contains a port. Setting it for localhost
(without port) is not a problem. Many thanks to Erwin for this tip!