Search code examples
javascriptfirefoxcookiesfastapifetch-api

Cannot access cookie in JavaScript, document.cookie is empty


I'm making a project with authorization with cookies. Access token with user name are being sent to js client by server and in network monitor in browser I can see the cookies being sent with requests from fetch. Upon page reload I want to read saved cookies and if they are present, keep then for user to be logged in.

The problem is Storage->Cookies in Firefox is empty and document.cookie returns empty string.

Backend - Python FastAPI, cookies are set this way:

login_manager.set_cookie(response, token) # httponly=True
response.set_cookie("blueberry-user", data.login, httponly=False, expires=timedelta(days=1))

Code in js frontend which sends an authorization request and receives cookie:

let response = await fetch(backendUrl + handleUrl, {
      method: "post",
      mode: "cors",
      credentials: "include",
      body: JSON.stringify({ login: login, password: password }),
      headers: {
        "Content-Type": "application/json",
      },
    });

Cookies are being set and sent with the next request: img img

At first I thought the problem was with httponly, but when I turned it of for setting the cookies it didn't help.


Solution

  • The problem solved by adding domain="blueberry.adefe.xyz" to the cookie in response. Backend URL: api.blueberry.adefe.xyz, frontend URL: blueberry.adefe.xyz, maybe the problem was about cross-origin cookies.

    The full code for adding a cookie to FastAPI response:

    @router.post("/user/login", tags=["Authentication"])
    def post_login(data: AuthRequestModel, response: Response):
     ...
     response.set_cookie(
       "blueberry-user",
       data.login,
       httponly=False,
       expires=timedelta(days=1),
       domain="blueberry.adefe.xyz",
      )
      response.status_code = status.HTTP_200_OK
      return response
    

    Still don't understand why the cookies were automatically stored and sent with the requests, but were not accessible in js and in browser