Skip to content
Advertisement

Cookies headers are present but Cookies are not stored in browser

Please help me to figure out why the browser (Chrome and any others) does not set cookies, while Set-Cookie header is present in Response Headers:

Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 345
Content-Type: application/json; charset=utf-8
Date: Sat, 18 Jan 2020 21:15:53 GMT
ETag: W/"159-UXuykOchcveuYBb7xZpN5Luf3jU"
Set-Cookie: jwt=************; Path=/; Expires=Fri, 17 Apr 2020 21:15:53 GMT; HttpOnly
Strict-Transport-Security: max-age=15552000; includeSubDomains
X-Content-Type-Options: nosniff
X-DNS-Prefetch-Control: off
X-Download-Options: noopen
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block

My app running at: http://localhost:8080

Advertisement

Answer

You seem to be using CORS.

To set a cookie with CORS you’ll need to set the withCredentials flag when making the request.

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials

The server will need to return the header Access-Control-Allow-Credentials: true. You’ll also need to change the Access-Control-Allow-Origin: * as you can’t use wildcards on a request that uses credentials.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

As of Chrome 80 you’ll also need to set SameSite=None and Secure directives on the cookie.

https://www.chromestatus.com/feature/5088147346030592
https://www.chromestatus.com/feature/5633521622188032
https://www.troyhunt.com/promiscuous-cookies-and-their-impending-death-via-the-samesite-policy/

To check whether a cookie is set you cannot simply open Application > Cookies to check for the cookie. The cookie will be set for localhost:3000 so looking at the cookies for localhost:8080 won’t show it. Instead you’ll need to open another tab that points to localhost:3000 and then look at Application > Cookies in there. Cookies are shared between tabs so you’ll still be able to see the cookies set by the original localhost:8080 tab.

Getting cross-origin cookies to work with Safari is a separate struggle. If you need to support Safari I suggest you do some research into that as you may need to adopt a different strategy altogether.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement