Home >Backend Development >Python Tutorial >Why Doesn't My FastAPI Backend Send Cookies to My React Frontend?

Why Doesn't My FastAPI Backend Send Cookies to My React Frontend?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-02 03:33:17945browse

Why Doesn't My FastAPI Backend Send Cookies to My React Frontend?

FastAPI Cannot Send Cookies to React Frontend

Overview

FastAPI is a popular Python framework for creating APIs. However, some users have reported issues with FastAPI not returning cookies to React frontend applications.

Problem

Why doesn't FastAPI return cookies to React frontend apps?

Code Example

Here is a code snippet illustrating the issue:

@router.post("/login")
def user_login(response: Response, username: str = Form(), password: str = Form(), db: Session = Depends(get_db)) -> dict:
    # Database operations omitted for brevity
    access_token = create_access_token(data={"sub": user.mobile_number})
    response.set_cookie(key="fakesession", value="fake-cookie-session-value")
    return {"status": "success"}

When sending a login request from Swagger UI, the cookie appears in the response headers. However, from a React app, no cookie is returned.

Solution

There are two steps to resolve this issue:

  1. Set Cookies Correctly:

    • Ensure there are no errors in the FastAPI request and a success response is received.
    • Set the cookie correctly using response.set_cookie(...).
  2. Configure CORS and Credentials:

    • Allow CORS requests by setting origins and allow_credentials=True in the CORSMiddleware.
    • In the React app, set withCredentials: true in Axios requests to send cookies.

Explanation

  1. Cookie Setting:

    • Verify that the cookie is being set correctly in the FastAPI response. Ensure the correct key, value, httponly, and other relevant parameters are set.
  2. Cross-Origin Resource Sharing (CORS):

    • Since React and FastAPI are on different ports, CORS requests are being made.
    • To allow cookies with CORS, the server must allow specific origins via Access-Control-Allow-Origin response headers.
    • In FastAPI, use CORSMiddleware with allow_credentials=True.
  3. Credentials in Request:

    • In React, set withCredentials: true in Axios requests.
    • This informs the browser to send cookies in subsequent requests to the FastAPI server.

Important Note

Explicitly specify the allowed origins to prevent unauthorized access to cookies. By default, only certain communication types are allowed in CORS requests without credentials, excluding cookies.

The above is the detailed content of Why Doesn't My FastAPI Backend Send Cookies to My React Frontend?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn