skip to Main Content

My setup is the following:

  • (http://localhost:39500) ASP.NET Core backend
  • (http://localhost:3000) React frontend

I am sending an API request from my frontend to backend. The backend responds with a Set-Cookie header but the cookie is not being set in the browser.

Raw headers:

Response headers

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Vary: Origin
Server: Microsoft-IIS/10.0
Set-Cookie: PT=longstringhere; expires=Tue, 27 Sep 2022 04:56:03 GMT; path=/; httponly
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Credentials: true
X-Powered-By: ASP.NET
Date: Tue, 27 Sep 2022 03:56:03 GMT

Request headers

POST /account/login HTTP/1.1
Host: localhost:39500
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:105.0) Gecko/20100101 Firefox/105.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: http://localhost:3000/
content-type: application/json
credentials: include
Content-Length: 46
Origin: http://localhost:3000
Connection: keep-alive
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site

When inspecting my browser cookie storage (Firefox and Chrome) I have no cookies being set, additionally no cookies are being sent to my backend as well.

Any ideas or pointers why this is happening?

2

Answers


  1. Chosen as BEST ANSWER

    In my frontend I was including into my headers "credentials": "include" which is not the same as setting the credentials to include in fetch. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch


  2. Frontend and backend run at different hosts. Set-Cookie saves the cookie for the given host, i.e. localhost:39500, but your frontend sits at host localhost:3000. Try inspecting cookies for localhost:39500 (for example in Chrome>Settings>Cookies and other site data>See all cookies and site data or with Postman), you will see that there is a cookie set. In production, you could serve your frontend from your backend, which will both be the same host. You could also put your frontend or backend under a subdomain, which can also be set as a cookie. See here for more info: Share cookie between subdomain and domain

    EDIT: For development, you can use a proxy (as described in https://create-react-app.dev/docs/proxying-api-requests-in-development/)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search